blob: 7dc2315eb4ae34aba200dc5a4157600af1b90e02 [file] [log] [blame]
Andrew Trick6a50baa2012-05-17 22:37:09 +00001//===- MachineScheduler.cpp - Machine Instruction Scheduler ---------------===//
Andrew Tricke77e84e2012-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 Trick02a80da2012-03-08 01:41:12 +000017#include "llvm/CodeGen/MachineScheduler.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/OwningPtr.h"
19#include "llvm/ADT/PriorityQueue.h"
20#include "llvm/Analysis/AliasAnalysis.h"
21#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Jakub Staszakdf17ddd2013-03-10 13:11:23 +000022#include "llvm/CodeGen/MachineDominators.h"
23#include "llvm/CodeGen/MachineLoopInfo.h"
Andrew Trick736dd9a2013-06-21 18:32:58 +000024#include "llvm/CodeGen/MachineRegisterInfo.h"
Andrew Tricke77e84e2012-01-13 06:30:30 +000025#include "llvm/CodeGen/Passes.h"
Andrew Trick05ff4662012-06-06 20:29:31 +000026#include "llvm/CodeGen/RegisterClassInfo.h"
Andrew Trickcd1c2f92012-11-28 05:13:24 +000027#include "llvm/CodeGen/ScheduleDFS.h"
Andrew Trick61f1a272012-05-24 22:11:09 +000028#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
Andrew Tricke77e84e2012-01-13 06:30:30 +000029#include "llvm/Support/CommandLine.h"
30#include "llvm/Support/Debug.h"
31#include "llvm/Support/ErrorHandling.h"
Andrew Trickea9fd952013-01-25 07:45:29 +000032#include "llvm/Support/GraphWriter.h"
Andrew Tricke77e84e2012-01-13 06:30:30 +000033#include "llvm/Support/raw_ostream.h"
Jakub Staszak80df8b82013-06-14 00:00:13 +000034#include "llvm/Target/TargetInstrInfo.h"
Andrew Trick7ccdc5c2012-01-17 06:55:07 +000035#include <queue>
36
Andrew Tricke77e84e2012-01-13 06:30:30 +000037using namespace llvm;
38
Andrew Trick7a8e1002012-09-11 00:39:15 +000039namespace llvm {
40cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
41 cl::desc("Force top-down list scheduling"));
42cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
43 cl::desc("Force bottom-up list scheduling"));
44}
Andrew Trick8823dec2012-03-14 04:00:41 +000045
Andrew Tricka5f19562012-03-07 00:18:25 +000046#ifndef NDEBUG
47static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
48 cl::desc("Pop up a window to show MISched dags after they are processed"));
Lang Hamesdd98c492012-03-19 18:38:38 +000049
50static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
51 cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
Andrew Tricka5f19562012-03-07 00:18:25 +000052#else
53static bool ViewMISchedDAGs = false;
54#endif // NDEBUG
55
Andrew Trickb6e74712013-09-04 20:59:59 +000056static cl::opt<bool> EnableRegPressure("misched-regpressure", cl::Hidden,
57 cl::desc("Enable register pressure scheduling."), cl::init(true));
58
Andrew Trickc01b0042013-08-23 17:48:43 +000059static cl::opt<bool> EnableCyclicPath("misched-cyclicpath", cl::Hidden,
Andrew Trick6c88b352013-09-09 23:31:14 +000060 cl::desc("Enable cyclic critical path analysis."), cl::init(true));
Andrew Trickc01b0042013-08-23 17:48:43 +000061
Andrew Tricka7714a02012-11-12 19:40:10 +000062static cl::opt<bool> EnableLoadCluster("misched-cluster", cl::Hidden,
Andrew Trick108c88c2012-11-13 08:47:29 +000063 cl::desc("Enable load clustering."), cl::init(true));
Andrew Tricka7714a02012-11-12 19:40:10 +000064
Andrew Trick263280242012-11-12 19:52:20 +000065// Experimental heuristics
66static cl::opt<bool> EnableMacroFusion("misched-fusion", cl::Hidden,
Andrew Trick108c88c2012-11-13 08:47:29 +000067 cl::desc("Enable scheduling for macro fusion."), cl::init(true));
Andrew Trick263280242012-11-12 19:52:20 +000068
Andrew Trick48f2a722013-03-08 05:40:34 +000069static cl::opt<bool> VerifyScheduling("verify-misched", cl::Hidden,
70 cl::desc("Verify machine instrs before and after machine scheduling"));
71
Andrew Trick44f750a2013-01-25 04:01:04 +000072// DAG subtrees must have at least this many nodes.
73static const unsigned MinSubtreeSize = 8;
74
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +000075// Pin the vtables to this file.
76void MachineSchedStrategy::anchor() {}
77void ScheduleDAGMutation::anchor() {}
78
Andrew Trick63440872012-01-14 02:17:06 +000079//===----------------------------------------------------------------------===//
80// Machine Instruction Scheduling Pass and Registry
81//===----------------------------------------------------------------------===//
82
Andrew Trick4d4b5462012-04-24 20:36:19 +000083MachineSchedContext::MachineSchedContext():
84 MF(0), MLI(0), MDT(0), PassConfig(0), AA(0), LIS(0) {
85 RegClassInfo = new RegisterClassInfo();
86}
87
88MachineSchedContext::~MachineSchedContext() {
89 delete RegClassInfo;
90}
91
Andrew Tricke77e84e2012-01-13 06:30:30 +000092namespace {
Andrew Trickd7f890e2013-12-28 21:56:47 +000093/// Base class for a machine scheduler class that can run at any point.
94class MachineSchedulerBase : public MachineSchedContext,
95 public MachineFunctionPass {
96public:
97 MachineSchedulerBase(char &ID): MachineFunctionPass(ID) {}
98
99 virtual void print(raw_ostream &O, const Module* = 0) const;
100
101protected:
102 void scheduleRegions(ScheduleDAGInstrs &Scheduler);
103};
104
Andrew Tricke1c034f2012-01-17 06:55:03 +0000105/// MachineScheduler runs after coalescing and before register allocation.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000106class MachineScheduler : public MachineSchedulerBase {
Andrew Tricke77e84e2012-01-13 06:30:30 +0000107public:
Andrew Tricke1c034f2012-01-17 06:55:03 +0000108 MachineScheduler();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000109
110 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
111
Andrew Tricke77e84e2012-01-13 06:30:30 +0000112 virtual bool runOnMachineFunction(MachineFunction&);
113
Andrew Tricke77e84e2012-01-13 06:30:30 +0000114 static char ID; // Class identification, replacement for typeinfo
Andrew Trick978674b2013-09-20 05:14:41 +0000115
116protected:
117 ScheduleDAGInstrs *createMachineScheduler();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000118};
Andrew Trick17080b92013-12-28 21:56:51 +0000119
120/// PostMachineScheduler runs after shortly before code emission.
121class PostMachineScheduler : public MachineSchedulerBase {
122public:
123 PostMachineScheduler();
124
125 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
126
127 virtual bool runOnMachineFunction(MachineFunction&);
128
129 static char ID; // Class identification, replacement for typeinfo
130
131protected:
132 ScheduleDAGInstrs *createPostMachineScheduler();
133};
Andrew Tricke77e84e2012-01-13 06:30:30 +0000134} // namespace
135
Andrew Tricke1c034f2012-01-17 06:55:03 +0000136char MachineScheduler::ID = 0;
Andrew Tricke77e84e2012-01-13 06:30:30 +0000137
Andrew Tricke1c034f2012-01-17 06:55:03 +0000138char &llvm::MachineSchedulerID = MachineScheduler::ID;
Andrew Tricke77e84e2012-01-13 06:30:30 +0000139
Andrew Tricke1c034f2012-01-17 06:55:03 +0000140INITIALIZE_PASS_BEGIN(MachineScheduler, "misched",
Andrew Tricke77e84e2012-01-13 06:30:30 +0000141 "Machine Instruction Scheduler", false, false)
142INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
143INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
144INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
Andrew Tricke1c034f2012-01-17 06:55:03 +0000145INITIALIZE_PASS_END(MachineScheduler, "misched",
Andrew Tricke77e84e2012-01-13 06:30:30 +0000146 "Machine Instruction Scheduler", false, false)
147
Andrew Tricke1c034f2012-01-17 06:55:03 +0000148MachineScheduler::MachineScheduler()
Andrew Trickd7f890e2013-12-28 21:56:47 +0000149: MachineSchedulerBase(ID) {
Andrew Tricke1c034f2012-01-17 06:55:03 +0000150 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Andrew Tricke77e84e2012-01-13 06:30:30 +0000151}
152
Andrew Tricke1c034f2012-01-17 06:55:03 +0000153void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
Andrew Tricke77e84e2012-01-13 06:30:30 +0000154 AU.setPreservesCFG();
155 AU.addRequiredID(MachineDominatorsID);
156 AU.addRequired<MachineLoopInfo>();
157 AU.addRequired<AliasAnalysis>();
Andrew Trick45300682012-03-09 00:52:20 +0000158 AU.addRequired<TargetPassConfig>();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000159 AU.addRequired<SlotIndexes>();
160 AU.addPreserved<SlotIndexes>();
161 AU.addRequired<LiveIntervals>();
162 AU.addPreserved<LiveIntervals>();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000163 MachineFunctionPass::getAnalysisUsage(AU);
164}
165
Andrew Trick17080b92013-12-28 21:56:51 +0000166char PostMachineScheduler::ID = 0;
167
168char &llvm::PostMachineSchedulerID = PostMachineScheduler::ID;
169
170INITIALIZE_PASS(PostMachineScheduler, "postmisched",
171 "PostRA Machine Instruction Scheduler", false, false);
172
173PostMachineScheduler::PostMachineScheduler()
174: MachineSchedulerBase(ID) {
175 initializePostMachineSchedulerPass(*PassRegistry::getPassRegistry());
176}
177
178void PostMachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
179 AU.setPreservesCFG();
180 AU.addRequiredID(MachineDominatorsID);
181 AU.addRequired<MachineLoopInfo>();
182 AU.addRequired<TargetPassConfig>();
183 MachineFunctionPass::getAnalysisUsage(AU);
184}
185
Andrew Tricke77e84e2012-01-13 06:30:30 +0000186MachinePassRegistry MachineSchedRegistry::Registry;
187
Andrew Trick45300682012-03-09 00:52:20 +0000188/// A dummy default scheduler factory indicates whether the scheduler
189/// is overridden on the command line.
190static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
191 return 0;
192}
Andrew Tricke77e84e2012-01-13 06:30:30 +0000193
194/// MachineSchedOpt allows command line selection of the scheduler.
195static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
196 RegisterPassParser<MachineSchedRegistry> >
197MachineSchedOpt("misched",
Andrew Trick45300682012-03-09 00:52:20 +0000198 cl::init(&useDefaultMachineSched), cl::Hidden,
Andrew Tricke77e84e2012-01-13 06:30:30 +0000199 cl::desc("Machine instruction scheduler to use"));
200
Andrew Trick45300682012-03-09 00:52:20 +0000201static MachineSchedRegistry
Andrew Trick8823dec2012-03-14 04:00:41 +0000202DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
Andrew Trick45300682012-03-09 00:52:20 +0000203 useDefaultMachineSched);
204
Andrew Trick8823dec2012-03-14 04:00:41 +0000205/// Forward declare the standard machine scheduler. This will be used as the
Andrew Trick45300682012-03-09 00:52:20 +0000206/// default scheduler if the target does not set a default.
Andrew Trick665d3ec2013-09-19 23:10:59 +0000207static ScheduleDAGInstrs *createGenericSched(MachineSchedContext *C);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000208static ScheduleDAGInstrs *createRawGenericSched(MachineSchedContext *C);
Andrew Trickcc45a282012-04-24 18:04:34 +0000209
210/// Decrement this iterator until reaching the top or a non-debug instr.
Andrew Trick2bc74c22013-08-30 04:36:57 +0000211static MachineBasicBlock::const_iterator
212priorNonDebug(MachineBasicBlock::const_iterator I,
213 MachineBasicBlock::const_iterator Beg) {
Andrew Trickcc45a282012-04-24 18:04:34 +0000214 assert(I != Beg && "reached the top of the region, cannot decrement");
215 while (--I != Beg) {
216 if (!I->isDebugValue())
217 break;
218 }
219 return I;
220}
221
Andrew Trick2bc74c22013-08-30 04:36:57 +0000222/// Non-const version.
223static MachineBasicBlock::iterator
224priorNonDebug(MachineBasicBlock::iterator I,
225 MachineBasicBlock::const_iterator Beg) {
226 return const_cast<MachineInstr*>(
227 &*priorNonDebug(MachineBasicBlock::const_iterator(I), Beg));
228}
229
Andrew Trickcc45a282012-04-24 18:04:34 +0000230/// If this iterator is a debug value, increment until reaching the End or a
231/// non-debug instruction.
Andrew Trick2c4f8b72013-08-31 05:17:58 +0000232static MachineBasicBlock::const_iterator
233nextIfDebug(MachineBasicBlock::const_iterator I,
234 MachineBasicBlock::const_iterator End) {
Andrew Trick463b2f12012-05-17 18:35:03 +0000235 for(; I != End; ++I) {
Andrew Trickcc45a282012-04-24 18:04:34 +0000236 if (!I->isDebugValue())
237 break;
238 }
239 return I;
240}
241
Andrew Trick2c4f8b72013-08-31 05:17:58 +0000242/// Non-const version.
243static MachineBasicBlock::iterator
244nextIfDebug(MachineBasicBlock::iterator I,
245 MachineBasicBlock::const_iterator End) {
246 // Cast the return value to nonconst MachineInstr, then cast to an
247 // instr_iterator, which does not check for null, finally return a
248 // bundle_iterator.
249 return MachineBasicBlock::instr_iterator(
250 const_cast<MachineInstr*>(
251 &*nextIfDebug(MachineBasicBlock::const_iterator(I), End)));
252}
253
Andrew Trickdc4c1ad2013-09-24 17:11:19 +0000254/// Instantiate a ScheduleDAGInstrs that will be owned by the caller.
Andrew Trick978674b2013-09-20 05:14:41 +0000255ScheduleDAGInstrs *MachineScheduler::createMachineScheduler() {
256 // Select the scheduler, or set the default.
257 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
258 if (Ctor != useDefaultMachineSched)
259 return Ctor(this);
260
261 // Get the default scheduler set by the target for this function.
262 ScheduleDAGInstrs *Scheduler = PassConfig->createMachineScheduler(this);
263 if (Scheduler)
264 return Scheduler;
265
266 // Default to GenericScheduler.
267 return createGenericSched(this);
268}
269
Andrew Trick17080b92013-12-28 21:56:51 +0000270/// Instantiate a ScheduleDAGInstrs for PostRA scheduling that will be owned by
271/// the caller. We don't have a command line option to override the postRA
272/// scheduler. The Target must configure it.
273ScheduleDAGInstrs *PostMachineScheduler::createPostMachineScheduler() {
274 // Get the postRA scheduler set by the target for this function.
275 ScheduleDAGInstrs *Scheduler = PassConfig->createPostMachineScheduler(this);
276 if (Scheduler)
277 return Scheduler;
278
279 // Default to GenericScheduler.
280 // return createRawGenericSched(this);
281 return NULL;
282}
283
Andrew Trick72515be2012-03-14 04:00:38 +0000284/// Top-level MachineScheduler pass driver.
285///
286/// Visit blocks in function order. Divide each block into scheduling regions
Andrew Trick8823dec2012-03-14 04:00:41 +0000287/// and visit them bottom-up. Visiting regions bottom-up is not required, but is
288/// consistent with the DAG builder, which traverses the interior of the
289/// scheduling regions bottom-up.
Andrew Trick72515be2012-03-14 04:00:38 +0000290///
291/// This design avoids exposing scheduling boundaries to the DAG builder,
Andrew Trick8823dec2012-03-14 04:00:41 +0000292/// simplifying the DAG builder's support for "special" target instructions.
293/// At the same time the design allows target schedulers to operate across
Andrew Trick72515be2012-03-14 04:00:38 +0000294/// scheduling boundaries, for example to bundle the boudary instructions
295/// without reordering them. This creates complexity, because the target
296/// scheduler must update the RegionBegin and RegionEnd positions cached by
297/// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
298/// design would be to split blocks at scheduling boundaries, but LLVM has a
299/// general bias against block splitting purely for implementation simplicity.
Andrew Tricke1c034f2012-01-17 06:55:03 +0000300bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
Andrew Trickc5d70082012-05-10 21:06:21 +0000301 DEBUG(dbgs() << "Before MISsched:\n"; mf.print(dbgs()));
302
Andrew Tricke77e84e2012-01-13 06:30:30 +0000303 // Initialize the context of the pass.
304 MF = &mf;
305 MLI = &getAnalysis<MachineLoopInfo>();
306 MDT = &getAnalysis<MachineDominatorTree>();
Andrew Trick45300682012-03-09 00:52:20 +0000307 PassConfig = &getAnalysis<TargetPassConfig>();
Andrew Trick02a80da2012-03-08 01:41:12 +0000308 AA = &getAnalysis<AliasAnalysis>();
309
Lang Hamesad33d5a2012-01-27 22:36:19 +0000310 LIS = &getAnalysis<LiveIntervals>();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000311
Andrew Trick48f2a722013-03-08 05:40:34 +0000312 if (VerifyScheduling) {
Andrew Trick97064962013-07-25 07:26:26 +0000313 DEBUG(LIS->dump());
Andrew Trick48f2a722013-03-08 05:40:34 +0000314 MF->verify(this, "Before machine scheduling.");
315 }
Andrew Trick4d4b5462012-04-24 20:36:19 +0000316 RegClassInfo->runOnMachineFunction(*MF);
Andrew Trick88639922012-04-24 17:56:43 +0000317
Andrew Trick978674b2013-09-20 05:14:41 +0000318 // Instantiate the selected scheduler for this target, function, and
319 // optimization level.
320 OwningPtr<ScheduleDAGInstrs> Scheduler(createMachineScheduler());
Andrew Trickd7f890e2013-12-28 21:56:47 +0000321 scheduleRegions(*Scheduler);
322
323 DEBUG(LIS->dump());
324 if (VerifyScheduling)
325 MF->verify(this, "After machine scheduling.");
326 return true;
327}
328
Andrew Trick17080b92013-12-28 21:56:51 +0000329bool PostMachineScheduler::runOnMachineFunction(MachineFunction &mf) {
330 DEBUG(dbgs() << "Before post-MI-sched:\n"; mf.print(dbgs()));
331
332 // Initialize the context of the pass.
333 MF = &mf;
334 PassConfig = &getAnalysis<TargetPassConfig>();
335
336 if (VerifyScheduling)
337 MF->verify(this, "Before post machine scheduling.");
338
339 // Instantiate the selected scheduler for this target, function, and
340 // optimization level.
341 OwningPtr<ScheduleDAGInstrs> Scheduler(createPostMachineScheduler());
342 scheduleRegions(*Scheduler);
343
344 if (VerifyScheduling)
345 MF->verify(this, "After post machine scheduling.");
346 return true;
347}
348
Andrew Trickd7f890e2013-12-28 21:56:47 +0000349/// Main driver for both MachineScheduler and PostMachineScheduler.
350void MachineSchedulerBase::scheduleRegions(ScheduleDAGInstrs &Scheduler) {
351 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000352
353 // Visit all machine basic blocks.
Andrew Trick88639922012-04-24 17:56:43 +0000354 //
355 // TODO: Visit blocks in global postorder or postorder within the bottom-up
356 // loop tree. Then we can optionally compute global RegPressure.
Andrew Tricke77e84e2012-01-13 06:30:30 +0000357 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
358 MBB != MBBEnd; ++MBB) {
359
Andrew Trickd7f890e2013-12-28 21:56:47 +0000360 Scheduler.startBlock(MBB);
Andrew Trickedfe2ec2012-03-09 08:02:51 +0000361
Andrew Trick7e120f42012-01-14 02:17:09 +0000362 // Break the block into scheduling regions [I, RegionEnd), and schedule each
Sylvestre Ledru35521e22012-07-23 08:51:15 +0000363 // region as soon as it is discovered. RegionEnd points the scheduling
Andrew Trickaf1bee72012-03-09 22:34:56 +0000364 // boundary at the bottom of the region. The DAG does not include RegionEnd,
365 // but the region does (i.e. the next RegionEnd is above the previous
366 // RegionBegin). If the current block has no terminator then RegionEnd ==
367 // MBB->end() for the bottom region.
368 //
369 // The Scheduler may insert instructions during either schedule() or
370 // exitRegion(), even for empty regions. So the local iterators 'I' and
371 // 'RegionEnd' are invalid across these calls.
Andrew Trick4d1fa712012-11-06 07:10:34 +0000372 unsigned RemainingInstrs = MBB->size();
Andrew Tricka21daf72012-03-09 03:46:39 +0000373 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
Andrew Trickd7f890e2013-12-28 21:56:47 +0000374 RegionEnd != MBB->begin(); RegionEnd = Scheduler.begin()) {
Andrew Trick88639922012-04-24 17:56:43 +0000375
Andrew Trickedfe2ec2012-03-09 08:02:51 +0000376 // Avoid decrementing RegionEnd for blocks with no terminator.
377 if (RegionEnd != MBB->end()
378 || TII->isSchedulingBoundary(llvm::prior(RegionEnd), MBB, *MF)) {
379 --RegionEnd;
380 // Count the boundary instruction.
Andrew Trick4d1fa712012-11-06 07:10:34 +0000381 --RemainingInstrs;
Andrew Trickedfe2ec2012-03-09 08:02:51 +0000382 }
383
Andrew Trick7e120f42012-01-14 02:17:09 +0000384 // The next region starts above the previous region. Look backward in the
385 // instruction stream until we find the nearest boundary.
Andrew Tricka53e1012013-08-23 17:48:33 +0000386 unsigned NumRegionInstrs = 0;
Andrew Trick7e120f42012-01-14 02:17:09 +0000387 MachineBasicBlock::iterator I = RegionEnd;
Andrew Tricka53e1012013-08-23 17:48:33 +0000388 for(;I != MBB->begin(); --I, --RemainingInstrs, ++NumRegionInstrs) {
Andrew Trick7e120f42012-01-14 02:17:09 +0000389 if (TII->isSchedulingBoundary(llvm::prior(I), MBB, *MF))
390 break;
391 }
Andrew Trick60cf03e2012-03-07 05:21:52 +0000392 // Notify the scheduler of the region, even if we may skip scheduling
393 // it. Perhaps it still needs to be bundled.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000394 Scheduler.enterRegion(MBB, I, RegionEnd, NumRegionInstrs);
Andrew Trick60cf03e2012-03-07 05:21:52 +0000395
396 // Skip empty scheduling regions (0 or 1 schedulable instructions).
397 if (I == RegionEnd || I == llvm::prior(RegionEnd)) {
Andrew Trick60cf03e2012-03-07 05:21:52 +0000398 // Close the current region. Bundle the terminator if needed.
Andrew Trickaf1bee72012-03-09 22:34:56 +0000399 // This invalidates 'RegionEnd' and 'I'.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000400 Scheduler.exitRegion();
Andrew Trick7ccdc5c2012-01-17 06:55:07 +0000401 continue;
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000402 }
Andrew Trick79d3eec2012-05-24 22:11:14 +0000403 DEBUG(dbgs() << "********** MI Scheduling **********\n");
Craig Toppera538d832012-08-22 06:07:19 +0000404 DEBUG(dbgs() << MF->getName()
Andrew Trick54b2ce32013-01-25 07:45:31 +0000405 << ":BB#" << MBB->getNumber() << " " << MBB->getName()
406 << "\n From: " << *I << " To: ";
Andrew Tricke57583a2012-02-08 02:17:21 +0000407 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
408 else dbgs() << "End";
Andrew Tricka53e1012013-08-23 17:48:33 +0000409 dbgs() << " RegionInstrs: " << NumRegionInstrs
410 << " Remaining: " << RemainingInstrs << "\n");
Andrew Trick7ccdc5c2012-01-17 06:55:07 +0000411
Andrew Trick1c0ec452012-03-09 03:46:42 +0000412 // Schedule a region: possibly reorder instructions.
Andrew Trickaf1bee72012-03-09 22:34:56 +0000413 // This invalidates 'RegionEnd' and 'I'.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000414 Scheduler.schedule();
Andrew Trick1c0ec452012-03-09 03:46:42 +0000415
416 // Close the current region.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000417 Scheduler.exitRegion();
Andrew Trick60cf03e2012-03-07 05:21:52 +0000418
419 // Scheduling has invalidated the current iterator 'I'. Ask the
420 // scheduler for the top of it's scheduled region.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000421 RegionEnd = Scheduler.begin();
Andrew Trick7e120f42012-01-14 02:17:09 +0000422 }
Andrew Trick4d1fa712012-11-06 07:10:34 +0000423 assert(RemainingInstrs == 0 && "Instruction count mismatch!");
Andrew Trickd7f890e2013-12-28 21:56:47 +0000424 Scheduler.finishBlock();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000425 }
Andrew Trickd7f890e2013-12-28 21:56:47 +0000426 Scheduler.finalizeSchedule();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000427}
428
Andrew Trickd7f890e2013-12-28 21:56:47 +0000429void MachineSchedulerBase::print(raw_ostream &O, const Module* m) const {
Andrew Tricke77e84e2012-01-13 06:30:30 +0000430 // unimplemented
431}
432
Manman Ren19f49ac2012-09-11 22:23:19 +0000433#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Andrew Trick7a8e1002012-09-11 00:39:15 +0000434void ReadyQueue::dump() {
Andrew Trickd40d0f22013-06-17 21:45:05 +0000435 dbgs() << Name << ": ";
Andrew Trick7a8e1002012-09-11 00:39:15 +0000436 for (unsigned i = 0, e = Queue.size(); i < e; ++i)
437 dbgs() << Queue[i]->NodeNum << " ";
438 dbgs() << "\n";
439}
440#endif
Andrew Trick8823dec2012-03-14 04:00:41 +0000441
442//===----------------------------------------------------------------------===//
Andrew Trickd7f890e2013-12-28 21:56:47 +0000443// ScheduleDAGMI - Basic machine instruction scheduling. This is
444// independent of PreRA/PostRA scheduling and involves no extra book-keeping for
445// virtual registers.
446// ===----------------------------------------------------------------------===/
Andrew Trick8823dec2012-03-14 04:00:41 +0000447
Andrew Trick44f750a2013-01-25 04:01:04 +0000448ScheduleDAGMI::~ScheduleDAGMI() {
Andrew Trick44f750a2013-01-25 04:01:04 +0000449 DeleteContainerPointers(Mutations);
450 delete SchedImpl;
451}
452
Andrew Trick85a1d4c2013-04-24 15:54:43 +0000453bool ScheduleDAGMI::canAddEdge(SUnit *SuccSU, SUnit *PredSU) {
454 return SuccSU == &ExitSU || !Topo.IsReachable(PredSU, SuccSU);
455}
456
Andrew Tricka7714a02012-11-12 19:40:10 +0000457bool ScheduleDAGMI::addEdge(SUnit *SuccSU, const SDep &PredDep) {
Andrew Trick263280242012-11-12 19:52:20 +0000458 if (SuccSU != &ExitSU) {
459 // Do not use WillCreateCycle, it assumes SD scheduling.
460 // If Pred is reachable from Succ, then the edge creates a cycle.
461 if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
462 return false;
463 Topo.AddPred(SuccSU, PredDep.getSUnit());
464 }
Andrew Tricka7714a02012-11-12 19:40:10 +0000465 SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
466 // Return true regardless of whether a new edge needed to be inserted.
467 return true;
468}
469
Andrew Trick02a80da2012-03-08 01:41:12 +0000470/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
471/// NumPredsLeft reaches zero, release the successor node.
Andrew Trick61f1a272012-05-24 22:11:09 +0000472///
473/// FIXME: Adjust SuccSU height based on MinLatency.
Andrew Trick8823dec2012-03-14 04:00:41 +0000474void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
Andrew Trick02a80da2012-03-08 01:41:12 +0000475 SUnit *SuccSU = SuccEdge->getSUnit();
476
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000477 if (SuccEdge->isWeak()) {
478 --SuccSU->WeakPredsLeft;
Andrew Tricka7714a02012-11-12 19:40:10 +0000479 if (SuccEdge->isCluster())
480 NextClusterSucc = SuccSU;
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000481 return;
482 }
Andrew Trick02a80da2012-03-08 01:41:12 +0000483#ifndef NDEBUG
484 if (SuccSU->NumPredsLeft == 0) {
485 dbgs() << "*** Scheduling failed! ***\n";
486 SuccSU->dump(this);
487 dbgs() << " has been released too many times!\n";
488 llvm_unreachable(0);
489 }
490#endif
491 --SuccSU->NumPredsLeft;
492 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
Andrew Trick8823dec2012-03-14 04:00:41 +0000493 SchedImpl->releaseTopNode(SuccSU);
Andrew Trick02a80da2012-03-08 01:41:12 +0000494}
495
496/// releaseSuccessors - Call releaseSucc on each of SU's successors.
Andrew Trick8823dec2012-03-14 04:00:41 +0000497void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
Andrew Trick02a80da2012-03-08 01:41:12 +0000498 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
499 I != E; ++I) {
500 releaseSucc(SU, &*I);
501 }
502}
503
Andrew Trick8823dec2012-03-14 04:00:41 +0000504/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
505/// NumSuccsLeft reaches zero, release the predecessor node.
Andrew Trick61f1a272012-05-24 22:11:09 +0000506///
507/// FIXME: Adjust PredSU height based on MinLatency.
Andrew Trick8823dec2012-03-14 04:00:41 +0000508void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
509 SUnit *PredSU = PredEdge->getSUnit();
510
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000511 if (PredEdge->isWeak()) {
512 --PredSU->WeakSuccsLeft;
Andrew Tricka7714a02012-11-12 19:40:10 +0000513 if (PredEdge->isCluster())
514 NextClusterPred = PredSU;
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000515 return;
516 }
Andrew Trick8823dec2012-03-14 04:00:41 +0000517#ifndef NDEBUG
518 if (PredSU->NumSuccsLeft == 0) {
519 dbgs() << "*** Scheduling failed! ***\n";
520 PredSU->dump(this);
521 dbgs() << " has been released too many times!\n";
522 llvm_unreachable(0);
523 }
524#endif
525 --PredSU->NumSuccsLeft;
526 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
527 SchedImpl->releaseBottomNode(PredSU);
528}
529
530/// releasePredecessors - Call releasePred on each of SU's predecessors.
531void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
532 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
533 I != E; ++I) {
534 releasePred(SU, &*I);
535 }
536}
537
Andrew Trickd7f890e2013-12-28 21:56:47 +0000538/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
539/// crossing a scheduling boundary. [begin, end) includes all instructions in
540/// the region, including the boundary itself and single-instruction regions
541/// that don't get scheduled.
542void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
543 MachineBasicBlock::iterator begin,
544 MachineBasicBlock::iterator end,
545 unsigned regioninstrs)
546{
547 ScheduleDAGInstrs::enterRegion(bb, begin, end, regioninstrs);
548
549 SchedImpl->initPolicy(begin, end, regioninstrs);
550}
551
Andrew Tricke833e1c2013-04-13 06:07:40 +0000552/// This is normally called from the main scheduler loop but may also be invoked
553/// by the scheduling strategy to perform additional code motion.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000554void ScheduleDAGMI::moveInstruction(
555 MachineInstr *MI, MachineBasicBlock::iterator InsertPos) {
Andrew Trick463b2f12012-05-17 18:35:03 +0000556 // Advance RegionBegin if the first instruction moves down.
Andrew Trick54f7def2012-03-21 04:12:10 +0000557 if (&*RegionBegin == MI)
Andrew Trick463b2f12012-05-17 18:35:03 +0000558 ++RegionBegin;
559
560 // Update the instruction stream.
Andrew Trick8823dec2012-03-14 04:00:41 +0000561 BB->splice(InsertPos, BB, MI);
Andrew Trick463b2f12012-05-17 18:35:03 +0000562
563 // Update LiveIntervals
Andrew Trickd7f890e2013-12-28 21:56:47 +0000564 if (LIS)
565 LIS->handleMove(MI, /*UpdateFlags=*/true);
Andrew Trick463b2f12012-05-17 18:35:03 +0000566
567 // Recede RegionBegin if an instruction moves above the first.
Andrew Trick8823dec2012-03-14 04:00:41 +0000568 if (RegionBegin == InsertPos)
569 RegionBegin = MI;
570}
571
Andrew Trickde670c02012-03-21 04:12:07 +0000572bool ScheduleDAGMI::checkSchedLimit() {
573#ifndef NDEBUG
574 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
575 CurrentTop = CurrentBottom;
576 return false;
577 }
578 ++NumInstrsScheduled;
579#endif
580 return true;
581}
582
Andrew Trickd7f890e2013-12-28 21:56:47 +0000583/// Per-region scheduling driver, called back from
584/// MachineScheduler::runOnMachineFunction. This is a simplified driver that
585/// does not consider liveness or register pressure. It is useful for PostRA
586/// scheduling and potentially other custom schedulers.
587void ScheduleDAGMI::schedule() {
588 // Build the DAG.
589 buildSchedGraph(AA);
590
591 Topo.InitDAGTopologicalSorting();
592
593 postprocessDAG();
594
595 SmallVector<SUnit*, 8> TopRoots, BotRoots;
596 findRootsAndBiasEdges(TopRoots, BotRoots);
597
598 // Initialize the strategy before modifying the DAG.
599 // This may initialize a DFSResult to be used for queue priority.
600 SchedImpl->initialize(this);
601
602 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
603 SUnits[su].dumpAll(this));
604 if (ViewMISchedDAGs) viewGraph();
605
606 // Initialize ready queues now that the DAG and priority data are finalized.
607 initQueues(TopRoots, BotRoots);
608
609 bool IsTopNode = false;
610 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
611 assert(!SU->isScheduled && "Node already scheduled");
612 if (!checkSchedLimit())
613 break;
614
615 MachineInstr *MI = SU->getInstr();
616 if (IsTopNode) {
617 assert(SU->isTopReady() && "node still has unscheduled dependencies");
618 if (&*CurrentTop == MI)
619 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
620 else
621 moveInstruction(MI, CurrentTop);
622 }
623 else {
624 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
625 MachineBasicBlock::iterator priorII =
626 priorNonDebug(CurrentBottom, CurrentTop);
627 if (&*priorII == MI)
628 CurrentBottom = priorII;
629 else {
630 if (&*CurrentTop == MI)
631 CurrentTop = nextIfDebug(++CurrentTop, priorII);
632 moveInstruction(MI, CurrentBottom);
633 CurrentBottom = MI;
634 }
635 }
636 updateQueues(SU, IsTopNode);
637
638 // Notify the scheduling strategy after updating the DAG.
639 SchedImpl->schedNode(SU, IsTopNode);
640 }
641 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
642
643 placeDebugValues();
644
645 DEBUG({
646 unsigned BBNum = begin()->getParent()->getNumber();
647 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
648 dumpSchedule();
649 dbgs() << '\n';
650 });
651}
652
653/// Apply each ScheduleDAGMutation step in order.
654void ScheduleDAGMI::postprocessDAG() {
655 for (unsigned i = 0, e = Mutations.size(); i < e; ++i) {
656 Mutations[i]->apply(this);
657 }
658}
659
660void ScheduleDAGMI::
661findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
662 SmallVectorImpl<SUnit*> &BotRoots) {
663 for (std::vector<SUnit>::iterator
664 I = SUnits.begin(), E = SUnits.end(); I != E; ++I) {
665 SUnit *SU = &(*I);
666 assert(!SU->isBoundaryNode() && "Boundary node should not be in SUnits");
667
668 // Order predecessors so DFSResult follows the critical path.
669 SU->biasCriticalPath();
670
671 // A SUnit is ready to top schedule if it has no predecessors.
672 if (!I->NumPredsLeft)
673 TopRoots.push_back(SU);
674 // A SUnit is ready to bottom schedule if it has no successors.
675 if (!I->NumSuccsLeft)
676 BotRoots.push_back(SU);
677 }
678 ExitSU.biasCriticalPath();
679}
680
681/// Identify DAG roots and setup scheduler queues.
682void ScheduleDAGMI::initQueues(ArrayRef<SUnit*> TopRoots,
683 ArrayRef<SUnit*> BotRoots) {
684 NextClusterSucc = NULL;
685 NextClusterPred = NULL;
686
687 // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
688 //
689 // Nodes with unreleased weak edges can still be roots.
690 // Release top roots in forward order.
691 for (SmallVectorImpl<SUnit*>::const_iterator
692 I = TopRoots.begin(), E = TopRoots.end(); I != E; ++I) {
693 SchedImpl->releaseTopNode(*I);
694 }
695 // Release bottom roots in reverse order so the higher priority nodes appear
696 // first. This is more natural and slightly more efficient.
697 for (SmallVectorImpl<SUnit*>::const_reverse_iterator
698 I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I) {
699 SchedImpl->releaseBottomNode(*I);
700 }
701
702 releaseSuccessors(&EntrySU);
703 releasePredecessors(&ExitSU);
704
705 SchedImpl->registerRoots();
706
707 // Advance past initial DebugValues.
708 CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
709 CurrentBottom = RegionEnd;
710}
711
712/// Update scheduler queues after scheduling an instruction.
713void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
714 // Release dependent instructions for scheduling.
715 if (IsTopNode)
716 releaseSuccessors(SU);
717 else
718 releasePredecessors(SU);
719
720 SU->isScheduled = true;
721}
722
723/// Reinsert any remaining debug_values, just like the PostRA scheduler.
724void ScheduleDAGMI::placeDebugValues() {
725 // If first instruction was a DBG_VALUE then put it back.
726 if (FirstDbgValue) {
727 BB->splice(RegionBegin, BB, FirstDbgValue);
728 RegionBegin = FirstDbgValue;
729 }
730
731 for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
732 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
733 std::pair<MachineInstr *, MachineInstr *> P = *prior(DI);
734 MachineInstr *DbgValue = P.first;
735 MachineBasicBlock::iterator OrigPrevMI = P.second;
736 if (&*RegionBegin == DbgValue)
737 ++RegionBegin;
738 BB->splice(++OrigPrevMI, BB, DbgValue);
739 if (OrigPrevMI == llvm::prior(RegionEnd))
740 RegionEnd = DbgValue;
741 }
742 DbgValues.clear();
743 FirstDbgValue = NULL;
744}
745
746#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
747void ScheduleDAGMI::dumpSchedule() const {
748 for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
749 if (SUnit *SU = getSUnit(&(*MI)))
750 SU->dump(this);
751 else
752 dbgs() << "Missing SUnit\n";
753 }
754}
755#endif
756
757//===----------------------------------------------------------------------===//
758// ScheduleDAGMILive - Base class for MachineInstr scheduling with LiveIntervals
759// preservation.
760//===----------------------------------------------------------------------===//
761
762ScheduleDAGMILive::~ScheduleDAGMILive() {
763 delete DFSResult;
764}
765
Andrew Trick88639922012-04-24 17:56:43 +0000766/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
767/// crossing a scheduling boundary. [begin, end) includes all instructions in
768/// the region, including the boundary itself and single-instruction regions
769/// that don't get scheduled.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000770void ScheduleDAGMILive::enterRegion(MachineBasicBlock *bb,
Andrew Trick88639922012-04-24 17:56:43 +0000771 MachineBasicBlock::iterator begin,
772 MachineBasicBlock::iterator end,
Andrew Tricka53e1012013-08-23 17:48:33 +0000773 unsigned regioninstrs)
Andrew Trick88639922012-04-24 17:56:43 +0000774{
Andrew Trickd7f890e2013-12-28 21:56:47 +0000775 // ScheduleDAGMI initializes SchedImpl's per-region policy.
776 ScheduleDAGMI::enterRegion(bb, begin, end, regioninstrs);
Andrew Trick4add42f2012-05-10 21:06:10 +0000777
778 // For convenience remember the end of the liveness region.
779 LiveRegionEnd =
780 (RegionEnd == bb->end()) ? RegionEnd : llvm::next(RegionEnd);
Andrew Trick75e411c2013-09-06 17:32:34 +0000781
Andrew Trickb248b4a2013-09-06 17:32:47 +0000782 SUPressureDiffs.clear();
783
Andrew Trick75e411c2013-09-06 17:32:34 +0000784 ShouldTrackPressure = SchedImpl->shouldTrackPressure();
Andrew Trick4add42f2012-05-10 21:06:10 +0000785}
786
787// Setup the register pressure trackers for the top scheduled top and bottom
788// scheduled regions.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000789void ScheduleDAGMILive::initRegPressure() {
Andrew Trick4add42f2012-05-10 21:06:10 +0000790 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin);
791 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
792
793 // Close the RPTracker to finalize live ins.
794 RPTracker.closeRegion();
795
Andrew Trick9c17eab2013-07-30 19:59:12 +0000796 DEBUG(RPTracker.dump());
Andrew Trick79d3eec2012-05-24 22:11:14 +0000797
Andrew Trick4add42f2012-05-10 21:06:10 +0000798 // Initialize the live ins and live outs.
799 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
800 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
801
802 // Close one end of the tracker so we can call
803 // getMaxUpward/DownwardPressureDelta before advancing across any
804 // instructions. This converts currently live regs into live ins/outs.
805 TopRPTracker.closeTop();
806 BotRPTracker.closeBottom();
807
Andrew Trick9c17eab2013-07-30 19:59:12 +0000808 BotRPTracker.initLiveThru(RPTracker);
809 if (!BotRPTracker.getLiveThru().empty()) {
810 TopRPTracker.initLiveThru(BotRPTracker.getLiveThru());
811 DEBUG(dbgs() << "Live Thru: ";
812 dumpRegSetPressure(BotRPTracker.getLiveThru(), TRI));
813 };
814
Andrew Trick2bc74c22013-08-30 04:36:57 +0000815 // For each live out vreg reduce the pressure change associated with other
816 // uses of the same vreg below the live-out reaching def.
817 updatePressureDiffs(RPTracker.getPressure().LiveOutRegs);
818
Andrew Trick4add42f2012-05-10 21:06:10 +0000819 // Account for liveness generated by the region boundary.
Andrew Trick2bc74c22013-08-30 04:36:57 +0000820 if (LiveRegionEnd != RegionEnd) {
821 SmallVector<unsigned, 8> LiveUses;
822 BotRPTracker.recede(&LiveUses);
823 updatePressureDiffs(LiveUses);
824 }
Andrew Trick4add42f2012-05-10 21:06:10 +0000825
826 assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
Andrew Trick22025772012-05-17 18:35:10 +0000827
828 // Cache the list of excess pressure sets in this region. This will also track
829 // the max pressure in the scheduled code for these sets.
830 RegionCriticalPSets.clear();
Jakub Staszakc641ada2013-01-25 21:44:27 +0000831 const std::vector<unsigned> &RegionPressure =
832 RPTracker.getPressure().MaxSetPressure;
Andrew Trick22025772012-05-17 18:35:10 +0000833 for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
Andrew Trick736dd9a2013-06-21 18:32:58 +0000834 unsigned Limit = RegClassInfo->getRegPressureSetLimit(i);
Andrew Trickb55db582013-06-21 18:33:01 +0000835 if (RegionPressure[i] > Limit) {
836 DEBUG(dbgs() << TRI->getRegPressureSetName(i)
837 << " Limit " << Limit
838 << " Actual " << RegionPressure[i] << "\n");
Andrew Trick1a831342013-08-30 03:49:48 +0000839 RegionCriticalPSets.push_back(PressureChange(i));
Andrew Trickb55db582013-06-21 18:33:01 +0000840 }
Andrew Trick22025772012-05-17 18:35:10 +0000841 }
842 DEBUG(dbgs() << "Excess PSets: ";
843 for (unsigned i = 0, e = RegionCriticalPSets.size(); i != e; ++i)
844 dbgs() << TRI->getRegPressureSetName(
Andrew Trick1a831342013-08-30 03:49:48 +0000845 RegionCriticalPSets[i].getPSet()) << " ";
Andrew Trick22025772012-05-17 18:35:10 +0000846 dbgs() << "\n");
847}
848
Andrew Trickd7f890e2013-12-28 21:56:47 +0000849void ScheduleDAGMILive::
Andrew Trickb248b4a2013-09-06 17:32:47 +0000850updateScheduledPressure(const SUnit *SU,
851 const std::vector<unsigned> &NewMaxPressure) {
852 const PressureDiff &PDiff = getPressureDiff(SU);
853 unsigned CritIdx = 0, CritEnd = RegionCriticalPSets.size();
854 for (PressureDiff::const_iterator I = PDiff.begin(), E = PDiff.end();
855 I != E; ++I) {
856 if (!I->isValid())
857 break;
858 unsigned ID = I->getPSet();
859 while (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() < ID)
860 ++CritIdx;
861 if (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() == ID) {
862 if ((int)NewMaxPressure[ID] > RegionCriticalPSets[CritIdx].getUnitInc()
863 && NewMaxPressure[ID] <= INT16_MAX)
864 RegionCriticalPSets[CritIdx].setUnitInc(NewMaxPressure[ID]);
865 }
866 unsigned Limit = RegClassInfo->getRegPressureSetLimit(ID);
867 if (NewMaxPressure[ID] >= Limit - 2) {
868 DEBUG(dbgs() << " " << TRI->getRegPressureSetName(ID) << ": "
869 << NewMaxPressure[ID] << " > " << Limit << "(+ "
870 << BotRPTracker.getLiveThru()[ID] << " livethru)\n");
871 }
Andrew Trick22025772012-05-17 18:35:10 +0000872 }
Andrew Trick88639922012-04-24 17:56:43 +0000873}
874
Andrew Trick2bc74c22013-08-30 04:36:57 +0000875/// Update the PressureDiff array for liveness after scheduling this
876/// instruction.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000877void ScheduleDAGMILive::updatePressureDiffs(ArrayRef<unsigned> LiveUses) {
Andrew Trick2bc74c22013-08-30 04:36:57 +0000878 for (unsigned LUIdx = 0, LUEnd = LiveUses.size(); LUIdx != LUEnd; ++LUIdx) {
879 /// FIXME: Currently assuming single-use physregs.
880 unsigned Reg = LiveUses[LUIdx];
Andrew Trickffdbefb2013-09-06 17:32:39 +0000881 DEBUG(dbgs() << " LiveReg: " << PrintVRegOrUnit(Reg, TRI) << "\n");
Andrew Trick2bc74c22013-08-30 04:36:57 +0000882 if (!TRI->isVirtualRegister(Reg))
883 continue;
Andrew Trickffdbefb2013-09-06 17:32:39 +0000884
Andrew Trick2bc74c22013-08-30 04:36:57 +0000885 // This may be called before CurrentBottom has been initialized. However,
886 // BotRPTracker must have a valid position. We want the value live into the
887 // instruction or live out of the block, so ask for the previous
888 // instruction's live-out.
889 const LiveInterval &LI = LIS->getInterval(Reg);
890 VNInfo *VNI;
Andrew Trick2c4f8b72013-08-31 05:17:58 +0000891 MachineBasicBlock::const_iterator I =
892 nextIfDebug(BotRPTracker.getPos(), BB->end());
893 if (I == BB->end())
Andrew Trick2bc74c22013-08-30 04:36:57 +0000894 VNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
895 else {
Matthias Braun88dd0ab2013-10-10 21:28:52 +0000896 LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(I));
Andrew Trick2bc74c22013-08-30 04:36:57 +0000897 VNI = LRQ.valueIn();
898 }
899 // RegisterPressureTracker guarantees that readsReg is true for LiveUses.
900 assert(VNI && "No live value at use.");
901 for (VReg2UseMap::iterator
902 UI = VRegUses.find(Reg); UI != VRegUses.end(); ++UI) {
903 SUnit *SU = UI->SU;
Andrew Trickffdbefb2013-09-06 17:32:39 +0000904 DEBUG(dbgs() << " UpdateRegP: SU(" << SU->NodeNum << ") "
905 << *SU->getInstr());
Andrew Trick2bc74c22013-08-30 04:36:57 +0000906 // If this use comes before the reaching def, it cannot be a last use, so
907 // descrease its pressure change.
908 if (!SU->isScheduled && SU != &ExitSU) {
Matthias Braun88dd0ab2013-10-10 21:28:52 +0000909 LiveQueryResult LRQ
910 = LI.Query(LIS->getInstructionIndex(SU->getInstr()));
Andrew Trick2bc74c22013-08-30 04:36:57 +0000911 if (LRQ.valueIn() == VNI)
912 getPressureDiff(SU).addPressureChange(Reg, true, &MRI);
913 }
914 }
915 }
916}
917
Andrew Trick8823dec2012-03-14 04:00:41 +0000918/// schedule - Called back from MachineScheduler::runOnMachineFunction
Andrew Trick88639922012-04-24 17:56:43 +0000919/// after setting up the current scheduling region. [RegionBegin, RegionEnd)
920/// only includes instructions that have DAG nodes, not scheduling boundaries.
Andrew Trick7a8e1002012-09-11 00:39:15 +0000921///
922/// This is a skeletal driver, with all the functionality pushed into helpers,
923/// so that it can be easilly extended by experimental schedulers. Generally,
924/// implementing MachineSchedStrategy should be sufficient to implement a new
925/// scheduling algorithm. However, if a scheduler further subclasses
Andrew Trickd7f890e2013-12-28 21:56:47 +0000926/// ScheduleDAGMILive then it will want to override this virtual method in order
927/// to update any specialized state.
928void ScheduleDAGMILive::schedule() {
Andrew Trick7a8e1002012-09-11 00:39:15 +0000929 buildDAGWithRegPressure();
930
Andrew Tricka7714a02012-11-12 19:40:10 +0000931 Topo.InitDAGTopologicalSorting();
932
Andrew Tricka2733e92012-09-14 17:22:42 +0000933 postprocessDAG();
934
Andrew Tricke2c3f5c2013-01-25 06:33:57 +0000935 SmallVector<SUnit*, 8> TopRoots, BotRoots;
936 findRootsAndBiasEdges(TopRoots, BotRoots);
937
938 // Initialize the strategy before modifying the DAG.
939 // This may initialize a DFSResult to be used for queue priority.
940 SchedImpl->initialize(this);
941
Andrew Trick7a8e1002012-09-11 00:39:15 +0000942 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
943 SUnits[su].dumpAll(this));
Andrew Tricke2c3f5c2013-01-25 06:33:57 +0000944 if (ViewMISchedDAGs) viewGraph();
Andrew Trick7a8e1002012-09-11 00:39:15 +0000945
Andrew Tricke2c3f5c2013-01-25 06:33:57 +0000946 // Initialize ready queues now that the DAG and priority data are finalized.
947 initQueues(TopRoots, BotRoots);
Andrew Trick7a8e1002012-09-11 00:39:15 +0000948
Andrew Trickd7f890e2013-12-28 21:56:47 +0000949 if (ShouldTrackPressure) {
950 assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
951 TopRPTracker.setPos(CurrentTop);
952 }
953
Andrew Trick7a8e1002012-09-11 00:39:15 +0000954 bool IsTopNode = false;
955 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
Andrew Trick984d98b2012-10-08 18:53:53 +0000956 assert(!SU->isScheduled && "Node already scheduled");
Andrew Trick7a8e1002012-09-11 00:39:15 +0000957 if (!checkSchedLimit())
958 break;
959
960 scheduleMI(SU, IsTopNode);
961
962 updateQueues(SU, IsTopNode);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000963
964 if (DFSResult) {
965 unsigned SubtreeID = DFSResult->getSubtreeID(SU);
966 if (!ScheduledTrees.test(SubtreeID)) {
967 ScheduledTrees.set(SubtreeID);
968 DFSResult->scheduleTree(SubtreeID);
969 SchedImpl->scheduleTree(SubtreeID);
970 }
971 }
972
973 // Notify the scheduling strategy after updating the DAG.
974 SchedImpl->schedNode(SU, IsTopNode);
Andrew Trick7a8e1002012-09-11 00:39:15 +0000975 }
976 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
977
978 placeDebugValues();
Andrew Trick3ca33ac2012-11-07 07:05:09 +0000979
980 DEBUG({
Andrew Trickcf7e6972012-11-28 03:42:47 +0000981 unsigned BBNum = begin()->getParent()->getNumber();
Andrew Trick3ca33ac2012-11-07 07:05:09 +0000982 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
983 dumpSchedule();
984 dbgs() << '\n';
985 });
Andrew Trick7a8e1002012-09-11 00:39:15 +0000986}
987
988/// Build the DAG and setup three register pressure trackers.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000989void ScheduleDAGMILive::buildDAGWithRegPressure() {
Andrew Trickb6e74712013-09-04 20:59:59 +0000990 if (!ShouldTrackPressure) {
991 RPTracker.reset();
992 RegionCriticalPSets.clear();
993 buildSchedGraph(AA);
994 return;
995 }
996
Andrew Trick4add42f2012-05-10 21:06:10 +0000997 // Initialize the register pressure tracker used by buildSchedGraph.
Andrew Trick9c17eab2013-07-30 19:59:12 +0000998 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
999 /*TrackUntiedDefs=*/true);
Andrew Trick88639922012-04-24 17:56:43 +00001000
Andrew Trick4add42f2012-05-10 21:06:10 +00001001 // Account for liveness generate by the region boundary.
1002 if (LiveRegionEnd != RegionEnd)
1003 RPTracker.recede();
1004
1005 // Build the DAG, and compute current register pressure.
Andrew Trick1a831342013-08-30 03:49:48 +00001006 buildSchedGraph(AA, &RPTracker, &SUPressureDiffs);
Andrew Trick02a80da2012-03-08 01:41:12 +00001007
Andrew Trick4add42f2012-05-10 21:06:10 +00001008 // Initialize top/bottom trackers after computing region pressure.
1009 initRegPressure();
Andrew Trick7a8e1002012-09-11 00:39:15 +00001010}
Andrew Trick4add42f2012-05-10 21:06:10 +00001011
Andrew Trickd7f890e2013-12-28 21:56:47 +00001012void ScheduleDAGMILive::computeDFSResult() {
Andrew Trick44f750a2013-01-25 04:01:04 +00001013 if (!DFSResult)
1014 DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize);
1015 DFSResult->clear();
Andrew Trick44f750a2013-01-25 04:01:04 +00001016 ScheduledTrees.clear();
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001017 DFSResult->resize(SUnits.size());
1018 DFSResult->compute(SUnits);
Andrew Trick44f750a2013-01-25 04:01:04 +00001019 ScheduledTrees.resize(DFSResult->getNumSubtrees());
1020}
1021
Andrew Trick483f4192013-08-29 18:04:49 +00001022/// Compute the max cyclic critical path through the DAG. The scheduling DAG
1023/// only provides the critical path for single block loops. To handle loops that
1024/// span blocks, we could use the vreg path latencies provided by
1025/// MachineTraceMetrics instead. However, MachineTraceMetrics is not currently
1026/// available for use in the scheduler.
1027///
1028/// The cyclic path estimation identifies a def-use pair that crosses the back
Andrew Trickef80f502013-08-30 02:02:12 +00001029/// edge and considers the depth and height of the nodes. For example, consider
Andrew Trick483f4192013-08-29 18:04:49 +00001030/// the following instruction sequence where each instruction has unit latency
1031/// and defines an epomymous virtual register:
1032///
1033/// a->b(a,c)->c(b)->d(c)->exit
1034///
1035/// The cyclic critical path is a two cycles: b->c->b
1036/// The acyclic critical path is four cycles: a->b->c->d->exit
1037/// LiveOutHeight = height(c) = len(c->d->exit) = 2
1038/// LiveOutDepth = depth(c) + 1 = len(a->b->c) + 1 = 3
1039/// LiveInHeight = height(b) + 1 = len(b->c->d->exit) + 1 = 4
1040/// LiveInDepth = depth(b) = len(a->b) = 1
1041///
1042/// LiveOutDepth - LiveInDepth = 3 - 1 = 2
1043/// LiveInHeight - LiveOutHeight = 4 - 2 = 2
1044/// CyclicCriticalPath = min(2, 2) = 2
Andrew Trickd7f890e2013-12-28 21:56:47 +00001045///
1046/// This could be relevant to PostRA scheduling, but is currently implemented
1047/// assuming LiveIntervals.
1048unsigned ScheduleDAGMILive::computeCyclicCriticalPath() {
Andrew Trick483f4192013-08-29 18:04:49 +00001049 // This only applies to single block loop.
1050 if (!BB->isSuccessor(BB))
1051 return 0;
1052
1053 unsigned MaxCyclicLatency = 0;
1054 // Visit each live out vreg def to find def/use pairs that cross iterations.
1055 ArrayRef<unsigned> LiveOuts = RPTracker.getPressure().LiveOutRegs;
1056 for (ArrayRef<unsigned>::iterator RI = LiveOuts.begin(), RE = LiveOuts.end();
1057 RI != RE; ++RI) {
1058 unsigned Reg = *RI;
1059 if (!TRI->isVirtualRegister(Reg))
1060 continue;
1061 const LiveInterval &LI = LIS->getInterval(Reg);
1062 const VNInfo *DefVNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
1063 if (!DefVNI)
1064 continue;
1065
1066 MachineInstr *DefMI = LIS->getInstructionFromIndex(DefVNI->def);
1067 const SUnit *DefSU = getSUnit(DefMI);
1068 if (!DefSU)
1069 continue;
1070
1071 unsigned LiveOutHeight = DefSU->getHeight();
1072 unsigned LiveOutDepth = DefSU->getDepth() + DefSU->Latency;
1073 // Visit all local users of the vreg def.
1074 for (VReg2UseMap::iterator
1075 UI = VRegUses.find(Reg); UI != VRegUses.end(); ++UI) {
1076 if (UI->SU == &ExitSU)
1077 continue;
1078
1079 // Only consider uses of the phi.
Matthias Braun88dd0ab2013-10-10 21:28:52 +00001080 LiveQueryResult LRQ =
1081 LI.Query(LIS->getInstructionIndex(UI->SU->getInstr()));
Andrew Trick483f4192013-08-29 18:04:49 +00001082 if (!LRQ.valueIn()->isPHIDef())
1083 continue;
1084
1085 // Assume that a path spanning two iterations is a cycle, which could
1086 // overestimate in strange cases. This allows cyclic latency to be
1087 // estimated as the minimum slack of the vreg's depth or height.
1088 unsigned CyclicLatency = 0;
1089 if (LiveOutDepth > UI->SU->getDepth())
1090 CyclicLatency = LiveOutDepth - UI->SU->getDepth();
1091
1092 unsigned LiveInHeight = UI->SU->getHeight() + DefSU->Latency;
1093 if (LiveInHeight > LiveOutHeight) {
1094 if (LiveInHeight - LiveOutHeight < CyclicLatency)
1095 CyclicLatency = LiveInHeight - LiveOutHeight;
1096 }
1097 else
1098 CyclicLatency = 0;
1099
1100 DEBUG(dbgs() << "Cyclic Path: SU(" << DefSU->NodeNum << ") -> SU("
1101 << UI->SU->NodeNum << ") = " << CyclicLatency << "c\n");
1102 if (CyclicLatency > MaxCyclicLatency)
1103 MaxCyclicLatency = CyclicLatency;
1104 }
1105 }
1106 DEBUG(dbgs() << "Cyclic Critical Path: " << MaxCyclicLatency << "c\n");
1107 return MaxCyclicLatency;
1108}
1109
Andrew Trick7a8e1002012-09-11 00:39:15 +00001110/// Move an instruction and update register pressure.
Andrew Trickd7f890e2013-12-28 21:56:47 +00001111void ScheduleDAGMILive::scheduleMI(SUnit *SU, bool IsTopNode) {
Andrew Trick7a8e1002012-09-11 00:39:15 +00001112 // Move the instruction to its new location in the instruction stream.
1113 MachineInstr *MI = SU->getInstr();
Andrew Trick02a80da2012-03-08 01:41:12 +00001114
Andrew Trick7a8e1002012-09-11 00:39:15 +00001115 if (IsTopNode) {
1116 assert(SU->isTopReady() && "node still has unscheduled dependencies");
1117 if (&*CurrentTop == MI)
1118 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
Andrew Trick8823dec2012-03-14 04:00:41 +00001119 else {
Andrew Trick7a8e1002012-09-11 00:39:15 +00001120 moveInstruction(MI, CurrentTop);
1121 TopRPTracker.setPos(MI);
Andrew Trick8823dec2012-03-14 04:00:41 +00001122 }
Andrew Trickc3ea0052012-04-24 18:04:37 +00001123
Andrew Trickb6e74712013-09-04 20:59:59 +00001124 if (ShouldTrackPressure) {
1125 // Update top scheduled pressure.
1126 TopRPTracker.advance();
1127 assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
Andrew Trickb248b4a2013-09-06 17:32:47 +00001128 updateScheduledPressure(SU, TopRPTracker.getPressure().MaxSetPressure);
Andrew Trickb6e74712013-09-04 20:59:59 +00001129 }
Andrew Trick7a8e1002012-09-11 00:39:15 +00001130 }
1131 else {
1132 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
1133 MachineBasicBlock::iterator priorII =
1134 priorNonDebug(CurrentBottom, CurrentTop);
1135 if (&*priorII == MI)
1136 CurrentBottom = priorII;
1137 else {
1138 if (&*CurrentTop == MI) {
1139 CurrentTop = nextIfDebug(++CurrentTop, priorII);
1140 TopRPTracker.setPos(CurrentTop);
1141 }
1142 moveInstruction(MI, CurrentBottom);
1143 CurrentBottom = MI;
1144 }
Andrew Trickb6e74712013-09-04 20:59:59 +00001145 if (ShouldTrackPressure) {
1146 // Update bottom scheduled pressure.
1147 SmallVector<unsigned, 8> LiveUses;
1148 BotRPTracker.recede(&LiveUses);
1149 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
Andrew Trickb248b4a2013-09-06 17:32:47 +00001150 updateScheduledPressure(SU, BotRPTracker.getPressure().MaxSetPressure);
Andrew Trickb6e74712013-09-04 20:59:59 +00001151 updatePressureDiffs(LiveUses);
Andrew Trickb6e74712013-09-04 20:59:59 +00001152 }
Andrew Trick7a8e1002012-09-11 00:39:15 +00001153 }
1154}
1155
Andrew Trick263280242012-11-12 19:52:20 +00001156//===----------------------------------------------------------------------===//
1157// LoadClusterMutation - DAG post-processing to cluster loads.
1158//===----------------------------------------------------------------------===//
1159
Andrew Tricka7714a02012-11-12 19:40:10 +00001160namespace {
1161/// \brief Post-process the DAG to create cluster edges between neighboring
1162/// loads.
1163class LoadClusterMutation : public ScheduleDAGMutation {
1164 struct LoadInfo {
1165 SUnit *SU;
1166 unsigned BaseReg;
1167 unsigned Offset;
1168 LoadInfo(SUnit *su, unsigned reg, unsigned ofs)
1169 : SU(su), BaseReg(reg), Offset(ofs) {}
1170 };
1171 static bool LoadInfoLess(const LoadClusterMutation::LoadInfo &LHS,
1172 const LoadClusterMutation::LoadInfo &RHS);
1173
1174 const TargetInstrInfo *TII;
1175 const TargetRegisterInfo *TRI;
1176public:
1177 LoadClusterMutation(const TargetInstrInfo *tii,
1178 const TargetRegisterInfo *tri)
1179 : TII(tii), TRI(tri) {}
1180
1181 virtual void apply(ScheduleDAGMI *DAG);
1182protected:
1183 void clusterNeighboringLoads(ArrayRef<SUnit*> Loads, ScheduleDAGMI *DAG);
1184};
1185} // anonymous
1186
1187bool LoadClusterMutation::LoadInfoLess(
1188 const LoadClusterMutation::LoadInfo &LHS,
1189 const LoadClusterMutation::LoadInfo &RHS) {
1190 if (LHS.BaseReg != RHS.BaseReg)
1191 return LHS.BaseReg < RHS.BaseReg;
1192 return LHS.Offset < RHS.Offset;
1193}
1194
1195void LoadClusterMutation::clusterNeighboringLoads(ArrayRef<SUnit*> Loads,
1196 ScheduleDAGMI *DAG) {
1197 SmallVector<LoadClusterMutation::LoadInfo,32> LoadRecords;
1198 for (unsigned Idx = 0, End = Loads.size(); Idx != End; ++Idx) {
1199 SUnit *SU = Loads[Idx];
1200 unsigned BaseReg;
1201 unsigned Offset;
1202 if (TII->getLdStBaseRegImmOfs(SU->getInstr(), BaseReg, Offset, TRI))
1203 LoadRecords.push_back(LoadInfo(SU, BaseReg, Offset));
1204 }
1205 if (LoadRecords.size() < 2)
1206 return;
1207 std::sort(LoadRecords.begin(), LoadRecords.end(), LoadInfoLess);
1208 unsigned ClusterLength = 1;
1209 for (unsigned Idx = 0, End = LoadRecords.size(); Idx < (End - 1); ++Idx) {
1210 if (LoadRecords[Idx].BaseReg != LoadRecords[Idx+1].BaseReg) {
1211 ClusterLength = 1;
1212 continue;
1213 }
1214
1215 SUnit *SUa = LoadRecords[Idx].SU;
1216 SUnit *SUb = LoadRecords[Idx+1].SU;
Andrew Trickec369d52012-11-12 21:28:10 +00001217 if (TII->shouldClusterLoads(SUa->getInstr(), SUb->getInstr(), ClusterLength)
Andrew Tricka7714a02012-11-12 19:40:10 +00001218 && DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
1219
1220 DEBUG(dbgs() << "Cluster loads SU(" << SUa->NodeNum << ") - SU("
1221 << SUb->NodeNum << ")\n");
1222 // Copy successor edges from SUa to SUb. Interleaving computation
1223 // dependent on SUa can prevent load combining due to register reuse.
1224 // Predecessor edges do not need to be copied from SUb to SUa since nearby
1225 // loads should have effectively the same inputs.
1226 for (SUnit::const_succ_iterator
1227 SI = SUa->Succs.begin(), SE = SUa->Succs.end(); SI != SE; ++SI) {
1228 if (SI->getSUnit() == SUb)
1229 continue;
1230 DEBUG(dbgs() << " Copy Succ SU(" << SI->getSUnit()->NodeNum << ")\n");
1231 DAG->addEdge(SI->getSUnit(), SDep(SUb, SDep::Artificial));
1232 }
1233 ++ClusterLength;
1234 }
1235 else
1236 ClusterLength = 1;
1237 }
1238}
1239
1240/// \brief Callback from DAG postProcessing to create cluster edges for loads.
1241void LoadClusterMutation::apply(ScheduleDAGMI *DAG) {
1242 // Map DAG NodeNum to store chain ID.
1243 DenseMap<unsigned, unsigned> StoreChainIDs;
1244 // Map each store chain to a set of dependent loads.
1245 SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
1246 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
1247 SUnit *SU = &DAG->SUnits[Idx];
1248 if (!SU->getInstr()->mayLoad())
1249 continue;
1250 unsigned ChainPredID = DAG->SUnits.size();
1251 for (SUnit::const_pred_iterator
1252 PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
1253 if (PI->isCtrl()) {
1254 ChainPredID = PI->getSUnit()->NodeNum;
1255 break;
1256 }
1257 }
1258 // Check if this chain-like pred has been seen
1259 // before. ChainPredID==MaxNodeID for loads at the top of the schedule.
1260 unsigned NumChains = StoreChainDependents.size();
1261 std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
1262 StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
1263 if (Result.second)
1264 StoreChainDependents.resize(NumChains + 1);
1265 StoreChainDependents[Result.first->second].push_back(SU);
1266 }
1267 // Iterate over the store chains.
1268 for (unsigned Idx = 0, End = StoreChainDependents.size(); Idx != End; ++Idx)
1269 clusterNeighboringLoads(StoreChainDependents[Idx], DAG);
1270}
1271
Andrew Trick02a80da2012-03-08 01:41:12 +00001272//===----------------------------------------------------------------------===//
Andrew Trick263280242012-11-12 19:52:20 +00001273// MacroFusion - DAG post-processing to encourage fusion of macro ops.
1274//===----------------------------------------------------------------------===//
1275
1276namespace {
1277/// \brief Post-process the DAG to create cluster edges between instructions
1278/// that may be fused by the processor into a single operation.
1279class MacroFusion : public ScheduleDAGMutation {
1280 const TargetInstrInfo *TII;
1281public:
1282 MacroFusion(const TargetInstrInfo *tii): TII(tii) {}
1283
1284 virtual void apply(ScheduleDAGMI *DAG);
1285};
1286} // anonymous
1287
1288/// \brief Callback from DAG postProcessing to create cluster edges to encourage
1289/// fused operations.
1290void MacroFusion::apply(ScheduleDAGMI *DAG) {
1291 // For now, assume targets can only fuse with the branch.
1292 MachineInstr *Branch = DAG->ExitSU.getInstr();
1293 if (!Branch)
1294 return;
1295
1296 for (unsigned Idx = DAG->SUnits.size(); Idx > 0;) {
1297 SUnit *SU = &DAG->SUnits[--Idx];
1298 if (!TII->shouldScheduleAdjacent(SU->getInstr(), Branch))
1299 continue;
1300
1301 // Create a single weak edge from SU to ExitSU. The only effect is to cause
1302 // bottom-up scheduling to heavily prioritize the clustered SU. There is no
1303 // need to copy predecessor edges from ExitSU to SU, since top-down
1304 // scheduling cannot prioritize ExitSU anyway. To defer top-down scheduling
1305 // of SU, we could create an artificial edge from the deepest root, but it
1306 // hasn't been needed yet.
1307 bool Success = DAG->addEdge(&DAG->ExitSU, SDep(SU, SDep::Cluster));
1308 (void)Success;
1309 assert(Success && "No DAG nodes should be reachable from ExitSU");
1310
1311 DEBUG(dbgs() << "Macro Fuse SU(" << SU->NodeNum << ")\n");
1312 break;
1313 }
1314}
1315
1316//===----------------------------------------------------------------------===//
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001317// CopyConstrain - DAG post-processing to encourage copy elimination.
1318//===----------------------------------------------------------------------===//
1319
1320namespace {
1321/// \brief Post-process the DAG to create weak edges from all uses of a copy to
1322/// the one use that defines the copy's source vreg, most likely an induction
1323/// variable increment.
1324class CopyConstrain : public ScheduleDAGMutation {
1325 // Transient state.
1326 SlotIndex RegionBeginIdx;
Andrew Trick2e875172013-04-24 23:19:56 +00001327 // RegionEndIdx is the slot index of the last non-debug instruction in the
1328 // scheduling region. So we may have RegionBeginIdx == RegionEndIdx.
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001329 SlotIndex RegionEndIdx;
1330public:
1331 CopyConstrain(const TargetInstrInfo *, const TargetRegisterInfo *) {}
1332
1333 virtual void apply(ScheduleDAGMI *DAG);
1334
1335protected:
Andrew Trickd7f890e2013-12-28 21:56:47 +00001336 void constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG);
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001337};
1338} // anonymous
1339
1340/// constrainLocalCopy handles two possibilities:
1341/// 1) Local src:
1342/// I0: = dst
1343/// I1: src = ...
1344/// I2: = dst
1345/// I3: dst = src (copy)
1346/// (create pred->succ edges I0->I1, I2->I1)
1347///
1348/// 2) Local copy:
1349/// I0: dst = src (copy)
1350/// I1: = dst
1351/// I2: src = ...
1352/// I3: = dst
1353/// (create pred->succ edges I1->I2, I3->I2)
1354///
1355/// Although the MachineScheduler is currently constrained to single blocks,
1356/// this algorithm should handle extended blocks. An EBB is a set of
1357/// contiguously numbered blocks such that the previous block in the EBB is
1358/// always the single predecessor.
Andrew Trickd7f890e2013-12-28 21:56:47 +00001359void CopyConstrain::constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG) {
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001360 LiveIntervals *LIS = DAG->getLIS();
1361 MachineInstr *Copy = CopySU->getInstr();
1362
1363 // Check for pure vreg copies.
1364 unsigned SrcReg = Copy->getOperand(1).getReg();
1365 if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
1366 return;
1367
1368 unsigned DstReg = Copy->getOperand(0).getReg();
1369 if (!TargetRegisterInfo::isVirtualRegister(DstReg))
1370 return;
1371
1372 // Check if either the dest or source is local. If it's live across a back
1373 // edge, it's not local. Note that if both vregs are live across the back
1374 // edge, we cannot successfully contrain the copy without cyclic scheduling.
1375 unsigned LocalReg = DstReg;
1376 unsigned GlobalReg = SrcReg;
1377 LiveInterval *LocalLI = &LIS->getInterval(LocalReg);
1378 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx)) {
1379 LocalReg = SrcReg;
1380 GlobalReg = DstReg;
1381 LocalLI = &LIS->getInterval(LocalReg);
1382 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx))
1383 return;
1384 }
1385 LiveInterval *GlobalLI = &LIS->getInterval(GlobalReg);
1386
1387 // Find the global segment after the start of the local LI.
1388 LiveInterval::iterator GlobalSegment = GlobalLI->find(LocalLI->beginIndex());
1389 // If GlobalLI does not overlap LocalLI->start, then a copy directly feeds a
1390 // local live range. We could create edges from other global uses to the local
1391 // start, but the coalescer should have already eliminated these cases, so
1392 // don't bother dealing with it.
1393 if (GlobalSegment == GlobalLI->end())
1394 return;
1395
1396 // If GlobalSegment is killed at the LocalLI->start, the call to find()
1397 // returned the next global segment. But if GlobalSegment overlaps with
1398 // LocalLI->start, then advance to the next segement. If a hole in GlobalLI
1399 // exists in LocalLI's vicinity, GlobalSegment will be the end of the hole.
1400 if (GlobalSegment->contains(LocalLI->beginIndex()))
1401 ++GlobalSegment;
1402
1403 if (GlobalSegment == GlobalLI->end())
1404 return;
1405
1406 // Check if GlobalLI contains a hole in the vicinity of LocalLI.
1407 if (GlobalSegment != GlobalLI->begin()) {
1408 // Two address defs have no hole.
1409 if (SlotIndex::isSameInstr(llvm::prior(GlobalSegment)->end,
1410 GlobalSegment->start)) {
1411 return;
1412 }
Andrew Trickd9761772013-07-30 19:59:08 +00001413 // If the prior global segment may be defined by the same two-address
1414 // instruction that also defines LocalLI, then can't make a hole here.
1415 if (SlotIndex::isSameInstr(llvm::prior(GlobalSegment)->start,
1416 LocalLI->beginIndex())) {
1417 return;
1418 }
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001419 // If GlobalLI has a prior segment, it must be live into the EBB. Otherwise
1420 // it would be a disconnected component in the live range.
1421 assert(llvm::prior(GlobalSegment)->start < LocalLI->beginIndex() &&
1422 "Disconnected LRG within the scheduling region.");
1423 }
1424 MachineInstr *GlobalDef = LIS->getInstructionFromIndex(GlobalSegment->start);
1425 if (!GlobalDef)
1426 return;
1427
1428 SUnit *GlobalSU = DAG->getSUnit(GlobalDef);
1429 if (!GlobalSU)
1430 return;
1431
1432 // GlobalDef is the bottom of the GlobalLI hole. Open the hole by
1433 // constraining the uses of the last local def to precede GlobalDef.
1434 SmallVector<SUnit*,8> LocalUses;
1435 const VNInfo *LastLocalVN = LocalLI->getVNInfoBefore(LocalLI->endIndex());
1436 MachineInstr *LastLocalDef = LIS->getInstructionFromIndex(LastLocalVN->def);
1437 SUnit *LastLocalSU = DAG->getSUnit(LastLocalDef);
1438 for (SUnit::const_succ_iterator
1439 I = LastLocalSU->Succs.begin(), E = LastLocalSU->Succs.end();
1440 I != E; ++I) {
1441 if (I->getKind() != SDep::Data || I->getReg() != LocalReg)
1442 continue;
1443 if (I->getSUnit() == GlobalSU)
1444 continue;
1445 if (!DAG->canAddEdge(GlobalSU, I->getSUnit()))
1446 return;
1447 LocalUses.push_back(I->getSUnit());
1448 }
1449 // Open the top of the GlobalLI hole by constraining any earlier global uses
1450 // to precede the start of LocalLI.
1451 SmallVector<SUnit*,8> GlobalUses;
1452 MachineInstr *FirstLocalDef =
1453 LIS->getInstructionFromIndex(LocalLI->beginIndex());
1454 SUnit *FirstLocalSU = DAG->getSUnit(FirstLocalDef);
1455 for (SUnit::const_pred_iterator
1456 I = GlobalSU->Preds.begin(), E = GlobalSU->Preds.end(); I != E; ++I) {
1457 if (I->getKind() != SDep::Anti || I->getReg() != GlobalReg)
1458 continue;
1459 if (I->getSUnit() == FirstLocalSU)
1460 continue;
1461 if (!DAG->canAddEdge(FirstLocalSU, I->getSUnit()))
1462 return;
1463 GlobalUses.push_back(I->getSUnit());
1464 }
1465 DEBUG(dbgs() << "Constraining copy SU(" << CopySU->NodeNum << ")\n");
1466 // Add the weak edges.
1467 for (SmallVectorImpl<SUnit*>::const_iterator
1468 I = LocalUses.begin(), E = LocalUses.end(); I != E; ++I) {
1469 DEBUG(dbgs() << " Local use SU(" << (*I)->NodeNum << ") -> SU("
1470 << GlobalSU->NodeNum << ")\n");
1471 DAG->addEdge(GlobalSU, SDep(*I, SDep::Weak));
1472 }
1473 for (SmallVectorImpl<SUnit*>::const_iterator
1474 I = GlobalUses.begin(), E = GlobalUses.end(); I != E; ++I) {
1475 DEBUG(dbgs() << " Global use SU(" << (*I)->NodeNum << ") -> SU("
1476 << FirstLocalSU->NodeNum << ")\n");
1477 DAG->addEdge(FirstLocalSU, SDep(*I, SDep::Weak));
1478 }
1479}
1480
1481/// \brief Callback from DAG postProcessing to create weak edges to encourage
1482/// copy elimination.
1483void CopyConstrain::apply(ScheduleDAGMI *DAG) {
Andrew Trickd7f890e2013-12-28 21:56:47 +00001484 assert(DAG->hasVRegLiveness() && "Expect VRegs with LiveIntervals");
1485
Andrew Trick2e875172013-04-24 23:19:56 +00001486 MachineBasicBlock::iterator FirstPos = nextIfDebug(DAG->begin(), DAG->end());
1487 if (FirstPos == DAG->end())
1488 return;
1489 RegionBeginIdx = DAG->getLIS()->getInstructionIndex(&*FirstPos);
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001490 RegionEndIdx = DAG->getLIS()->getInstructionIndex(
1491 &*priorNonDebug(DAG->end(), DAG->begin()));
1492
1493 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
1494 SUnit *SU = &DAG->SUnits[Idx];
1495 if (!SU->getInstr()->isCopy())
1496 continue;
1497
Andrew Trickd7f890e2013-12-28 21:56:47 +00001498 constrainLocalCopy(SU, static_cast<ScheduleDAGMILive*>(DAG));
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001499 }
1500}
1501
1502//===----------------------------------------------------------------------===//
Andrew Trickfc127d12013-12-07 05:59:44 +00001503// MachineSchedStrategy helpers used by GenericScheduler, GenericPostScheduler
1504// and possibly other custom schedulers.
1505// ===----------------------------------------------------------------------===/
Andrew Tricke1c034f2012-01-17 06:55:03 +00001506
Andrew Trick5a22df42013-12-05 17:56:02 +00001507static const unsigned InvalidCycle = ~0U;
1508
Andrew Trickfc127d12013-12-07 05:59:44 +00001509SchedBoundary::~SchedBoundary() { delete HazardRec; }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001510
Andrew Trickfc127d12013-12-07 05:59:44 +00001511void SchedBoundary::reset() {
1512 // A new HazardRec is created for each DAG and owned by SchedBoundary.
1513 // Destroying and reconstructing it is very expensive though. So keep
1514 // invalid, placeholder HazardRecs.
1515 if (HazardRec && HazardRec->isEnabled()) {
1516 delete HazardRec;
1517 HazardRec = 0;
1518 }
1519 Available.clear();
1520 Pending.clear();
1521 CheckPending = false;
1522 NextSUs.clear();
1523 CurrCycle = 0;
1524 CurrMOps = 0;
1525 MinReadyCycle = UINT_MAX;
1526 ExpectedLatency = 0;
1527 DependentLatency = 0;
1528 RetiredMOps = 0;
1529 MaxExecutedResCount = 0;
1530 ZoneCritResIdx = 0;
1531 IsResourceLimited = false;
1532 ReservedCycles.clear();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001533#ifndef NDEBUG
Andrew Trickfc127d12013-12-07 05:59:44 +00001534 MaxObservedLatency = 0;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001535#endif
Andrew Trickfc127d12013-12-07 05:59:44 +00001536 // Reserve a zero-count for invalid CritResIdx.
1537 ExecutedResCounts.resize(1);
1538 assert(!ExecutedResCounts[0] && "nonzero count for bad resource");
1539}
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001540
Andrew Trickfc127d12013-12-07 05:59:44 +00001541void SchedRemainder::
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001542init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
1543 reset();
1544 if (!SchedModel->hasInstrSchedModel())
1545 return;
1546 RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
1547 for (std::vector<SUnit>::iterator
1548 I = DAG->SUnits.begin(), E = DAG->SUnits.end(); I != E; ++I) {
1549 const MCSchedClassDesc *SC = DAG->getSchedClass(&*I);
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001550 RemIssueCount += SchedModel->getNumMicroOps(I->getInstr(), SC)
1551 * SchedModel->getMicroOpFactor();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001552 for (TargetSchedModel::ProcResIter
1553 PI = SchedModel->getWriteProcResBegin(SC),
1554 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1555 unsigned PIdx = PI->ProcResourceIdx;
1556 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1557 RemainingCounts[PIdx] += (Factor * PI->Cycles);
1558 }
1559 }
1560}
1561
Andrew Trickfc127d12013-12-07 05:59:44 +00001562void SchedBoundary::
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001563init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
1564 reset();
1565 DAG = dag;
1566 SchedModel = smodel;
1567 Rem = rem;
Andrew Trick5a22df42013-12-05 17:56:02 +00001568 if (SchedModel->hasInstrSchedModel()) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001569 ExecutedResCounts.resize(SchedModel->getNumProcResourceKinds());
Andrew Trick5a22df42013-12-05 17:56:02 +00001570 ReservedCycles.resize(SchedModel->getNumProcResourceKinds(), InvalidCycle);
1571 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001572}
1573
Andrew Trick880e5732013-12-05 17:55:58 +00001574/// Compute the stall cycles based on this SUnit's ready time. Heuristics treat
1575/// these "soft stalls" differently than the hard stall cycles based on CPU
1576/// resources and computed by checkHazard(). A fully in-order model
1577/// (MicroOpBufferSize==0) will not make use of this since instructions are not
1578/// available for scheduling until they are ready. However, a weaker in-order
1579/// model may use this for heuristics. For example, if a processor has in-order
1580/// behavior when reading certain resources, this may come into play.
Andrew Trickfc127d12013-12-07 05:59:44 +00001581unsigned SchedBoundary::getLatencyStallCycles(SUnit *SU) {
Andrew Trick880e5732013-12-05 17:55:58 +00001582 if (!SU->isUnbuffered)
1583 return 0;
1584
1585 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
1586 if (ReadyCycle > CurrCycle)
1587 return ReadyCycle - CurrCycle;
1588 return 0;
1589}
1590
Andrew Trick5a22df42013-12-05 17:56:02 +00001591/// Compute the next cycle at which the given processor resource can be
1592/// scheduled.
Andrew Trickfc127d12013-12-07 05:59:44 +00001593unsigned SchedBoundary::
Andrew Trick5a22df42013-12-05 17:56:02 +00001594getNextResourceCycle(unsigned PIdx, unsigned Cycles) {
1595 unsigned NextUnreserved = ReservedCycles[PIdx];
1596 // If this resource has never been used, always return cycle zero.
1597 if (NextUnreserved == InvalidCycle)
1598 return 0;
1599 // For bottom-up scheduling add the cycles needed for the current operation.
1600 if (!isTop())
1601 NextUnreserved += Cycles;
1602 return NextUnreserved;
1603}
1604
Andrew Trick8c9e6722012-06-29 03:23:24 +00001605/// Does this SU have a hazard within the current instruction group.
1606///
1607/// The scheduler supports two modes of hazard recognition. The first is the
1608/// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
1609/// supports highly complicated in-order reservation tables
1610/// (ScoreboardHazardRecognizer) and arbitraty target-specific logic.
1611///
1612/// The second is a streamlined mechanism that checks for hazards based on
1613/// simple counters that the scheduler itself maintains. It explicitly checks
1614/// for instruction dispatch limitations, including the number of micro-ops that
1615/// can dispatch per cycle.
1616///
1617/// TODO: Also check whether the SU must start a new group.
Andrew Trickfc127d12013-12-07 05:59:44 +00001618bool SchedBoundary::checkHazard(SUnit *SU) {
Andrew Trick8c9e6722012-06-29 03:23:24 +00001619 if (HazardRec->isEnabled())
1620 return HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard;
1621
Andrew Trickdd79f0f2012-10-10 05:43:09 +00001622 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
Andrew Tricke2ff5752013-06-15 04:49:49 +00001623 if ((CurrMOps > 0) && (CurrMOps + uops > SchedModel->getIssueWidth())) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001624 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") uops="
1625 << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
Andrew Trick8c9e6722012-06-29 03:23:24 +00001626 return true;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001627 }
Andrew Trick5a22df42013-12-05 17:56:02 +00001628 if (SchedModel->hasInstrSchedModel() && SU->hasReservedResource) {
1629 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1630 for (TargetSchedModel::ProcResIter
1631 PI = SchedModel->getWriteProcResBegin(SC),
1632 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1633 if (getNextResourceCycle(PI->ProcResourceIdx, PI->Cycles) > CurrCycle)
1634 return true;
1635 }
1636 }
Andrew Trick8c9e6722012-06-29 03:23:24 +00001637 return false;
1638}
1639
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001640// Find the unscheduled node in ReadySUs with the highest latency.
Andrew Trickfc127d12013-12-07 05:59:44 +00001641unsigned SchedBoundary::
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001642findMaxLatency(ArrayRef<SUnit*> ReadySUs) {
1643 SUnit *LateSU = 0;
1644 unsigned RemLatency = 0;
1645 for (ArrayRef<SUnit*>::iterator I = ReadySUs.begin(), E = ReadySUs.end();
Andrew Trickd6d5ad32012-12-18 20:52:56 +00001646 I != E; ++I) {
1647 unsigned L = getUnscheduledLatency(*I);
Andrew Trickf5b8ef22013-06-15 04:49:44 +00001648 if (L > RemLatency) {
Andrew Trickd6d5ad32012-12-18 20:52:56 +00001649 RemLatency = L;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001650 LateSU = *I;
Andrew Trickf5b8ef22013-06-15 04:49:44 +00001651 }
Andrew Trickd6d5ad32012-12-18 20:52:56 +00001652 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001653 if (LateSU) {
1654 DEBUG(dbgs() << Available.getName() << " RemLatency SU("
1655 << LateSU->NodeNum << ") " << RemLatency << "c\n");
Andrew Trickd6d5ad32012-12-18 20:52:56 +00001656 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001657 return RemLatency;
1658}
Andrew Trickf5b8ef22013-06-15 04:49:44 +00001659
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001660// Count resources in this zone and the remaining unscheduled
1661// instruction. Return the max count, scaled. Set OtherCritIdx to the critical
1662// resource index, or zero if the zone is issue limited.
Andrew Trickfc127d12013-12-07 05:59:44 +00001663unsigned SchedBoundary::
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001664getOtherResourceCount(unsigned &OtherCritIdx) {
Alexey Samsonov64c391d2013-07-19 08:55:18 +00001665 OtherCritIdx = 0;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001666 if (!SchedModel->hasInstrSchedModel())
1667 return 0;
1668
1669 unsigned OtherCritCount = Rem->RemIssueCount
1670 + (RetiredMOps * SchedModel->getMicroOpFactor());
1671 DEBUG(dbgs() << " " << Available.getName() << " + Remain MOps: "
1672 << OtherCritCount / SchedModel->getMicroOpFactor() << '\n');
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001673 for (unsigned PIdx = 1, PEnd = SchedModel->getNumProcResourceKinds();
1674 PIdx != PEnd; ++PIdx) {
1675 unsigned OtherCount = getResourceCount(PIdx) + Rem->RemainingCounts[PIdx];
1676 if (OtherCount > OtherCritCount) {
1677 OtherCritCount = OtherCount;
1678 OtherCritIdx = PIdx;
1679 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001680 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001681 if (OtherCritIdx) {
1682 DEBUG(dbgs() << " " << Available.getName() << " + Remain CritRes: "
1683 << OtherCritCount / SchedModel->getResourceFactor(OtherCritIdx)
Andrew Trickfc127d12013-12-07 05:59:44 +00001684 << " " << SchedModel->getResourceName(OtherCritIdx) << "\n");
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001685 }
1686 return OtherCritCount;
1687}
1688
Andrew Trickfc127d12013-12-07 05:59:44 +00001689void SchedBoundary::releaseNode(SUnit *SU, unsigned ReadyCycle) {
Andrew Trick61f1a272012-05-24 22:11:09 +00001690 if (ReadyCycle < MinReadyCycle)
1691 MinReadyCycle = ReadyCycle;
1692
1693 // Check for interlocks first. For the purpose of other heuristics, an
1694 // instruction that cannot issue appears as if it's not in the ReadyQueue.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001695 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
1696 if ((!IsBuffered && ReadyCycle > CurrCycle) || checkHazard(SU))
Andrew Trick61f1a272012-05-24 22:11:09 +00001697 Pending.push(SU);
1698 else
1699 Available.push(SU);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001700
1701 // Record this node as an immediate dependent of the scheduled node.
1702 NextSUs.insert(SU);
Andrew Trick61f1a272012-05-24 22:11:09 +00001703}
1704
Andrew Trickfc127d12013-12-07 05:59:44 +00001705void SchedBoundary::releaseTopNode(SUnit *SU) {
1706 if (SU->isScheduled)
1707 return;
1708
1709 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1710 I != E; ++I) {
1711 if (I->isWeak())
1712 continue;
1713 unsigned PredReadyCycle = I->getSUnit()->TopReadyCycle;
1714 unsigned Latency = I->getLatency();
1715#ifndef NDEBUG
1716 MaxObservedLatency = std::max(Latency, MaxObservedLatency);
1717#endif
1718 if (SU->TopReadyCycle < PredReadyCycle + Latency)
1719 SU->TopReadyCycle = PredReadyCycle + Latency;
1720 }
1721 releaseNode(SU, SU->TopReadyCycle);
1722}
1723
1724void SchedBoundary::releaseBottomNode(SUnit *SU) {
1725 if (SU->isScheduled)
1726 return;
1727
1728 assert(SU->getInstr() && "Scheduled SUnit must have instr");
1729
1730 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1731 I != E; ++I) {
1732 if (I->isWeak())
1733 continue;
1734 unsigned SuccReadyCycle = I->getSUnit()->BotReadyCycle;
1735 unsigned Latency = I->getLatency();
1736#ifndef NDEBUG
1737 MaxObservedLatency = std::max(Latency, MaxObservedLatency);
1738#endif
1739 if (SU->BotReadyCycle < SuccReadyCycle + Latency)
1740 SU->BotReadyCycle = SuccReadyCycle + Latency;
1741 }
1742 releaseNode(SU, SU->BotReadyCycle);
1743}
1744
Andrew Trick61f1a272012-05-24 22:11:09 +00001745/// Move the boundary of scheduled code by one cycle.
Andrew Trickfc127d12013-12-07 05:59:44 +00001746void SchedBoundary::bumpCycle(unsigned NextCycle) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001747 if (SchedModel->getMicroOpBufferSize() == 0) {
1748 assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
1749 if (MinReadyCycle > NextCycle)
1750 NextCycle = MinReadyCycle;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001751 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001752 // Update the current micro-ops, which will issue in the next cycle.
1753 unsigned DecMOps = SchedModel->getIssueWidth() * (NextCycle - CurrCycle);
1754 CurrMOps = (CurrMOps <= DecMOps) ? 0 : CurrMOps - DecMOps;
1755
1756 // Decrement DependentLatency based on the next cycle.
Andrew Trickf5b8ef22013-06-15 04:49:44 +00001757 if ((NextCycle - CurrCycle) > DependentLatency)
1758 DependentLatency = 0;
1759 else
1760 DependentLatency -= (NextCycle - CurrCycle);
Andrew Trick61f1a272012-05-24 22:11:09 +00001761
1762 if (!HazardRec->isEnabled()) {
Andrew Trick45446062012-06-05 21:11:27 +00001763 // Bypass HazardRec virtual calls.
Andrew Trick61f1a272012-05-24 22:11:09 +00001764 CurrCycle = NextCycle;
1765 }
1766 else {
Andrew Trick45446062012-06-05 21:11:27 +00001767 // Bypass getHazardType calls in case of long latency.
Andrew Trick61f1a272012-05-24 22:11:09 +00001768 for (; CurrCycle != NextCycle; ++CurrCycle) {
1769 if (isTop())
1770 HazardRec->AdvanceCycle();
1771 else
1772 HazardRec->RecedeCycle();
1773 }
1774 }
1775 CheckPending = true;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001776 unsigned LFactor = SchedModel->getLatencyFactor();
1777 IsResourceLimited =
1778 (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
1779 > (int)LFactor;
Andrew Trick61f1a272012-05-24 22:11:09 +00001780
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001781 DEBUG(dbgs() << "Cycle: " << CurrCycle << ' ' << Available.getName() << '\n');
1782}
1783
Andrew Trickfc127d12013-12-07 05:59:44 +00001784void SchedBoundary::incExecutedResources(unsigned PIdx, unsigned Count) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001785 ExecutedResCounts[PIdx] += Count;
1786 if (ExecutedResCounts[PIdx] > MaxExecutedResCount)
1787 MaxExecutedResCount = ExecutedResCounts[PIdx];
Andrew Trick61f1a272012-05-24 22:11:09 +00001788}
1789
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001790/// Add the given processor resource to this scheduled zone.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001791///
1792/// \param Cycles indicates the number of consecutive (non-pipelined) cycles
1793/// during which this resource is consumed.
1794///
1795/// \return the next cycle at which the instruction may execute without
1796/// oversubscribing resources.
Andrew Trickfc127d12013-12-07 05:59:44 +00001797unsigned SchedBoundary::
Andrew Trick5a22df42013-12-05 17:56:02 +00001798countResource(unsigned PIdx, unsigned Cycles, unsigned NextCycle) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001799 unsigned Factor = SchedModel->getResourceFactor(PIdx);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001800 unsigned Count = Factor * Cycles;
Andrew Trickfc127d12013-12-07 05:59:44 +00001801 DEBUG(dbgs() << " " << SchedModel->getResourceName(PIdx)
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001802 << " +" << Cycles << "x" << Factor << "u\n");
1803
1804 // Update Executed resources counts.
1805 incExecutedResources(PIdx, Count);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001806 assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
1807 Rem->RemainingCounts[PIdx] -= Count;
1808
Andrew Trickb13ef172013-07-19 00:20:07 +00001809 // Check if this resource exceeds the current critical resource. If so, it
1810 // becomes the critical resource.
1811 if (ZoneCritResIdx != PIdx && (getResourceCount(PIdx) > getCriticalCount())) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001812 ZoneCritResIdx = PIdx;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001813 DEBUG(dbgs() << " *** Critical resource "
Andrew Trickfc127d12013-12-07 05:59:44 +00001814 << SchedModel->getResourceName(PIdx) << ": "
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001815 << getResourceCount(PIdx) / SchedModel->getLatencyFactor() << "c\n");
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001816 }
Andrew Trick5a22df42013-12-05 17:56:02 +00001817 // For reserved resources, record the highest cycle using the resource.
1818 unsigned NextAvailable = getNextResourceCycle(PIdx, Cycles);
1819 if (NextAvailable > CurrCycle) {
1820 DEBUG(dbgs() << " Resource conflict: "
1821 << SchedModel->getProcResource(PIdx)->Name << " reserved until @"
1822 << NextAvailable << "\n");
1823 }
1824 return NextAvailable;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001825}
1826
Andrew Trick45446062012-06-05 21:11:27 +00001827/// Move the boundary of scheduled code by one SUnit.
Andrew Trickfc127d12013-12-07 05:59:44 +00001828void SchedBoundary::bumpNode(SUnit *SU) {
Andrew Trick45446062012-06-05 21:11:27 +00001829 // Update the reservation table.
1830 if (HazardRec->isEnabled()) {
1831 if (!isTop() && SU->isCall) {
1832 // Calls are scheduled with their preceding instructions. For bottom-up
1833 // scheduling, clear the pipeline state before emitting.
1834 HazardRec->Reset();
1835 }
1836 HazardRec->EmitInstruction(SU);
1837 }
Andrew Trick5a22df42013-12-05 17:56:02 +00001838 // checkHazard should prevent scheduling multiple instructions per cycle that
1839 // exceed the issue width.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001840 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1841 unsigned IncMOps = SchedModel->getNumMicroOps(SU->getInstr());
Daniel Jasper0d92abd2013-12-06 08:58:22 +00001842 assert(
1843 (CurrMOps == 0 || (CurrMOps + IncMOps) <= SchedModel->getIssueWidth()) &&
Andrew Trickf7760a22013-12-06 17:19:20 +00001844 "Cannot schedule this instruction's MicroOps in the current cycle.");
Andrew Trick5a22df42013-12-05 17:56:02 +00001845
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001846 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
1847 DEBUG(dbgs() << " Ready @" << ReadyCycle << "c\n");
1848
Andrew Trick5a22df42013-12-05 17:56:02 +00001849 unsigned NextCycle = CurrCycle;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001850 switch (SchedModel->getMicroOpBufferSize()) {
1851 case 0:
1852 assert(ReadyCycle <= CurrCycle && "Broken PendingQueue");
1853 break;
1854 case 1:
1855 if (ReadyCycle > NextCycle) {
1856 NextCycle = ReadyCycle;
1857 DEBUG(dbgs() << " *** Stall until: " << ReadyCycle << "\n");
1858 }
1859 break;
1860 default:
1861 // We don't currently model the OOO reorder buffer, so consider all
Andrew Trick880e5732013-12-05 17:55:58 +00001862 // scheduled MOps to be "retired". We do loosely model in-order resource
1863 // latency. If this instruction uses an in-order resource, account for any
1864 // likely stall cycles.
1865 if (SU->isUnbuffered && ReadyCycle > NextCycle)
1866 NextCycle = ReadyCycle;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001867 break;
1868 }
1869 RetiredMOps += IncMOps;
1870
1871 // Update resource counts and critical resource.
1872 if (SchedModel->hasInstrSchedModel()) {
1873 unsigned DecRemIssue = IncMOps * SchedModel->getMicroOpFactor();
1874 assert(Rem->RemIssueCount >= DecRemIssue && "MOps double counted");
1875 Rem->RemIssueCount -= DecRemIssue;
1876 if (ZoneCritResIdx) {
1877 // Scale scheduled micro-ops for comparing with the critical resource.
1878 unsigned ScaledMOps =
1879 RetiredMOps * SchedModel->getMicroOpFactor();
1880
1881 // If scaled micro-ops are now more than the previous critical resource by
1882 // a full cycle, then micro-ops issue becomes critical.
1883 if ((int)(ScaledMOps - getResourceCount(ZoneCritResIdx))
1884 >= (int)SchedModel->getLatencyFactor()) {
1885 ZoneCritResIdx = 0;
1886 DEBUG(dbgs() << " *** Critical resource NumMicroOps: "
1887 << ScaledMOps / SchedModel->getLatencyFactor() << "c\n");
1888 }
1889 }
1890 for (TargetSchedModel::ProcResIter
1891 PI = SchedModel->getWriteProcResBegin(SC),
1892 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1893 unsigned RCycle =
Andrew Trick5a22df42013-12-05 17:56:02 +00001894 countResource(PI->ProcResourceIdx, PI->Cycles, NextCycle);
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001895 if (RCycle > NextCycle)
1896 NextCycle = RCycle;
1897 }
Andrew Trick5a22df42013-12-05 17:56:02 +00001898 if (SU->hasReservedResource) {
1899 // For reserved resources, record the highest cycle using the resource.
1900 // For top-down scheduling, this is the cycle in which we schedule this
1901 // instruction plus the number of cycles the operations reserves the
1902 // resource. For bottom-up is it simply the instruction's cycle.
1903 for (TargetSchedModel::ProcResIter
1904 PI = SchedModel->getWriteProcResBegin(SC),
1905 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1906 unsigned PIdx = PI->ProcResourceIdx;
1907 if (SchedModel->getProcResource(PIdx)->BufferSize == 0)
1908 ReservedCycles[PIdx] = isTop() ? NextCycle + PI->Cycles : NextCycle;
1909 }
1910 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001911 }
1912 // Update ExpectedLatency and DependentLatency.
1913 unsigned &TopLatency = isTop() ? ExpectedLatency : DependentLatency;
1914 unsigned &BotLatency = isTop() ? DependentLatency : ExpectedLatency;
1915 if (SU->getDepth() > TopLatency) {
1916 TopLatency = SU->getDepth();
1917 DEBUG(dbgs() << " " << Available.getName()
1918 << " TopLatency SU(" << SU->NodeNum << ") " << TopLatency << "c\n");
1919 }
1920 if (SU->getHeight() > BotLatency) {
1921 BotLatency = SU->getHeight();
1922 DEBUG(dbgs() << " " << Available.getName()
1923 << " BotLatency SU(" << SU->NodeNum << ") " << BotLatency << "c\n");
1924 }
1925 // If we stall for any reason, bump the cycle.
1926 if (NextCycle > CurrCycle) {
1927 bumpCycle(NextCycle);
1928 }
1929 else {
1930 // After updating ZoneCritResIdx and ExpectedLatency, check if we're
1931 // resource limited. If a stall occured, bumpCycle does this.
1932 unsigned LFactor = SchedModel->getLatencyFactor();
1933 IsResourceLimited =
1934 (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
1935 > (int)LFactor;
1936 }
Andrew Trick5a22df42013-12-05 17:56:02 +00001937 // Update CurrMOps after calling bumpCycle to handle stalls, since bumpCycle
1938 // resets CurrMOps. Loop to handle instructions with more MOps than issue in
1939 // one cycle. Since we commonly reach the max MOps here, opportunistically
1940 // bump the cycle to avoid uselessly checking everything in the readyQ.
1941 CurrMOps += IncMOps;
1942 while (CurrMOps >= SchedModel->getIssueWidth()) {
1943 bumpCycle(++NextCycle);
1944 DEBUG(dbgs() << " *** Max MOps " << CurrMOps
1945 << " at cycle " << CurrCycle << '\n');
1946 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001947 DEBUG(dumpScheduledState());
Andrew Trick45446062012-06-05 21:11:27 +00001948}
1949
Andrew Trick61f1a272012-05-24 22:11:09 +00001950/// Release pending ready nodes in to the available queue. This makes them
1951/// visible to heuristics.
Andrew Trickfc127d12013-12-07 05:59:44 +00001952void SchedBoundary::releasePending() {
Andrew Trick61f1a272012-05-24 22:11:09 +00001953 // If the available queue is empty, it is safe to reset MinReadyCycle.
1954 if (Available.empty())
1955 MinReadyCycle = UINT_MAX;
1956
1957 // Check to see if any of the pending instructions are ready to issue. If
1958 // so, add them to the available queue.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001959 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
Andrew Trick61f1a272012-05-24 22:11:09 +00001960 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
1961 SUnit *SU = *(Pending.begin()+i);
Andrew Trick45446062012-06-05 21:11:27 +00001962 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
Andrew Trick61f1a272012-05-24 22:11:09 +00001963
1964 if (ReadyCycle < MinReadyCycle)
1965 MinReadyCycle = ReadyCycle;
1966
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001967 if (!IsBuffered && ReadyCycle > CurrCycle)
Andrew Trick61f1a272012-05-24 22:11:09 +00001968 continue;
1969
Andrew Trick8c9e6722012-06-29 03:23:24 +00001970 if (checkHazard(SU))
Andrew Trick61f1a272012-05-24 22:11:09 +00001971 continue;
1972
1973 Available.push(SU);
1974 Pending.remove(Pending.begin()+i);
1975 --i; --e;
1976 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001977 DEBUG(if (!Pending.empty()) Pending.dump());
Andrew Trick61f1a272012-05-24 22:11:09 +00001978 CheckPending = false;
1979}
1980
1981/// Remove SU from the ready set for this boundary.
Andrew Trickfc127d12013-12-07 05:59:44 +00001982void SchedBoundary::removeReady(SUnit *SU) {
Andrew Trick61f1a272012-05-24 22:11:09 +00001983 if (Available.isInQueue(SU))
1984 Available.remove(Available.find(SU));
1985 else {
1986 assert(Pending.isInQueue(SU) && "bad ready count");
1987 Pending.remove(Pending.find(SU));
1988 }
1989}
1990
1991/// If this queue only has one ready candidate, return it. As a side effect,
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001992/// defer any nodes that now hit a hazard, and advance the cycle until at least
1993/// one node is ready. If multiple instructions are ready, return NULL.
Andrew Trickfc127d12013-12-07 05:59:44 +00001994SUnit *SchedBoundary::pickOnlyChoice() {
Andrew Trick61f1a272012-05-24 22:11:09 +00001995 if (CheckPending)
1996 releasePending();
1997
Andrew Tricke2ff5752013-06-15 04:49:49 +00001998 if (CurrMOps > 0) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001999 // Defer any ready instrs that now have a hazard.
2000 for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
2001 if (checkHazard(*I)) {
2002 Pending.push(*I);
2003 I = Available.remove(I);
2004 continue;
2005 }
2006 ++I;
2007 }
2008 }
Andrew Trick61f1a272012-05-24 22:11:09 +00002009 for (unsigned i = 0; Available.empty(); ++i) {
Andrew Trickde2109e2013-06-15 04:49:57 +00002010 assert(i <= (HazardRec->getMaxLookAhead() + MaxObservedLatency) &&
Andrew Trick45446062012-06-05 21:11:27 +00002011 "permanent hazard"); (void)i;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002012 bumpCycle(CurrCycle + 1);
Andrew Trick61f1a272012-05-24 22:11:09 +00002013 releasePending();
2014 }
2015 if (Available.size() == 1)
2016 return *Available.begin();
2017 return NULL;
2018}
2019
Andrew Trick8e8415f2013-06-15 05:46:47 +00002020#ifndef NDEBUG
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002021// This is useful information to dump after bumpNode.
2022// Note that the Queue contents are more useful before pickNodeFromQueue.
Andrew Trickfc127d12013-12-07 05:59:44 +00002023void SchedBoundary::dumpScheduledState() {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002024 unsigned ResFactor;
2025 unsigned ResCount;
2026 if (ZoneCritResIdx) {
2027 ResFactor = SchedModel->getResourceFactor(ZoneCritResIdx);
2028 ResCount = getResourceCount(ZoneCritResIdx);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002029 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002030 else {
2031 ResFactor = SchedModel->getMicroOpFactor();
2032 ResCount = RetiredMOps * SchedModel->getMicroOpFactor();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002033 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002034 unsigned LFactor = SchedModel->getLatencyFactor();
2035 dbgs() << Available.getName() << " @" << CurrCycle << "c\n"
2036 << " Retired: " << RetiredMOps;
2037 dbgs() << "\n Executed: " << getExecutedCount() / LFactor << "c";
2038 dbgs() << "\n Critical: " << ResCount / LFactor << "c, "
Andrew Trickfc127d12013-12-07 05:59:44 +00002039 << ResCount / ResFactor << " "
2040 << SchedModel->getResourceName(ZoneCritResIdx)
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002041 << "\n ExpectedLatency: " << ExpectedLatency << "c\n"
2042 << (IsResourceLimited ? " - Resource" : " - Latency")
2043 << " limited.\n";
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002044}
Andrew Trick8e8415f2013-06-15 05:46:47 +00002045#endif
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002046
Andrew Trickfc127d12013-12-07 05:59:44 +00002047//===----------------------------------------------------------------------===//
2048// GenericScheduler - Implementation of the generic MachineSchedStrategy.
2049//===----------------------------------------------------------------------===//
2050
2051namespace {
2052/// GenericScheduler shrinks the unscheduled zone using heuristics to balance
2053/// the schedule.
2054class GenericScheduler : public MachineSchedStrategy {
2055public:
2056 /// Represent the type of SchedCandidate found within a single queue.
2057 /// pickNodeBidirectional depends on these listed by decreasing priority.
2058 enum CandReason {
2059 NoCand, PhysRegCopy, RegExcess, RegCritical, Stall, Cluster, Weak, RegMax,
2060 ResourceReduce, ResourceDemand, BotHeightReduce, BotPathReduce,
2061 TopDepthReduce, TopPathReduce, NextDefUse, NodeOrder};
2062
2063#ifndef NDEBUG
2064 static const char *getReasonStr(GenericScheduler::CandReason Reason);
2065#endif
2066
2067 /// Policy for scheduling the next instruction in the candidate's zone.
2068 struct CandPolicy {
2069 bool ReduceLatency;
2070 unsigned ReduceResIdx;
2071 unsigned DemandResIdx;
2072
2073 CandPolicy(): ReduceLatency(false), ReduceResIdx(0), DemandResIdx(0) {}
2074 };
2075
2076 /// Status of an instruction's critical resource consumption.
2077 struct SchedResourceDelta {
2078 // Count critical resources in the scheduled region required by SU.
2079 unsigned CritResources;
2080
2081 // Count critical resources from another region consumed by SU.
2082 unsigned DemandedResources;
2083
2084 SchedResourceDelta(): CritResources(0), DemandedResources(0) {}
2085
2086 bool operator==(const SchedResourceDelta &RHS) const {
2087 return CritResources == RHS.CritResources
2088 && DemandedResources == RHS.DemandedResources;
2089 }
2090 bool operator!=(const SchedResourceDelta &RHS) const {
2091 return !operator==(RHS);
2092 }
2093 };
2094
2095 /// Store the state used by GenericScheduler heuristics, required for the
2096 /// lifetime of one invocation of pickNode().
2097 struct SchedCandidate {
2098 CandPolicy Policy;
2099
2100 // The best SUnit candidate.
2101 SUnit *SU;
2102
2103 // The reason for this candidate.
2104 CandReason Reason;
2105
2106 // Set of reasons that apply to multiple candidates.
2107 uint32_t RepeatReasonSet;
2108
2109 // Register pressure values for the best candidate.
2110 RegPressureDelta RPDelta;
2111
2112 // Critical resource consumption of the best candidate.
2113 SchedResourceDelta ResDelta;
2114
2115 SchedCandidate(const CandPolicy &policy)
2116 : Policy(policy), SU(NULL), Reason(NoCand), RepeatReasonSet(0) {}
2117
2118 bool isValid() const { return SU; }
2119
2120 // Copy the status of another candidate without changing policy.
2121 void setBest(SchedCandidate &Best) {
2122 assert(Best.Reason != NoCand && "uninitialized Sched candidate");
2123 SU = Best.SU;
2124 Reason = Best.Reason;
2125 RPDelta = Best.RPDelta;
2126 ResDelta = Best.ResDelta;
2127 }
2128
2129 bool isRepeat(CandReason R) { return RepeatReasonSet & (1 << R); }
2130 void setRepeat(CandReason R) { RepeatReasonSet |= (1 << R); }
2131
Andrew Trickd7f890e2013-12-28 21:56:47 +00002132 void initResourceDelta(const ScheduleDAGMILive *DAG,
Andrew Trickfc127d12013-12-07 05:59:44 +00002133 const TargetSchedModel *SchedModel);
2134 };
2135
2136private:
2137 const MachineSchedContext *Context;
Andrew Trickd7f890e2013-12-28 21:56:47 +00002138 ScheduleDAGMILive *DAG;
Andrew Trickfc127d12013-12-07 05:59:44 +00002139 const TargetSchedModel *SchedModel;
2140 const TargetRegisterInfo *TRI;
2141
2142 // State of the top and bottom scheduled instruction boundaries.
2143 SchedRemainder Rem;
2144 SchedBoundary Top;
2145 SchedBoundary Bot;
2146
2147 MachineSchedPolicy RegionPolicy;
2148public:
2149 GenericScheduler(const MachineSchedContext *C):
2150 Context(C), DAG(0), SchedModel(0), TRI(0),
2151 Top(SchedBoundary::TopQID, "TopQ"), Bot(SchedBoundary::BotQID, "BotQ") {}
2152
2153 virtual void initPolicy(MachineBasicBlock::iterator Begin,
2154 MachineBasicBlock::iterator End,
2155 unsigned NumRegionInstrs);
2156
2157 bool shouldTrackPressure() const { return RegionPolicy.ShouldTrackPressure; }
2158
2159 virtual void initialize(ScheduleDAGMI *dag);
2160
2161 virtual SUnit *pickNode(bool &IsTopNode);
2162
2163 virtual void schedNode(SUnit *SU, bool IsTopNode);
2164
2165 virtual void releaseTopNode(SUnit *SU) { Top.releaseTopNode(SU); }
2166
2167 virtual void releaseBottomNode(SUnit *SU) { Bot.releaseBottomNode(SU); }
2168
2169 virtual void registerRoots();
2170
2171protected:
2172 void checkAcyclicLatency();
2173
2174 void setPolicy(CandPolicy &Policy, SchedBoundary &CurrZone,
2175 SchedBoundary &OtherZone);
2176
2177 void tryCandidate(SchedCandidate &Cand,
2178 SchedCandidate &TryCand,
2179 SchedBoundary &Zone,
2180 const RegPressureTracker &RPTracker,
2181 RegPressureTracker &TempTracker);
2182
2183 SUnit *pickNodeBidirectional(bool &IsTopNode);
2184
2185 void pickNodeFromQueue(SchedBoundary &Zone,
2186 const RegPressureTracker &RPTracker,
2187 SchedCandidate &Candidate);
2188
2189 void reschedulePhysRegCopies(SUnit *SU, bool isTop);
2190
2191#ifndef NDEBUG
2192 void traceCandidate(const SchedCandidate &Cand);
2193#endif
2194};
2195} // namespace
2196
2197void GenericScheduler::initialize(ScheduleDAGMI *dag) {
Andrew Trickd7f890e2013-12-28 21:56:47 +00002198 assert(dag->hasVRegLiveness() &&
2199 "(PreRA)GenericScheduler needs vreg liveness");
2200 DAG = static_cast<ScheduleDAGMILive*>(dag);
Andrew Trickfc127d12013-12-07 05:59:44 +00002201 SchedModel = DAG->getSchedModel();
2202 TRI = DAG->TRI;
2203
2204 Rem.init(DAG, SchedModel);
2205 Top.init(DAG, SchedModel, &Rem);
2206 Bot.init(DAG, SchedModel, &Rem);
2207
2208 // Initialize resource counts.
2209
2210 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
2211 // are disabled, then these HazardRecs will be disabled.
2212 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
2213 const TargetMachine &TM = DAG->MF.getTarget();
2214 if (!Top.HazardRec) {
2215 Top.HazardRec =
2216 TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
2217 }
2218 if (!Bot.HazardRec) {
2219 Bot.HazardRec =
2220 TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
2221 }
2222}
2223
2224/// Initialize the per-region scheduling policy.
2225void GenericScheduler::initPolicy(MachineBasicBlock::iterator Begin,
2226 MachineBasicBlock::iterator End,
2227 unsigned NumRegionInstrs) {
2228 const TargetMachine &TM = Context->MF->getTarget();
2229
2230 // Avoid setting up the register pressure tracker for small regions to save
2231 // compile time. As a rough heuristic, only track pressure when the number of
2232 // schedulable instructions exceeds half the integer register file.
2233 unsigned NIntRegs = Context->RegClassInfo->getNumAllocatableRegs(
2234 TM.getTargetLowering()->getRegClassFor(MVT::i32));
2235
2236 RegionPolicy.ShouldTrackPressure = NumRegionInstrs > (NIntRegs / 2);
2237
2238 // For generic targets, we default to bottom-up, because it's simpler and more
2239 // compile-time optimizations have been implemented in that direction.
2240 RegionPolicy.OnlyBottomUp = true;
2241
2242 // Allow the subtarget to override default policy.
2243 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
2244 ST.overrideSchedPolicy(RegionPolicy, Begin, End, NumRegionInstrs);
2245
2246 // After subtarget overrides, apply command line options.
2247 if (!EnableRegPressure)
2248 RegionPolicy.ShouldTrackPressure = false;
2249
2250 // Check -misched-topdown/bottomup can force or unforce scheduling direction.
2251 // e.g. -misched-bottomup=false allows scheduling in both directions.
2252 assert((!ForceTopDown || !ForceBottomUp) &&
2253 "-misched-topdown incompatible with -misched-bottomup");
2254 if (ForceBottomUp.getNumOccurrences() > 0) {
2255 RegionPolicy.OnlyBottomUp = ForceBottomUp;
2256 if (RegionPolicy.OnlyBottomUp)
2257 RegionPolicy.OnlyTopDown = false;
2258 }
2259 if (ForceTopDown.getNumOccurrences() > 0) {
2260 RegionPolicy.OnlyTopDown = ForceTopDown;
2261 if (RegionPolicy.OnlyTopDown)
2262 RegionPolicy.OnlyBottomUp = false;
2263 }
2264}
2265
2266/// Set IsAcyclicLatencyLimited if the acyclic path is longer than the cyclic
2267/// critical path by more cycles than it takes to drain the instruction buffer.
2268/// We estimate an upper bounds on in-flight instructions as:
2269///
2270/// CyclesPerIteration = max( CyclicPath, Loop-Resource-Height )
2271/// InFlightIterations = AcyclicPath / CyclesPerIteration
2272/// InFlightResources = InFlightIterations * LoopResources
2273///
2274/// TODO: Check execution resources in addition to IssueCount.
2275void GenericScheduler::checkAcyclicLatency() {
2276 if (Rem.CyclicCritPath == 0 || Rem.CyclicCritPath >= Rem.CriticalPath)
2277 return;
2278
2279 // Scaled number of cycles per loop iteration.
2280 unsigned IterCount =
2281 std::max(Rem.CyclicCritPath * SchedModel->getLatencyFactor(),
2282 Rem.RemIssueCount);
2283 // Scaled acyclic critical path.
2284 unsigned AcyclicCount = Rem.CriticalPath * SchedModel->getLatencyFactor();
2285 // InFlightCount = (AcyclicPath / IterCycles) * InstrPerLoop
2286 unsigned InFlightCount =
2287 (AcyclicCount * Rem.RemIssueCount + IterCount-1) / IterCount;
2288 unsigned BufferLimit =
2289 SchedModel->getMicroOpBufferSize() * SchedModel->getMicroOpFactor();
2290
2291 Rem.IsAcyclicLatencyLimited = InFlightCount > BufferLimit;
2292
2293 DEBUG(dbgs() << "IssueCycles="
2294 << Rem.RemIssueCount / SchedModel->getLatencyFactor() << "c "
2295 << "IterCycles=" << IterCount / SchedModel->getLatencyFactor()
2296 << "c NumIters=" << (AcyclicCount + IterCount-1) / IterCount
2297 << " InFlight=" << InFlightCount / SchedModel->getMicroOpFactor()
2298 << "m BufferLim=" << SchedModel->getMicroOpBufferSize() << "m\n";
2299 if (Rem.IsAcyclicLatencyLimited)
2300 dbgs() << " ACYCLIC LATENCY LIMIT\n");
2301}
2302
2303void GenericScheduler::registerRoots() {
2304 Rem.CriticalPath = DAG->ExitSU.getDepth();
2305
2306 // Some roots may not feed into ExitSU. Check all of them in case.
2307 for (std::vector<SUnit*>::const_iterator
2308 I = Bot.Available.begin(), E = Bot.Available.end(); I != E; ++I) {
2309 if ((*I)->getDepth() > Rem.CriticalPath)
2310 Rem.CriticalPath = (*I)->getDepth();
2311 }
2312 DEBUG(dbgs() << "Critical Path: " << Rem.CriticalPath << '\n');
2313
2314 if (EnableCyclicPath) {
2315 Rem.CyclicCritPath = DAG->computeCyclicCriticalPath();
2316 checkAcyclicLatency();
2317 }
2318}
2319
2320/// Set the CandPolicy given a scheduling zone given the current resources and
2321/// latencies inside and outside the zone.
2322void GenericScheduler::setPolicy(CandPolicy &Policy, SchedBoundary &CurrZone,
2323 SchedBoundary &OtherZone) {
2324 // Apply preemptive heuristics based on the the total latency and resources
2325 // inside and outside this zone. Potential stalls should be considered before
2326 // following this policy.
2327
2328 // Compute remaining latency. We need this both to determine whether the
2329 // overall schedule has become latency-limited and whether the instructions
2330 // outside this zone are resource or latency limited.
2331 //
2332 // The "dependent" latency is updated incrementally during scheduling as the
2333 // max height/depth of scheduled nodes minus the cycles since it was
2334 // scheduled:
2335 // DLat = max (N.depth - (CurrCycle - N.ReadyCycle) for N in Zone
2336 //
2337 // The "independent" latency is the max ready queue depth:
2338 // ILat = max N.depth for N in Available|Pending
2339 //
2340 // RemainingLatency is the greater of independent and dependent latency.
2341 unsigned RemLatency = CurrZone.getDependentLatency();
2342 RemLatency = std::max(RemLatency,
2343 CurrZone.findMaxLatency(CurrZone.Available.elements()));
2344 RemLatency = std::max(RemLatency,
2345 CurrZone.findMaxLatency(CurrZone.Pending.elements()));
2346
2347 // Compute the critical resource outside the zone.
2348 unsigned OtherCritIdx;
2349 unsigned OtherCount = OtherZone.getOtherResourceCount(OtherCritIdx);
2350
2351 bool OtherResLimited = false;
2352 if (SchedModel->hasInstrSchedModel()) {
2353 unsigned LFactor = SchedModel->getLatencyFactor();
2354 OtherResLimited = (int)(OtherCount - (RemLatency * LFactor)) > (int)LFactor;
2355 }
2356 if (!OtherResLimited
2357 && (RemLatency + CurrZone.getCurrCycle() > Rem.CriticalPath)) {
2358 Policy.ReduceLatency |= true;
2359 DEBUG(dbgs() << " " << CurrZone.Available.getName() << " RemainingLatency "
2360 << RemLatency << " + " << CurrZone.getCurrCycle() << "c > CritPath "
2361 << Rem.CriticalPath << "\n");
2362 }
2363 // If the same resource is limiting inside and outside the zone, do nothing.
2364 if (CurrZone.getZoneCritResIdx() == OtherCritIdx)
2365 return;
2366
2367 DEBUG(
2368 if (CurrZone.isResourceLimited()) {
2369 dbgs() << " " << CurrZone.Available.getName() << " ResourceLimited: "
2370 << SchedModel->getResourceName(CurrZone.getZoneCritResIdx())
2371 << "\n";
2372 }
2373 if (OtherResLimited)
2374 dbgs() << " RemainingLimit: "
2375 << SchedModel->getResourceName(OtherCritIdx) << "\n";
2376 if (!CurrZone.isResourceLimited() && !OtherResLimited)
2377 dbgs() << " Latency limited both directions.\n");
2378
2379 if (CurrZone.isResourceLimited() && !Policy.ReduceResIdx)
2380 Policy.ReduceResIdx = CurrZone.getZoneCritResIdx();
2381
2382 if (OtherResLimited)
2383 Policy.DemandResIdx = OtherCritIdx;
2384}
2385
Andrew Trick665d3ec2013-09-19 23:10:59 +00002386void GenericScheduler::SchedCandidate::
Andrew Trickd7f890e2013-12-28 21:56:47 +00002387initResourceDelta(const ScheduleDAGMILive *DAG,
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002388 const TargetSchedModel *SchedModel) {
2389 if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
2390 return;
2391
2392 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
2393 for (TargetSchedModel::ProcResIter
2394 PI = SchedModel->getWriteProcResBegin(SC),
2395 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2396 if (PI->ProcResourceIdx == Policy.ReduceResIdx)
2397 ResDelta.CritResources += PI->Cycles;
2398 if (PI->ProcResourceIdx == Policy.DemandResIdx)
2399 ResDelta.DemandedResources += PI->Cycles;
2400 }
2401}
2402
2403/// Return true if this heuristic determines order.
Andrew Trick80e66ce2013-04-05 00:31:34 +00002404static bool tryLess(int TryVal, int CandVal,
Andrew Trick665d3ec2013-09-19 23:10:59 +00002405 GenericScheduler::SchedCandidate &TryCand,
2406 GenericScheduler::SchedCandidate &Cand,
2407 GenericScheduler::CandReason Reason) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002408 if (TryVal < CandVal) {
2409 TryCand.Reason = Reason;
2410 return true;
2411 }
2412 if (TryVal > CandVal) {
2413 if (Cand.Reason > Reason)
2414 Cand.Reason = Reason;
2415 return true;
2416 }
Andrew Trickd40d0f22013-06-17 21:45:05 +00002417 Cand.setRepeat(Reason);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002418 return false;
2419}
Andrew Tricka7714a02012-11-12 19:40:10 +00002420
Andrew Trick80e66ce2013-04-05 00:31:34 +00002421static bool tryGreater(int TryVal, int CandVal,
Andrew Trick665d3ec2013-09-19 23:10:59 +00002422 GenericScheduler::SchedCandidate &TryCand,
2423 GenericScheduler::SchedCandidate &Cand,
2424 GenericScheduler::CandReason Reason) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002425 if (TryVal > CandVal) {
2426 TryCand.Reason = Reason;
2427 return true;
2428 }
2429 if (TryVal < CandVal) {
2430 if (Cand.Reason > Reason)
2431 Cand.Reason = Reason;
2432 return true;
2433 }
Andrew Trickd40d0f22013-06-17 21:45:05 +00002434 Cand.setRepeat(Reason);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002435 return false;
2436}
2437
Andrew Trick1a831342013-08-30 03:49:48 +00002438static bool tryPressure(const PressureChange &TryP,
2439 const PressureChange &CandP,
Andrew Trick665d3ec2013-09-19 23:10:59 +00002440 GenericScheduler::SchedCandidate &TryCand,
2441 GenericScheduler::SchedCandidate &Cand,
2442 GenericScheduler::CandReason Reason) {
Andrew Trickb1a45b62013-08-30 04:27:29 +00002443 int TryRank = TryP.getPSetOrMax();
2444 int CandRank = CandP.getPSetOrMax();
2445 // If both candidates affect the same set, go with the smallest increase.
2446 if (TryRank == CandRank) {
2447 return tryLess(TryP.getUnitInc(), CandP.getUnitInc(), TryCand, Cand,
2448 Reason);
Andrew Trick401b6952013-07-25 07:26:35 +00002449 }
Andrew Trickb1a45b62013-08-30 04:27:29 +00002450 // If one candidate decreases and the other increases, go with it.
2451 // Invalid candidates have UnitInc==0.
2452 if (tryLess(TryP.getUnitInc() < 0, CandP.getUnitInc() < 0, TryCand, Cand,
2453 Reason)) {
2454 return true;
2455 }
Andrew Trick401b6952013-07-25 07:26:35 +00002456 // If the candidates are decreasing pressure, reverse priority.
Andrew Trick1a831342013-08-30 03:49:48 +00002457 if (TryP.getUnitInc() < 0)
Andrew Trick401b6952013-07-25 07:26:35 +00002458 std::swap(TryRank, CandRank);
2459 return tryGreater(TryRank, CandRank, TryCand, Cand, Reason);
2460}
2461
Andrew Tricka7714a02012-11-12 19:40:10 +00002462static unsigned getWeakLeft(const SUnit *SU, bool isTop) {
2463 return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
2464}
2465
Andrew Tricke833e1c2013-04-13 06:07:40 +00002466/// Minimize physical register live ranges. Regalloc wants them adjacent to
2467/// their physreg def/use.
2468///
2469/// FIXME: This is an unnecessary check on the critical path. Most are root/leaf
2470/// copies which can be prescheduled. The rest (e.g. x86 MUL) could be bundled
2471/// with the operation that produces or consumes the physreg. We'll do this when
2472/// regalloc has support for parallel copies.
2473static int biasPhysRegCopy(const SUnit *SU, bool isTop) {
2474 const MachineInstr *MI = SU->getInstr();
2475 if (!MI->isCopy())
2476 return 0;
2477
2478 unsigned ScheduledOper = isTop ? 1 : 0;
2479 unsigned UnscheduledOper = isTop ? 0 : 1;
2480 // If we have already scheduled the physreg produce/consumer, immediately
2481 // schedule the copy.
2482 if (TargetRegisterInfo::isPhysicalRegister(
2483 MI->getOperand(ScheduledOper).getReg()))
2484 return 1;
2485 // If the physreg is at the boundary, defer it. Otherwise schedule it
2486 // immediately to free the dependent. We can hoist the copy later.
2487 bool AtBoundary = isTop ? !SU->NumSuccsLeft : !SU->NumPredsLeft;
2488 if (TargetRegisterInfo::isPhysicalRegister(
2489 MI->getOperand(UnscheduledOper).getReg()))
2490 return AtBoundary ? -1 : 1;
2491 return 0;
2492}
2493
Andrew Trick665d3ec2013-09-19 23:10:59 +00002494static bool tryLatency(GenericScheduler::SchedCandidate &TryCand,
2495 GenericScheduler::SchedCandidate &Cand,
Andrew Trickfc127d12013-12-07 05:59:44 +00002496 SchedBoundary &Zone) {
Andrew Trickc01b0042013-08-23 17:48:43 +00002497 if (Zone.isTop()) {
2498 if (Cand.SU->getDepth() > Zone.getScheduledLatency()) {
2499 if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
Andrew Trick665d3ec2013-09-19 23:10:59 +00002500 TryCand, Cand, GenericScheduler::TopDepthReduce))
Andrew Trickc01b0042013-08-23 17:48:43 +00002501 return true;
2502 }
2503 if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
Andrew Trick665d3ec2013-09-19 23:10:59 +00002504 TryCand, Cand, GenericScheduler::TopPathReduce))
Andrew Trickc01b0042013-08-23 17:48:43 +00002505 return true;
2506 }
2507 else {
2508 if (Cand.SU->getHeight() > Zone.getScheduledLatency()) {
2509 if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
Andrew Trick665d3ec2013-09-19 23:10:59 +00002510 TryCand, Cand, GenericScheduler::BotHeightReduce))
Andrew Trickc01b0042013-08-23 17:48:43 +00002511 return true;
2512 }
2513 if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
Andrew Trick665d3ec2013-09-19 23:10:59 +00002514 TryCand, Cand, GenericScheduler::BotPathReduce))
Andrew Trickc01b0042013-08-23 17:48:43 +00002515 return true;
2516 }
2517 return false;
2518}
2519
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002520/// Apply a set of heursitics to a new candidate. Heuristics are currently
2521/// hierarchical. This may be more efficient than a graduated cost model because
2522/// we don't need to evaluate all aspects of the model for each node in the
2523/// queue. But it's really done to make the heuristics easier to debug and
2524/// statistically analyze.
2525///
2526/// \param Cand provides the policy and current best candidate.
2527/// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
2528/// \param Zone describes the scheduled zone that we are extending.
2529/// \param RPTracker describes reg pressure within the scheduled zone.
2530/// \param TempTracker is a scratch pressure tracker to reuse in queries.
Andrew Trick665d3ec2013-09-19 23:10:59 +00002531void GenericScheduler::tryCandidate(SchedCandidate &Cand,
Andrew Trickbb1247b2013-12-05 17:55:47 +00002532 SchedCandidate &TryCand,
2533 SchedBoundary &Zone,
2534 const RegPressureTracker &RPTracker,
2535 RegPressureTracker &TempTracker) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002536
Andrew Trick66c3dfb2013-09-04 21:00:11 +00002537 if (DAG->isTrackingPressure()) {
Andrew Trick310190e2013-09-04 21:00:02 +00002538 // Always initialize TryCand's RPDelta.
2539 if (Zone.isTop()) {
2540 TempTracker.getMaxDownwardPressureDelta(
Andrew Trick1a831342013-08-30 03:49:48 +00002541 TryCand.SU->getInstr(),
Andrew Trick1a831342013-08-30 03:49:48 +00002542 TryCand.RPDelta,
2543 DAG->getRegionCriticalPSets(),
2544 DAG->getRegPressure().MaxSetPressure);
2545 }
2546 else {
Andrew Trick310190e2013-09-04 21:00:02 +00002547 if (VerifyScheduling) {
2548 TempTracker.getMaxUpwardPressureDelta(
2549 TryCand.SU->getInstr(),
2550 &DAG->getPressureDiff(TryCand.SU),
2551 TryCand.RPDelta,
2552 DAG->getRegionCriticalPSets(),
2553 DAG->getRegPressure().MaxSetPressure);
2554 }
2555 else {
2556 RPTracker.getUpwardPressureDelta(
2557 TryCand.SU->getInstr(),
2558 DAG->getPressureDiff(TryCand.SU),
2559 TryCand.RPDelta,
2560 DAG->getRegionCriticalPSets(),
2561 DAG->getRegPressure().MaxSetPressure);
2562 }
Andrew Trick1a831342013-08-30 03:49:48 +00002563 }
2564 }
Andrew Trickc573cd92013-09-06 17:32:44 +00002565 DEBUG(if (TryCand.RPDelta.Excess.isValid())
2566 dbgs() << " SU(" << TryCand.SU->NodeNum << ") "
2567 << TRI->getRegPressureSetName(TryCand.RPDelta.Excess.getPSet())
2568 << ":" << TryCand.RPDelta.Excess.getUnitInc() << "\n");
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002569
2570 // Initialize the candidate if needed.
2571 if (!Cand.isValid()) {
2572 TryCand.Reason = NodeOrder;
2573 return;
2574 }
Andrew Tricke833e1c2013-04-13 06:07:40 +00002575
2576 if (tryGreater(biasPhysRegCopy(TryCand.SU, Zone.isTop()),
2577 biasPhysRegCopy(Cand.SU, Zone.isTop()),
2578 TryCand, Cand, PhysRegCopy))
2579 return;
2580
Andrew Trick401b6952013-07-25 07:26:35 +00002581 // Avoid exceeding the target's limit. If signed PSetID is negative, it is
2582 // invalid; convert it to INT_MAX to give it lowest priority.
Andrew Trick66c3dfb2013-09-04 21:00:11 +00002583 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.Excess,
2584 Cand.RPDelta.Excess,
2585 TryCand, Cand, RegExcess))
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002586 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002587
2588 // Avoid increasing the max critical pressure in the scheduled region.
Andrew Trick66c3dfb2013-09-04 21:00:11 +00002589 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CriticalMax,
2590 Cand.RPDelta.CriticalMax,
2591 TryCand, Cand, RegCritical))
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002592 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002593
Andrew Trickddffae92013-09-06 17:32:36 +00002594 // For loops that are acyclic path limited, aggressively schedule for latency.
Andrew Tricke1f7bf22013-09-09 22:28:08 +00002595 // This can result in very long dependence chains scheduled in sequence, so
2596 // once every cycle (when CurrMOps == 0), switch to normal heuristics.
Andrew Trickfc127d12013-12-07 05:59:44 +00002597 if (Rem.IsAcyclicLatencyLimited && !Zone.getCurrMOps()
Andrew Tricke1f7bf22013-09-09 22:28:08 +00002598 && tryLatency(TryCand, Cand, Zone))
Andrew Trickddffae92013-09-06 17:32:36 +00002599 return;
2600
Andrew Trick880e5732013-12-05 17:55:58 +00002601 // Prioritize instructions that read unbuffered resources by stall cycles.
2602 if (tryLess(Zone.getLatencyStallCycles(TryCand.SU),
2603 Zone.getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
2604 return;
2605
Andrew Tricka7714a02012-11-12 19:40:10 +00002606 // Keep clustered nodes together to encourage downstream peephole
2607 // optimizations which may reduce resource requirements.
2608 //
2609 // This is a best effort to set things up for a post-RA pass. Optimizations
2610 // like generating loads of multiple registers should ideally be done within
2611 // the scheduler pass by combining the loads during DAG postprocessing.
2612 const SUnit *NextClusterSU =
2613 Zone.isTop() ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
2614 if (tryGreater(TryCand.SU == NextClusterSU, Cand.SU == NextClusterSU,
2615 TryCand, Cand, Cluster))
2616 return;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00002617
2618 // Weak edges are for clustering and other constraints.
Andrew Tricka7714a02012-11-12 19:40:10 +00002619 if (tryLess(getWeakLeft(TryCand.SU, Zone.isTop()),
2620 getWeakLeft(Cand.SU, Zone.isTop()),
Andrew Trick85a1d4c2013-04-24 15:54:43 +00002621 TryCand, Cand, Weak)) {
Andrew Tricka7714a02012-11-12 19:40:10 +00002622 return;
2623 }
Andrew Trick71f08a32013-06-17 21:45:13 +00002624 // Avoid increasing the max pressure of the entire region.
Andrew Trick66c3dfb2013-09-04 21:00:11 +00002625 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CurrentMax,
2626 Cand.RPDelta.CurrentMax,
2627 TryCand, Cand, RegMax))
Andrew Trick71f08a32013-06-17 21:45:13 +00002628 return;
2629
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002630 // Avoid critical resource consumption and balance the schedule.
2631 TryCand.initResourceDelta(DAG, SchedModel);
2632 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
2633 TryCand, Cand, ResourceReduce))
2634 return;
2635 if (tryGreater(TryCand.ResDelta.DemandedResources,
2636 Cand.ResDelta.DemandedResources,
2637 TryCand, Cand, ResourceDemand))
2638 return;
2639
2640 // Avoid serializing long latency dependence chains.
Andrew Trickc01b0042013-08-23 17:48:43 +00002641 // For acyclic path limited loops, latency was already checked above.
2642 if (Cand.Policy.ReduceLatency && !Rem.IsAcyclicLatencyLimited
2643 && tryLatency(TryCand, Cand, Zone)) {
2644 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002645 }
2646
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002647 // Prefer immediate defs/users of the last scheduled instruction. This is a
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002648 // local pressure avoidance strategy that also makes the machine code
2649 // readable.
Andrew Trickfc127d12013-12-07 05:59:44 +00002650 if (tryGreater(Zone.isNextSU(TryCand.SU), Zone.isNextSU(Cand.SU),
Andrew Tricka7714a02012-11-12 19:40:10 +00002651 TryCand, Cand, NextDefUse))
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002652 return;
Andrew Tricka7714a02012-11-12 19:40:10 +00002653
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002654 // Fall through to original instruction order.
2655 if ((Zone.isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
2656 || (!Zone.isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
2657 TryCand.Reason = NodeOrder;
2658 }
2659}
Andrew Trick419eae22012-05-10 21:06:19 +00002660
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002661#ifndef NDEBUG
Andrew Trick665d3ec2013-09-19 23:10:59 +00002662const char *GenericScheduler::getReasonStr(
2663 GenericScheduler::CandReason Reason) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002664 switch (Reason) {
2665 case NoCand: return "NOCAND ";
Andrew Tricke833e1c2013-04-13 06:07:40 +00002666 case PhysRegCopy: return "PREG-COPY";
Andrew Trickd40d0f22013-06-17 21:45:05 +00002667 case RegExcess: return "REG-EXCESS";
2668 case RegCritical: return "REG-CRIT ";
Andrew Trick880e5732013-12-05 17:55:58 +00002669 case Stall: return "STALL ";
Andrew Tricka7714a02012-11-12 19:40:10 +00002670 case Cluster: return "CLUSTER ";
Andrew Trick85a1d4c2013-04-24 15:54:43 +00002671 case Weak: return "WEAK ";
Andrew Trick71f08a32013-06-17 21:45:13 +00002672 case RegMax: return "REG-MAX ";
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002673 case ResourceReduce: return "RES-REDUCE";
2674 case ResourceDemand: return "RES-DEMAND";
2675 case TopDepthReduce: return "TOP-DEPTH ";
2676 case TopPathReduce: return "TOP-PATH ";
2677 case BotHeightReduce:return "BOT-HEIGHT";
2678 case BotPathReduce: return "BOT-PATH ";
2679 case NextDefUse: return "DEF-USE ";
2680 case NodeOrder: return "ORDER ";
2681 };
Benjamin Kramerc280f412012-11-09 15:45:22 +00002682 llvm_unreachable("Unknown reason!");
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002683}
2684
Andrew Trick665d3ec2013-09-19 23:10:59 +00002685void GenericScheduler::traceCandidate(const SchedCandidate &Cand) {
Andrew Trick1a831342013-08-30 03:49:48 +00002686 PressureChange P;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002687 unsigned ResIdx = 0;
2688 unsigned Latency = 0;
2689 switch (Cand.Reason) {
2690 default:
2691 break;
Andrew Trickd40d0f22013-06-17 21:45:05 +00002692 case RegExcess:
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002693 P = Cand.RPDelta.Excess;
2694 break;
Andrew Trickd40d0f22013-06-17 21:45:05 +00002695 case RegCritical:
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002696 P = Cand.RPDelta.CriticalMax;
2697 break;
Andrew Trick71f08a32013-06-17 21:45:13 +00002698 case RegMax:
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002699 P = Cand.RPDelta.CurrentMax;
2700 break;
2701 case ResourceReduce:
2702 ResIdx = Cand.Policy.ReduceResIdx;
2703 break;
2704 case ResourceDemand:
2705 ResIdx = Cand.Policy.DemandResIdx;
2706 break;
2707 case TopDepthReduce:
2708 Latency = Cand.SU->getDepth();
2709 break;
2710 case TopPathReduce:
2711 Latency = Cand.SU->getHeight();
2712 break;
2713 case BotHeightReduce:
2714 Latency = Cand.SU->getHeight();
2715 break;
2716 case BotPathReduce:
2717 Latency = Cand.SU->getDepth();
2718 break;
2719 }
Andrew Trick419d4912013-04-05 00:31:29 +00002720 dbgs() << " SU(" << Cand.SU->NodeNum << ") " << getReasonStr(Cand.Reason);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002721 if (P.isValid())
Andrew Trick1a831342013-08-30 03:49:48 +00002722 dbgs() << " " << TRI->getRegPressureSetName(P.getPSet())
2723 << ":" << P.getUnitInc() << " ";
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002724 else
Andrew Trick419d4912013-04-05 00:31:29 +00002725 dbgs() << " ";
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002726 if (ResIdx)
Andrew Trick419d4912013-04-05 00:31:29 +00002727 dbgs() << " " << SchedModel->getProcResource(ResIdx)->Name << " ";
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002728 else
2729 dbgs() << " ";
Andrew Trick419d4912013-04-05 00:31:29 +00002730 if (Latency)
2731 dbgs() << " " << Latency << " cycles ";
2732 else
2733 dbgs() << " ";
2734 dbgs() << '\n';
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002735}
2736#endif
2737
Andrew Trickc573cd92013-09-06 17:32:44 +00002738/// Pick the best candidate from the queue.
Andrew Trick7ee9de52012-05-10 21:06:16 +00002739///
2740/// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
2741/// DAG building. To adjust for the current scheduling location we need to
2742/// maintain the number of vreg uses remaining to be top-scheduled.
Andrew Trick665d3ec2013-09-19 23:10:59 +00002743void GenericScheduler::pickNodeFromQueue(SchedBoundary &Zone,
Andrew Trickbb1247b2013-12-05 17:55:47 +00002744 const RegPressureTracker &RPTracker,
2745 SchedCandidate &Cand) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002746 ReadyQueue &Q = Zone.Available;
2747
Andrew Tricka8ad5f72012-05-24 22:11:12 +00002748 DEBUG(Q.dump());
Andrew Trick22025772012-05-17 18:35:10 +00002749
Andrew Trick7ee9de52012-05-10 21:06:16 +00002750 // getMaxPressureDelta temporarily modifies the tracker.
2751 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
2752
Andrew Trickdd375dd2012-05-24 22:11:03 +00002753 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
Andrew Trick7ee9de52012-05-10 21:06:16 +00002754
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002755 SchedCandidate TryCand(Cand.Policy);
2756 TryCand.SU = *I;
2757 tryCandidate(Cand, TryCand, Zone, RPTracker, TempTracker);
2758 if (TryCand.Reason != NoCand) {
2759 // Initialize resource delta if needed in case future heuristics query it.
2760 if (TryCand.ResDelta == SchedResourceDelta())
2761 TryCand.initResourceDelta(DAG, SchedModel);
2762 Cand.setBest(TryCand);
Andrew Trick419d4912013-04-05 00:31:29 +00002763 DEBUG(traceCandidate(Cand));
Andrew Trick22025772012-05-17 18:35:10 +00002764 }
Andrew Trick7ee9de52012-05-10 21:06:16 +00002765 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002766}
2767
Andrew Trick665d3ec2013-09-19 23:10:59 +00002768static void tracePick(const GenericScheduler::SchedCandidate &Cand,
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002769 bool IsTop) {
Andrew Trick1f0bb692013-04-13 06:07:49 +00002770 DEBUG(dbgs() << "Pick " << (IsTop ? "Top " : "Bot ")
Andrew Trick665d3ec2013-09-19 23:10:59 +00002771 << GenericScheduler::getReasonStr(Cand.Reason) << '\n');
Andrew Trick7ee9de52012-05-10 21:06:16 +00002772}
2773
Andrew Trick22025772012-05-17 18:35:10 +00002774/// Pick the best candidate node from either the top or bottom queue.
Andrew Trick665d3ec2013-09-19 23:10:59 +00002775SUnit *GenericScheduler::pickNodeBidirectional(bool &IsTopNode) {
Andrew Trick22025772012-05-17 18:35:10 +00002776 // Schedule as far as possible in the direction of no choice. This is most
2777 // efficient, but also provides the best heuristics for CriticalPSets.
Andrew Trick61f1a272012-05-24 22:11:09 +00002778 if (SUnit *SU = Bot.pickOnlyChoice()) {
Andrew Trick22025772012-05-17 18:35:10 +00002779 IsTopNode = false;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002780 DEBUG(dbgs() << "Pick Bot NOCAND\n");
Andrew Trick61f1a272012-05-24 22:11:09 +00002781 return SU;
Andrew Trick22025772012-05-17 18:35:10 +00002782 }
Andrew Trick61f1a272012-05-24 22:11:09 +00002783 if (SUnit *SU = Top.pickOnlyChoice()) {
Andrew Trick22025772012-05-17 18:35:10 +00002784 IsTopNode = true;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002785 DEBUG(dbgs() << "Pick Top NOCAND\n");
Andrew Trick61f1a272012-05-24 22:11:09 +00002786 return SU;
Andrew Trick22025772012-05-17 18:35:10 +00002787 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002788 CandPolicy NoPolicy;
2789 SchedCandidate BotCand(NoPolicy);
2790 SchedCandidate TopCand(NoPolicy);
Andrew Trickfc127d12013-12-07 05:59:44 +00002791 // Set the bottom-up policy based on the state of the current bottom zone and
2792 // the instructions outside the zone, including the top zone.
2793 setPolicy(BotCand.Policy, Bot, Top);
2794 // Set the top-down policy based on the state of the current top zone and
2795 // the instructions outside the zone, including the bottom zone.
2796 setPolicy(TopCand.Policy, Top, Bot);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002797
Andrew Trick22025772012-05-17 18:35:10 +00002798 // Prefer bottom scheduling when heuristics are silent.
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002799 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
2800 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick22025772012-05-17 18:35:10 +00002801
2802 // If either Q has a single candidate that provides the least increase in
2803 // Excess pressure, we can immediately schedule from that Q.
2804 //
2805 // RegionCriticalPSets summarizes the pressure within the scheduled region and
2806 // affects picking from either Q. If scheduling in one direction must
2807 // increase pressure for one of the excess PSets, then schedule in that
2808 // direction first to provide more freedom in the other direction.
Andrew Trickd40d0f22013-06-17 21:45:05 +00002809 if ((BotCand.Reason == RegExcess && !BotCand.isRepeat(RegExcess))
2810 || (BotCand.Reason == RegCritical
2811 && !BotCand.isRepeat(RegCritical)))
2812 {
Andrew Trick22025772012-05-17 18:35:10 +00002813 IsTopNode = false;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002814 tracePick(BotCand, IsTopNode);
Andrew Trick61f1a272012-05-24 22:11:09 +00002815 return BotCand.SU;
Andrew Trick22025772012-05-17 18:35:10 +00002816 }
2817 // Check if the top Q has a better candidate.
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002818 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
2819 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick22025772012-05-17 18:35:10 +00002820
Andrew Trickd40d0f22013-06-17 21:45:05 +00002821 // Choose the queue with the most important (lowest enum) reason.
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002822 if (TopCand.Reason < BotCand.Reason) {
2823 IsTopNode = true;
2824 tracePick(TopCand, IsTopNode);
2825 return TopCand.SU;
2826 }
Andrew Trickd40d0f22013-06-17 21:45:05 +00002827 // Otherwise prefer the bottom candidate, in node order if all else failed.
Andrew Trick22025772012-05-17 18:35:10 +00002828 IsTopNode = false;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002829 tracePick(BotCand, IsTopNode);
Andrew Trick61f1a272012-05-24 22:11:09 +00002830 return BotCand.SU;
Andrew Trick22025772012-05-17 18:35:10 +00002831}
2832
2833/// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
Andrew Trick665d3ec2013-09-19 23:10:59 +00002834SUnit *GenericScheduler::pickNode(bool &IsTopNode) {
Andrew Trick7ee9de52012-05-10 21:06:16 +00002835 if (DAG->top() == DAG->bottom()) {
Andrew Trick61f1a272012-05-24 22:11:09 +00002836 assert(Top.Available.empty() && Top.Pending.empty() &&
2837 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
Andrew Trick7ee9de52012-05-10 21:06:16 +00002838 return NULL;
2839 }
Andrew Trick7ee9de52012-05-10 21:06:16 +00002840 SUnit *SU;
Andrew Trick984d98b2012-10-08 18:53:53 +00002841 do {
Andrew Trick75e411c2013-09-06 17:32:34 +00002842 if (RegionPolicy.OnlyTopDown) {
Andrew Trick984d98b2012-10-08 18:53:53 +00002843 SU = Top.pickOnlyChoice();
2844 if (!SU) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002845 CandPolicy NoPolicy;
2846 SchedCandidate TopCand(NoPolicy);
2847 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
Andrew Trick1ab16d92013-09-04 21:00:13 +00002848 assert(TopCand.Reason != NoCand && "failed to find a candidate");
Andrew Trickef54c592013-09-04 21:00:16 +00002849 tracePick(TopCand, true);
Andrew Trick984d98b2012-10-08 18:53:53 +00002850 SU = TopCand.SU;
2851 }
2852 IsTopNode = true;
Andrew Tricka306a8a2012-05-24 23:11:17 +00002853 }
Andrew Trick75e411c2013-09-06 17:32:34 +00002854 else if (RegionPolicy.OnlyBottomUp) {
Andrew Trick984d98b2012-10-08 18:53:53 +00002855 SU = Bot.pickOnlyChoice();
2856 if (!SU) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002857 CandPolicy NoPolicy;
2858 SchedCandidate BotCand(NoPolicy);
2859 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
Andrew Trick1ab16d92013-09-04 21:00:13 +00002860 assert(BotCand.Reason != NoCand && "failed to find a candidate");
Andrew Trickef54c592013-09-04 21:00:16 +00002861 tracePick(BotCand, false);
Andrew Trick984d98b2012-10-08 18:53:53 +00002862 SU = BotCand.SU;
2863 }
2864 IsTopNode = false;
Andrew Tricka306a8a2012-05-24 23:11:17 +00002865 }
Andrew Trick984d98b2012-10-08 18:53:53 +00002866 else {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002867 SU = pickNodeBidirectional(IsTopNode);
Andrew Trick984d98b2012-10-08 18:53:53 +00002868 }
2869 } while (SU->isScheduled);
2870
Andrew Trick61f1a272012-05-24 22:11:09 +00002871 if (SU->isTopReady())
2872 Top.removeReady(SU);
2873 if (SU->isBottomReady())
2874 Bot.removeReady(SU);
Andrew Trick4e7f6a72012-05-25 02:02:39 +00002875
Andrew Trick1f0bb692013-04-13 06:07:49 +00002876 DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " << *SU->getInstr());
Andrew Trick7ee9de52012-05-10 21:06:16 +00002877 return SU;
2878}
2879
Andrew Trick665d3ec2013-09-19 23:10:59 +00002880void GenericScheduler::reschedulePhysRegCopies(SUnit *SU, bool isTop) {
Andrew Tricke833e1c2013-04-13 06:07:40 +00002881
2882 MachineBasicBlock::iterator InsertPos = SU->getInstr();
2883 if (!isTop)
2884 ++InsertPos;
2885 SmallVectorImpl<SDep> &Deps = isTop ? SU->Preds : SU->Succs;
2886
2887 // Find already scheduled copies with a single physreg dependence and move
2888 // them just above the scheduled instruction.
2889 for (SmallVectorImpl<SDep>::iterator I = Deps.begin(), E = Deps.end();
2890 I != E; ++I) {
2891 if (I->getKind() != SDep::Data || !TRI->isPhysicalRegister(I->getReg()))
2892 continue;
2893 SUnit *DepSU = I->getSUnit();
2894 if (isTop ? DepSU->Succs.size() > 1 : DepSU->Preds.size() > 1)
2895 continue;
2896 MachineInstr *Copy = DepSU->getInstr();
2897 if (!Copy->isCopy())
2898 continue;
2899 DEBUG(dbgs() << " Rescheduling physreg copy ";
2900 I->getSUnit()->dump(DAG));
2901 DAG->moveInstruction(Copy, InsertPos);
2902 }
2903}
2904
Andrew Trick61f1a272012-05-24 22:11:09 +00002905/// Update the scheduler's state after scheduling a node. This is the same node
Andrew Trickd7f890e2013-12-28 21:56:47 +00002906/// that was just returned by pickNode(). However, ScheduleDAGMILive needs to update
Andrew Trick45446062012-06-05 21:11:27 +00002907/// it's state based on the current cycle before MachineSchedStrategy does.
Andrew Tricke833e1c2013-04-13 06:07:40 +00002908///
2909/// FIXME: Eventually, we may bundle physreg copies rather than rescheduling
2910/// them here. See comments in biasPhysRegCopy.
Andrew Trick665d3ec2013-09-19 23:10:59 +00002911void GenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
Andrew Trick45446062012-06-05 21:11:27 +00002912 if (IsTopNode) {
Andrew Trickfc127d12013-12-07 05:59:44 +00002913 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
Andrew Trickce27bb92012-06-29 03:23:22 +00002914 Top.bumpNode(SU);
Andrew Tricke833e1c2013-04-13 06:07:40 +00002915 if (SU->hasPhysRegUses)
2916 reschedulePhysRegCopies(SU, true);
Andrew Trick61f1a272012-05-24 22:11:09 +00002917 }
Andrew Trick45446062012-06-05 21:11:27 +00002918 else {
Andrew Trickfc127d12013-12-07 05:59:44 +00002919 SU->BotReadyCycle = std::max(SU->BotReadyCycle, Bot.getCurrCycle());
Andrew Trickce27bb92012-06-29 03:23:22 +00002920 Bot.bumpNode(SU);
Andrew Tricke833e1c2013-04-13 06:07:40 +00002921 if (SU->hasPhysRegDefs)
2922 reschedulePhysRegCopies(SU, false);
Andrew Trick61f1a272012-05-24 22:11:09 +00002923 }
2924}
2925
Andrew Trickd7f890e2013-12-28 21:56:47 +00002926/// Create a generic scheduler with no DAG mutation passes.
2927static ScheduleDAGInstrs *createRawGenericSched(MachineSchedContext *C) {
2928 return new ScheduleDAGMILive(C, new GenericScheduler(C));
2929}
2930
Andrew Trick8823dec2012-03-14 04:00:41 +00002931/// Create the standard converging machine scheduler. This will be used as the
2932/// default scheduler if the target does not set a default.
Andrew Trick665d3ec2013-09-19 23:10:59 +00002933static ScheduleDAGInstrs *createGenericSched(MachineSchedContext *C) {
Andrew Trickd7f890e2013-12-28 21:56:47 +00002934 ScheduleDAGMILive *DAG =
2935 static_cast<ScheduleDAGMILive*>(createRawGenericSched(C));
Andrew Tricka7714a02012-11-12 19:40:10 +00002936 // Register DAG post-processors.
Andrew Trick85a1d4c2013-04-24 15:54:43 +00002937 //
2938 // FIXME: extend the mutation API to allow earlier mutations to instantiate
2939 // data and pass it to later mutations. Have a single mutation that gathers
2940 // the interesting nodes in one pass.
Andrew Trick0cd8afc2013-06-15 04:49:46 +00002941 DAG->addMutation(new CopyConstrain(DAG->TII, DAG->TRI));
Andrew Tricka6e87772013-09-04 21:00:08 +00002942 if (EnableLoadCluster && DAG->TII->enableClusterLoads())
Andrew Tricka7714a02012-11-12 19:40:10 +00002943 DAG->addMutation(new LoadClusterMutation(DAG->TII, DAG->TRI));
Andrew Trick263280242012-11-12 19:52:20 +00002944 if (EnableMacroFusion)
2945 DAG->addMutation(new MacroFusion(DAG->TII));
Andrew Tricka7714a02012-11-12 19:40:10 +00002946 return DAG;
Andrew Tricke1c034f2012-01-17 06:55:03 +00002947}
2948static MachineSchedRegistry
Andrew Trick665d3ec2013-09-19 23:10:59 +00002949GenericSchedRegistry("converge", "Standard converging scheduler.",
2950 createGenericSched);
Andrew Tricke1c034f2012-01-17 06:55:03 +00002951
2952//===----------------------------------------------------------------------===//
Andrew Trick90f711d2012-10-15 18:02:27 +00002953// ILP Scheduler. Currently for experimental analysis of heuristics.
2954//===----------------------------------------------------------------------===//
2955
2956namespace {
2957/// \brief Order nodes by the ILP metric.
2958struct ILPOrder {
Andrew Trick44f750a2013-01-25 04:01:04 +00002959 const SchedDFSResult *DFSResult;
2960 const BitVector *ScheduledTrees;
Andrew Trick90f711d2012-10-15 18:02:27 +00002961 bool MaximizeILP;
2962
Andrew Trick44f750a2013-01-25 04:01:04 +00002963 ILPOrder(bool MaxILP): DFSResult(0), ScheduledTrees(0), MaximizeILP(MaxILP) {}
Andrew Trick90f711d2012-10-15 18:02:27 +00002964
2965 /// \brief Apply a less-than relation on node priority.
Andrew Trick48d392e2012-11-28 05:13:28 +00002966 ///
2967 /// (Return true if A comes after B in the Q.)
Andrew Trick90f711d2012-10-15 18:02:27 +00002968 bool operator()(const SUnit *A, const SUnit *B) const {
Andrew Trick48d392e2012-11-28 05:13:28 +00002969 unsigned SchedTreeA = DFSResult->getSubtreeID(A);
2970 unsigned SchedTreeB = DFSResult->getSubtreeID(B);
2971 if (SchedTreeA != SchedTreeB) {
2972 // Unscheduled trees have lower priority.
2973 if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
2974 return ScheduledTrees->test(SchedTreeB);
2975
2976 // Trees with shallower connections have have lower priority.
2977 if (DFSResult->getSubtreeLevel(SchedTreeA)
2978 != DFSResult->getSubtreeLevel(SchedTreeB)) {
2979 return DFSResult->getSubtreeLevel(SchedTreeA)
2980 < DFSResult->getSubtreeLevel(SchedTreeB);
2981 }
2982 }
Andrew Trick90f711d2012-10-15 18:02:27 +00002983 if (MaximizeILP)
Andrew Trick48d392e2012-11-28 05:13:28 +00002984 return DFSResult->getILP(A) < DFSResult->getILP(B);
Andrew Trick90f711d2012-10-15 18:02:27 +00002985 else
Andrew Trick48d392e2012-11-28 05:13:28 +00002986 return DFSResult->getILP(A) > DFSResult->getILP(B);
Andrew Trick90f711d2012-10-15 18:02:27 +00002987 }
2988};
2989
2990/// \brief Schedule based on the ILP metric.
2991class ILPScheduler : public MachineSchedStrategy {
Andrew Trickd7f890e2013-12-28 21:56:47 +00002992 ScheduleDAGMILive *DAG;
Andrew Trick90f711d2012-10-15 18:02:27 +00002993 ILPOrder Cmp;
2994
2995 std::vector<SUnit*> ReadyQ;
2996public:
Andrew Trick44f750a2013-01-25 04:01:04 +00002997 ILPScheduler(bool MaximizeILP): DAG(0), Cmp(MaximizeILP) {}
Andrew Trick90f711d2012-10-15 18:02:27 +00002998
Andrew Trick44f750a2013-01-25 04:01:04 +00002999 virtual void initialize(ScheduleDAGMI *dag) {
Andrew Trickd7f890e2013-12-28 21:56:47 +00003000 assert(dag->hasVRegLiveness() && "ILPScheduler needs vreg liveness");
3001 DAG = static_cast<ScheduleDAGMILive*>(dag);
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00003002 DAG->computeDFSResult();
Andrew Trick44f750a2013-01-25 04:01:04 +00003003 Cmp.DFSResult = DAG->getDFSResult();
3004 Cmp.ScheduledTrees = &DAG->getScheduledTrees();
Andrew Trick90f711d2012-10-15 18:02:27 +00003005 ReadyQ.clear();
Andrew Trick90f711d2012-10-15 18:02:27 +00003006 }
3007
3008 virtual void registerRoots() {
Benjamin Krameraa598b32012-11-29 14:36:26 +00003009 // Restore the heap in ReadyQ with the updated DFS results.
3010 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
Andrew Trick90f711d2012-10-15 18:02:27 +00003011 }
3012
3013 /// Implement MachineSchedStrategy interface.
3014 /// -----------------------------------------
3015
Andrew Trick48d392e2012-11-28 05:13:28 +00003016 /// Callback to select the highest priority node from the ready Q.
Andrew Trick90f711d2012-10-15 18:02:27 +00003017 virtual SUnit *pickNode(bool &IsTopNode) {
3018 if (ReadyQ.empty()) return NULL;
Matt Arsenault4ab769f2013-03-21 00:57:21 +00003019 std::pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
Andrew Trick90f711d2012-10-15 18:02:27 +00003020 SUnit *SU = ReadyQ.back();
3021 ReadyQ.pop_back();
3022 IsTopNode = false;
Andrew Trick1f0bb692013-04-13 06:07:49 +00003023 DEBUG(dbgs() << "Pick node " << "SU(" << SU->NodeNum << ") "
Andrew Trick44f750a2013-01-25 04:01:04 +00003024 << " ILP: " << DAG->getDFSResult()->getILP(SU)
3025 << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU) << " @"
3026 << DAG->getDFSResult()->getSubtreeLevel(
Andrew Trick1f0bb692013-04-13 06:07:49 +00003027 DAG->getDFSResult()->getSubtreeID(SU)) << '\n'
3028 << "Scheduling " << *SU->getInstr());
Andrew Trick90f711d2012-10-15 18:02:27 +00003029 return SU;
3030 }
3031
Andrew Trick44f750a2013-01-25 04:01:04 +00003032 /// \brief Scheduler callback to notify that a new subtree is scheduled.
3033 virtual void scheduleTree(unsigned SubtreeID) {
3034 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3035 }
3036
Andrew Trick48d392e2012-11-28 05:13:28 +00003037 /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
3038 /// DFSResults, and resort the priority Q.
3039 virtual void schedNode(SUnit *SU, bool IsTopNode) {
3040 assert(!IsTopNode && "SchedDFSResult needs bottom-up");
Andrew Trick48d392e2012-11-28 05:13:28 +00003041 }
Andrew Trick90f711d2012-10-15 18:02:27 +00003042
3043 virtual void releaseTopNode(SUnit *) { /*only called for top roots*/ }
3044
3045 virtual void releaseBottomNode(SUnit *SU) {
3046 ReadyQ.push_back(SU);
3047 std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3048 }
3049};
3050} // namespace
3051
3052static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
Andrew Trickd7f890e2013-12-28 21:56:47 +00003053 return new ScheduleDAGMILive(C, new ILPScheduler(true));
Andrew Trick90f711d2012-10-15 18:02:27 +00003054}
3055static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
Andrew Trickd7f890e2013-12-28 21:56:47 +00003056 return new ScheduleDAGMILive(C, new ILPScheduler(false));
Andrew Trick90f711d2012-10-15 18:02:27 +00003057}
3058static MachineSchedRegistry ILPMaxRegistry(
3059 "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
3060static MachineSchedRegistry ILPMinRegistry(
3061 "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
3062
3063//===----------------------------------------------------------------------===//
Andrew Trick63440872012-01-14 02:17:06 +00003064// Machine Instruction Shuffler for Correctness Testing
3065//===----------------------------------------------------------------------===//
3066
Andrew Tricke77e84e2012-01-13 06:30:30 +00003067#ifndef NDEBUG
3068namespace {
Andrew Trick8823dec2012-03-14 04:00:41 +00003069/// Apply a less-than relation on the node order, which corresponds to the
3070/// instruction order prior to scheduling. IsReverse implements greater-than.
3071template<bool IsReverse>
3072struct SUnitOrder {
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003073 bool operator()(SUnit *A, SUnit *B) const {
Andrew Trick8823dec2012-03-14 04:00:41 +00003074 if (IsReverse)
3075 return A->NodeNum > B->NodeNum;
3076 else
3077 return A->NodeNum < B->NodeNum;
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003078 }
3079};
3080
Andrew Tricke77e84e2012-01-13 06:30:30 +00003081/// Reorder instructions as much as possible.
Andrew Trick8823dec2012-03-14 04:00:41 +00003082class InstructionShuffler : public MachineSchedStrategy {
3083 bool IsAlternating;
3084 bool IsTopDown;
3085
3086 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
3087 // gives nodes with a higher number higher priority causing the latest
3088 // instructions to be scheduled first.
3089 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
3090 TopQ;
3091 // When scheduling bottom-up, use greater-than as the queue priority.
3092 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
3093 BottomQ;
Andrew Tricke77e84e2012-01-13 06:30:30 +00003094public:
Andrew Trick8823dec2012-03-14 04:00:41 +00003095 InstructionShuffler(bool alternate, bool topdown)
3096 : IsAlternating(alternate), IsTopDown(topdown) {}
Andrew Tricke77e84e2012-01-13 06:30:30 +00003097
Andrew Trickd7f890e2013-12-28 21:56:47 +00003098 virtual void initialize(ScheduleDAGMI*) {
Andrew Trick8823dec2012-03-14 04:00:41 +00003099 TopQ.clear();
3100 BottomQ.clear();
3101 }
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003102
Andrew Trick8823dec2012-03-14 04:00:41 +00003103 /// Implement MachineSchedStrategy interface.
3104 /// -----------------------------------------
3105
3106 virtual SUnit *pickNode(bool &IsTopNode) {
3107 SUnit *SU;
3108 if (IsTopDown) {
3109 do {
3110 if (TopQ.empty()) return NULL;
3111 SU = TopQ.top();
3112 TopQ.pop();
3113 } while (SU->isScheduled);
3114 IsTopNode = true;
3115 }
3116 else {
3117 do {
3118 if (BottomQ.empty()) return NULL;
3119 SU = BottomQ.top();
3120 BottomQ.pop();
3121 } while (SU->isScheduled);
3122 IsTopNode = false;
3123 }
3124 if (IsAlternating)
3125 IsTopDown = !IsTopDown;
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003126 return SU;
3127 }
3128
Andrew Trick61f1a272012-05-24 22:11:09 +00003129 virtual void schedNode(SUnit *SU, bool IsTopNode) {}
3130
Andrew Trick8823dec2012-03-14 04:00:41 +00003131 virtual void releaseTopNode(SUnit *SU) {
3132 TopQ.push(SU);
3133 }
3134 virtual void releaseBottomNode(SUnit *SU) {
3135 BottomQ.push(SU);
Andrew Tricke77e84e2012-01-13 06:30:30 +00003136 }
3137};
3138} // namespace
3139
Andrew Trick02a80da2012-03-08 01:41:12 +00003140static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
Andrew Trick8823dec2012-03-14 04:00:41 +00003141 bool Alternate = !ForceTopDown && !ForceBottomUp;
3142 bool TopDown = !ForceBottomUp;
Benjamin Kramer05e7a842012-03-14 11:26:37 +00003143 assert((TopDown || !ForceTopDown) &&
Andrew Trick8823dec2012-03-14 04:00:41 +00003144 "-misched-topdown incompatible with -misched-bottomup");
Andrew Trickd7f890e2013-12-28 21:56:47 +00003145 return new ScheduleDAGMILive(C, new InstructionShuffler(Alternate, TopDown));
Andrew Tricke77e84e2012-01-13 06:30:30 +00003146}
Andrew Trick8823dec2012-03-14 04:00:41 +00003147static MachineSchedRegistry ShufflerRegistry(
3148 "shuffle", "Shuffle machine instructions alternating directions",
3149 createInstructionShuffler);
Andrew Tricke77e84e2012-01-13 06:30:30 +00003150#endif // !NDEBUG
Andrew Trickea9fd952013-01-25 07:45:29 +00003151
3152//===----------------------------------------------------------------------===//
Andrew Trickd7f890e2013-12-28 21:56:47 +00003153// GraphWriter support for ScheduleDAGMILive.
Andrew Trickea9fd952013-01-25 07:45:29 +00003154//===----------------------------------------------------------------------===//
3155
3156#ifndef NDEBUG
3157namespace llvm {
3158
3159template<> struct GraphTraits<
3160 ScheduleDAGMI*> : public GraphTraits<ScheduleDAG*> {};
3161
3162template<>
3163struct DOTGraphTraits<ScheduleDAGMI*> : public DefaultDOTGraphTraits {
3164
3165 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
3166
3167 static std::string getGraphName(const ScheduleDAG *G) {
3168 return G->MF.getName();
3169 }
3170
3171 static bool renderGraphFromBottomUp() {
3172 return true;
3173 }
3174
3175 static bool isNodeHidden(const SUnit *Node) {
Andrew Trick856ecd92013-09-04 21:00:18 +00003176 return (Node->Preds.size() > 10 || Node->Succs.size() > 10);
Andrew Trickea9fd952013-01-25 07:45:29 +00003177 }
3178
3179 static bool hasNodeAddressLabel(const SUnit *Node,
3180 const ScheduleDAG *Graph) {
3181 return false;
3182 }
3183
3184 /// If you want to override the dot attributes printed for a particular
3185 /// edge, override this method.
3186 static std::string getEdgeAttributes(const SUnit *Node,
3187 SUnitIterator EI,
3188 const ScheduleDAG *Graph) {
3189 if (EI.isArtificialDep())
3190 return "color=cyan,style=dashed";
3191 if (EI.isCtrlDep())
3192 return "color=blue,style=dashed";
3193 return "";
3194 }
3195
3196 static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) {
3197 std::string Str;
3198 raw_string_ostream SS(Str);
Andrew Trickd7f890e2013-12-28 21:56:47 +00003199 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3200 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
3201 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : 0;
Andrew Trick7609b7d2013-09-06 17:32:42 +00003202 SS << "SU:" << SU->NodeNum;
3203 if (DFS)
3204 SS << " I:" << DFS->getNumInstrs(SU);
Andrew Trickea9fd952013-01-25 07:45:29 +00003205 return SS.str();
3206 }
3207 static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G) {
3208 return G->getGraphNodeLabel(SU);
3209 }
3210
Andrew Trickd7f890e2013-12-28 21:56:47 +00003211 static std::string getNodeAttributes(const SUnit *N, const ScheduleDAG *G) {
Andrew Trickea9fd952013-01-25 07:45:29 +00003212 std::string Str("shape=Mrecord");
Andrew Trickd7f890e2013-12-28 21:56:47 +00003213 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3214 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
3215 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : 0;
Andrew Trickea9fd952013-01-25 07:45:29 +00003216 if (DFS) {
3217 Str += ",style=filled,fillcolor=\"#";
3218 Str += DOT::getColorString(DFS->getSubtreeID(N));
3219 Str += '"';
3220 }
3221 return Str;
3222 }
3223};
3224} // namespace llvm
3225#endif // NDEBUG
3226
3227/// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
3228/// rendered using 'dot'.
3229///
3230void ScheduleDAGMI::viewGraph(const Twine &Name, const Twine &Title) {
3231#ifndef NDEBUG
3232 ViewGraph(this, Name, false, Title);
3233#else
3234 errs() << "ScheduleDAGMI::viewGraph is only available in debug builds on "
3235 << "systems with Graphviz or gv!\n";
3236#endif // NDEBUG
3237}
3238
3239/// Out-of-line implementation with no arguments is handy for gdb.
3240void ScheduleDAGMI::viewGraph() {
3241 viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName());
3242}