blob: aa599158e9efffaa43dc8f60414ec92657b17357 [file] [log] [blame]
Andrew Trick5429a6b2012-05-17 22:37:09 +00001//===- MachineScheduler.cpp - Machine Instruction Scheduler ---------------===//
Andrew Trick96f678f2012-01-13 06:30:30 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// MachineScheduler schedules machine instructions after phi elimination. It
11// preserves LiveIntervals so it can be invoked before register allocation.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "misched"
16
Andrew Trickc174eaf2012-03-08 01:41:12 +000017#include "llvm/CodeGen/MachineScheduler.h"
Chandler Carruthd04a8d42012-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"
Andrew Trick96f678f2012-01-13 06:30:30 +000022#include "llvm/CodeGen/Passes.h"
Andrew Trick15252602012-06-06 20:29:31 +000023#include "llvm/CodeGen/RegisterClassInfo.h"
Andrew Trick53e98a22012-11-28 05:13:24 +000024#include "llvm/CodeGen/ScheduleDFS.h"
Andrew Trick0a39d4e2012-05-24 22:11:09 +000025#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000026#include "llvm/Support/CommandLine.h"
27#include "llvm/Support/Debug.h"
28#include "llvm/Support/ErrorHandling.h"
29#include "llvm/Support/raw_ostream.h"
Andrew Trickc6cf11b2012-01-17 06:55:07 +000030#include <queue>
31
Andrew Trick96f678f2012-01-13 06:30:30 +000032using namespace llvm;
33
Andrew Trick78e5efe2012-09-11 00:39:15 +000034namespace llvm {
35cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
36 cl::desc("Force top-down list scheduling"));
37cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
38 cl::desc("Force bottom-up list scheduling"));
39}
Andrew Trick17d35e52012-03-14 04:00:41 +000040
Andrew Trick0df7f882012-03-07 00:18:25 +000041#ifndef NDEBUG
42static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
43 cl::desc("Pop up a window to show MISched dags after they are processed"));
Lang Hames23f1cbb2012-03-19 18:38:38 +000044
45static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
46 cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
Andrew Trick0df7f882012-03-07 00:18:25 +000047#else
48static bool ViewMISchedDAGs = false;
49#endif // NDEBUG
50
Andrew Trick9b5caaa2012-11-12 19:40:10 +000051// Experimental heuristics
52static cl::opt<bool> EnableLoadCluster("misched-cluster", cl::Hidden,
Andrew Trickad1cc1d2012-11-13 08:47:29 +000053 cl::desc("Enable load clustering."), cl::init(true));
Andrew Trick9b5caaa2012-11-12 19:40:10 +000054
Andrew Trick6996fd02012-11-12 19:52:20 +000055// Experimental heuristics
56static cl::opt<bool> EnableMacroFusion("misched-fusion", cl::Hidden,
Andrew Trickad1cc1d2012-11-13 08:47:29 +000057 cl::desc("Enable scheduling for macro fusion."), cl::init(true));
Andrew Trick6996fd02012-11-12 19:52:20 +000058
Andrew Trick178f7d02013-01-25 04:01:04 +000059// DAG subtrees must have at least this many nodes.
60static const unsigned MinSubtreeSize = 8;
61
Andrew Trick5edf2f02012-01-14 02:17:06 +000062//===----------------------------------------------------------------------===//
63// Machine Instruction Scheduling Pass and Registry
64//===----------------------------------------------------------------------===//
65
Andrew Trick86b7e2a2012-04-24 20:36:19 +000066MachineSchedContext::MachineSchedContext():
67 MF(0), MLI(0), MDT(0), PassConfig(0), AA(0), LIS(0) {
68 RegClassInfo = new RegisterClassInfo();
69}
70
71MachineSchedContext::~MachineSchedContext() {
72 delete RegClassInfo;
73}
74
Andrew Trick96f678f2012-01-13 06:30:30 +000075namespace {
Andrew Trick42b7a712012-01-17 06:55:03 +000076/// MachineScheduler runs after coalescing and before register allocation.
Andrew Trickc174eaf2012-03-08 01:41:12 +000077class MachineScheduler : public MachineSchedContext,
78 public MachineFunctionPass {
Andrew Trick96f678f2012-01-13 06:30:30 +000079public:
Andrew Trick42b7a712012-01-17 06:55:03 +000080 MachineScheduler();
Andrew Trick96f678f2012-01-13 06:30:30 +000081
82 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
83
84 virtual void releaseMemory() {}
85
86 virtual bool runOnMachineFunction(MachineFunction&);
87
88 virtual void print(raw_ostream &O, const Module* = 0) const;
89
90 static char ID; // Class identification, replacement for typeinfo
91};
92} // namespace
93
Andrew Trick42b7a712012-01-17 06:55:03 +000094char MachineScheduler::ID = 0;
Andrew Trick96f678f2012-01-13 06:30:30 +000095
Andrew Trick42b7a712012-01-17 06:55:03 +000096char &llvm::MachineSchedulerID = MachineScheduler::ID;
Andrew Trick96f678f2012-01-13 06:30:30 +000097
Andrew Trick42b7a712012-01-17 06:55:03 +000098INITIALIZE_PASS_BEGIN(MachineScheduler, "misched",
Andrew Trick96f678f2012-01-13 06:30:30 +000099 "Machine Instruction Scheduler", false, false)
100INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
101INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
102INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
Andrew Trick42b7a712012-01-17 06:55:03 +0000103INITIALIZE_PASS_END(MachineScheduler, "misched",
Andrew Trick96f678f2012-01-13 06:30:30 +0000104 "Machine Instruction Scheduler", false, false)
105
Andrew Trick42b7a712012-01-17 06:55:03 +0000106MachineScheduler::MachineScheduler()
Andrew Trickc174eaf2012-03-08 01:41:12 +0000107: MachineFunctionPass(ID) {
Andrew Trick42b7a712012-01-17 06:55:03 +0000108 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Andrew Trick96f678f2012-01-13 06:30:30 +0000109}
110
Andrew Trick42b7a712012-01-17 06:55:03 +0000111void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
Andrew Trick96f678f2012-01-13 06:30:30 +0000112 AU.setPreservesCFG();
113 AU.addRequiredID(MachineDominatorsID);
114 AU.addRequired<MachineLoopInfo>();
115 AU.addRequired<AliasAnalysis>();
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000116 AU.addRequired<TargetPassConfig>();
Andrew Trick96f678f2012-01-13 06:30:30 +0000117 AU.addRequired<SlotIndexes>();
118 AU.addPreserved<SlotIndexes>();
119 AU.addRequired<LiveIntervals>();
120 AU.addPreserved<LiveIntervals>();
Andrew Trick96f678f2012-01-13 06:30:30 +0000121 MachineFunctionPass::getAnalysisUsage(AU);
122}
123
Andrew Trick96f678f2012-01-13 06:30:30 +0000124MachinePassRegistry MachineSchedRegistry::Registry;
125
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000126/// A dummy default scheduler factory indicates whether the scheduler
127/// is overridden on the command line.
128static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
129 return 0;
130}
Andrew Trick96f678f2012-01-13 06:30:30 +0000131
132/// MachineSchedOpt allows command line selection of the scheduler.
133static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
134 RegisterPassParser<MachineSchedRegistry> >
135MachineSchedOpt("misched",
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000136 cl::init(&useDefaultMachineSched), cl::Hidden,
Andrew Trick96f678f2012-01-13 06:30:30 +0000137 cl::desc("Machine instruction scheduler to use"));
138
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000139static MachineSchedRegistry
Andrew Trick17d35e52012-03-14 04:00:41 +0000140DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000141 useDefaultMachineSched);
142
Andrew Trick17d35e52012-03-14 04:00:41 +0000143/// Forward declare the standard machine scheduler. This will be used as the
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000144/// default scheduler if the target does not set a default.
Andrew Trick17d35e52012-03-14 04:00:41 +0000145static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C);
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000146
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000147
148/// Decrement this iterator until reaching the top or a non-debug instr.
149static MachineBasicBlock::iterator
150priorNonDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator Beg) {
151 assert(I != Beg && "reached the top of the region, cannot decrement");
152 while (--I != Beg) {
153 if (!I->isDebugValue())
154 break;
155 }
156 return I;
157}
158
159/// If this iterator is a debug value, increment until reaching the End or a
160/// non-debug instruction.
161static MachineBasicBlock::iterator
162nextIfDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator End) {
Andrew Trick811d92682012-05-17 18:35:03 +0000163 for(; I != End; ++I) {
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000164 if (!I->isDebugValue())
165 break;
166 }
167 return I;
168}
169
Andrew Trickcb058d52012-03-14 04:00:38 +0000170/// Top-level MachineScheduler pass driver.
171///
172/// Visit blocks in function order. Divide each block into scheduling regions
Andrew Trick17d35e52012-03-14 04:00:41 +0000173/// and visit them bottom-up. Visiting regions bottom-up is not required, but is
174/// consistent with the DAG builder, which traverses the interior of the
175/// scheduling regions bottom-up.
Andrew Trickcb058d52012-03-14 04:00:38 +0000176///
177/// This design avoids exposing scheduling boundaries to the DAG builder,
Andrew Trick17d35e52012-03-14 04:00:41 +0000178/// simplifying the DAG builder's support for "special" target instructions.
179/// At the same time the design allows target schedulers to operate across
Andrew Trickcb058d52012-03-14 04:00:38 +0000180/// scheduling boundaries, for example to bundle the boudary instructions
181/// without reordering them. This creates complexity, because the target
182/// scheduler must update the RegionBegin and RegionEnd positions cached by
183/// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
184/// design would be to split blocks at scheduling boundaries, but LLVM has a
185/// general bias against block splitting purely for implementation simplicity.
Andrew Trick42b7a712012-01-17 06:55:03 +0000186bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
Andrew Trick89c324b2012-05-10 21:06:21 +0000187 DEBUG(dbgs() << "Before MISsched:\n"; mf.print(dbgs()));
188
Andrew Trick96f678f2012-01-13 06:30:30 +0000189 // Initialize the context of the pass.
190 MF = &mf;
191 MLI = &getAnalysis<MachineLoopInfo>();
192 MDT = &getAnalysis<MachineDominatorTree>();
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000193 PassConfig = &getAnalysis<TargetPassConfig>();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000194 AA = &getAnalysis<AliasAnalysis>();
195
Lang Hames907cc8f2012-01-27 22:36:19 +0000196 LIS = &getAnalysis<LiveIntervals>();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000197 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
Andrew Trick96f678f2012-01-13 06:30:30 +0000198
Andrew Trick86b7e2a2012-04-24 20:36:19 +0000199 RegClassInfo->runOnMachineFunction(*MF);
Andrew Trick006e1ab2012-04-24 17:56:43 +0000200
Andrew Trick96f678f2012-01-13 06:30:30 +0000201 // Select the scheduler, or set the default.
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000202 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
203 if (Ctor == useDefaultMachineSched) {
204 // Get the default scheduler set by the target.
205 Ctor = MachineSchedRegistry::getDefault();
206 if (!Ctor) {
Andrew Trick17d35e52012-03-14 04:00:41 +0000207 Ctor = createConvergingSched;
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000208 MachineSchedRegistry::setDefault(Ctor);
209 }
Andrew Trick96f678f2012-01-13 06:30:30 +0000210 }
211 // Instantiate the selected scheduler.
212 OwningPtr<ScheduleDAGInstrs> Scheduler(Ctor(this));
213
214 // Visit all machine basic blocks.
Andrew Trick006e1ab2012-04-24 17:56:43 +0000215 //
216 // TODO: Visit blocks in global postorder or postorder within the bottom-up
217 // loop tree. Then we can optionally compute global RegPressure.
Andrew Trick96f678f2012-01-13 06:30:30 +0000218 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
219 MBB != MBBEnd; ++MBB) {
220
Andrew Trick1fabd9f2012-03-09 08:02:51 +0000221 Scheduler->startBlock(MBB);
222
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000223 // Break the block into scheduling regions [I, RegionEnd), and schedule each
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +0000224 // region as soon as it is discovered. RegionEnd points the scheduling
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000225 // boundary at the bottom of the region. The DAG does not include RegionEnd,
226 // but the region does (i.e. the next RegionEnd is above the previous
227 // RegionBegin). If the current block has no terminator then RegionEnd ==
228 // MBB->end() for the bottom region.
229 //
230 // The Scheduler may insert instructions during either schedule() or
231 // exitRegion(), even for empty regions. So the local iterators 'I' and
232 // 'RegionEnd' are invalid across these calls.
Andrew Trick22764532012-11-06 07:10:34 +0000233 unsigned RemainingInstrs = MBB->size();
Andrew Trick7799eb42012-03-09 03:46:39 +0000234 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000235 RegionEnd != MBB->begin(); RegionEnd = Scheduler->begin()) {
Andrew Trick006e1ab2012-04-24 17:56:43 +0000236
Andrew Trick1fabd9f2012-03-09 08:02:51 +0000237 // Avoid decrementing RegionEnd for blocks with no terminator.
238 if (RegionEnd != MBB->end()
239 || TII->isSchedulingBoundary(llvm::prior(RegionEnd), MBB, *MF)) {
240 --RegionEnd;
241 // Count the boundary instruction.
Andrew Trick22764532012-11-06 07:10:34 +0000242 --RemainingInstrs;
Andrew Trick1fabd9f2012-03-09 08:02:51 +0000243 }
244
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000245 // The next region starts above the previous region. Look backward in the
246 // instruction stream until we find the nearest boundary.
247 MachineBasicBlock::iterator I = RegionEnd;
Andrew Trick22764532012-11-06 07:10:34 +0000248 for(;I != MBB->begin(); --I, --RemainingInstrs) {
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000249 if (TII->isSchedulingBoundary(llvm::prior(I), MBB, *MF))
250 break;
251 }
Andrew Trick47c14452012-03-07 05:21:52 +0000252 // Notify the scheduler of the region, even if we may skip scheduling
253 // it. Perhaps it still needs to be bundled.
Andrew Trick22764532012-11-06 07:10:34 +0000254 Scheduler->enterRegion(MBB, I, RegionEnd, RemainingInstrs);
Andrew Trick47c14452012-03-07 05:21:52 +0000255
256 // Skip empty scheduling regions (0 or 1 schedulable instructions).
257 if (I == RegionEnd || I == llvm::prior(RegionEnd)) {
Andrew Trick47c14452012-03-07 05:21:52 +0000258 // Close the current region. Bundle the terminator if needed.
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000259 // This invalidates 'RegionEnd' and 'I'.
Andrew Trick47c14452012-03-07 05:21:52 +0000260 Scheduler->exitRegion();
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000261 continue;
Andrew Trick3c58ba82012-01-14 02:17:18 +0000262 }
Andrew Trickbb0a2422012-05-24 22:11:14 +0000263 DEBUG(dbgs() << "********** MI Scheduling **********\n");
Craig Topper96601ca2012-08-22 06:07:19 +0000264 DEBUG(dbgs() << MF->getName()
Andrew Trick291411c2012-02-08 02:17:21 +0000265 << ":BB#" << MBB->getNumber() << "\n From: " << *I << " To: ";
266 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
267 else dbgs() << "End";
Andrew Trick22764532012-11-06 07:10:34 +0000268 dbgs() << " Remaining: " << RemainingInstrs << "\n");
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000269
Andrew Trickd24da972012-03-09 03:46:42 +0000270 // Schedule a region: possibly reorder instructions.
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000271 // This invalidates 'RegionEnd' and 'I'.
Andrew Trick953be892012-03-07 23:00:49 +0000272 Scheduler->schedule();
Andrew Trickd24da972012-03-09 03:46:42 +0000273
274 // Close the current region.
Andrew Trick47c14452012-03-07 05:21:52 +0000275 Scheduler->exitRegion();
276
277 // Scheduling has invalidated the current iterator 'I'. Ask the
278 // scheduler for the top of it's scheduled region.
279 RegionEnd = Scheduler->begin();
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000280 }
Andrew Trick22764532012-11-06 07:10:34 +0000281 assert(RemainingInstrs == 0 && "Instruction count mismatch!");
Andrew Trick953be892012-03-07 23:00:49 +0000282 Scheduler->finishBlock();
Andrew Trick96f678f2012-01-13 06:30:30 +0000283 }
Andrew Trick830da402012-04-01 07:24:23 +0000284 Scheduler->finalizeSchedule();
Andrew Trickaad37f12012-03-21 04:12:12 +0000285 DEBUG(LIS->print(dbgs()));
Andrew Trick96f678f2012-01-13 06:30:30 +0000286 return true;
287}
288
Andrew Trick42b7a712012-01-17 06:55:03 +0000289void MachineScheduler::print(raw_ostream &O, const Module* m) const {
Andrew Trick96f678f2012-01-13 06:30:30 +0000290 // unimplemented
291}
292
Manman Renb720be62012-09-11 22:23:19 +0000293#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Andrew Trick78e5efe2012-09-11 00:39:15 +0000294void ReadyQueue::dump() {
295 dbgs() << Name << ": ";
296 for (unsigned i = 0, e = Queue.size(); i < e; ++i)
297 dbgs() << Queue[i]->NodeNum << " ";
298 dbgs() << "\n";
299}
300#endif
Andrew Trick17d35e52012-03-14 04:00:41 +0000301
302//===----------------------------------------------------------------------===//
303// ScheduleDAGMI - Base class for MachineInstr scheduling with LiveIntervals
304// preservation.
305//===----------------------------------------------------------------------===//
306
Andrew Trick178f7d02013-01-25 04:01:04 +0000307ScheduleDAGMI::~ScheduleDAGMI() {
308 delete DFSResult;
309 DeleteContainerPointers(Mutations);
310 delete SchedImpl;
311}
312
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000313bool ScheduleDAGMI::addEdge(SUnit *SuccSU, const SDep &PredDep) {
Andrew Trick6996fd02012-11-12 19:52:20 +0000314 if (SuccSU != &ExitSU) {
315 // Do not use WillCreateCycle, it assumes SD scheduling.
316 // If Pred is reachable from Succ, then the edge creates a cycle.
317 if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
318 return false;
319 Topo.AddPred(SuccSU, PredDep.getSUnit());
320 }
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000321 SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
322 // Return true regardless of whether a new edge needed to be inserted.
323 return true;
324}
325
Andrew Trickc174eaf2012-03-08 01:41:12 +0000326/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
327/// NumPredsLeft reaches zero, release the successor node.
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000328///
329/// FIXME: Adjust SuccSU height based on MinLatency.
Andrew Trick17d35e52012-03-14 04:00:41 +0000330void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
Andrew Trickc174eaf2012-03-08 01:41:12 +0000331 SUnit *SuccSU = SuccEdge->getSUnit();
332
Andrew Trickae692f22012-11-12 19:28:57 +0000333 if (SuccEdge->isWeak()) {
334 --SuccSU->WeakPredsLeft;
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000335 if (SuccEdge->isCluster())
336 NextClusterSucc = SuccSU;
Andrew Trickae692f22012-11-12 19:28:57 +0000337 return;
338 }
Andrew Trickc174eaf2012-03-08 01:41:12 +0000339#ifndef NDEBUG
340 if (SuccSU->NumPredsLeft == 0) {
341 dbgs() << "*** Scheduling failed! ***\n";
342 SuccSU->dump(this);
343 dbgs() << " has been released too many times!\n";
344 llvm_unreachable(0);
345 }
346#endif
347 --SuccSU->NumPredsLeft;
348 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
Andrew Trick17d35e52012-03-14 04:00:41 +0000349 SchedImpl->releaseTopNode(SuccSU);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000350}
351
352/// releaseSuccessors - Call releaseSucc on each of SU's successors.
Andrew Trick17d35e52012-03-14 04:00:41 +0000353void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
Andrew Trickc174eaf2012-03-08 01:41:12 +0000354 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
355 I != E; ++I) {
356 releaseSucc(SU, &*I);
357 }
358}
359
Andrew Trick17d35e52012-03-14 04:00:41 +0000360/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
361/// NumSuccsLeft reaches zero, release the predecessor node.
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000362///
363/// FIXME: Adjust PredSU height based on MinLatency.
Andrew Trick17d35e52012-03-14 04:00:41 +0000364void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
365 SUnit *PredSU = PredEdge->getSUnit();
366
Andrew Trickae692f22012-11-12 19:28:57 +0000367 if (PredEdge->isWeak()) {
368 --PredSU->WeakSuccsLeft;
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000369 if (PredEdge->isCluster())
370 NextClusterPred = PredSU;
Andrew Trickae692f22012-11-12 19:28:57 +0000371 return;
372 }
Andrew Trick17d35e52012-03-14 04:00:41 +0000373#ifndef NDEBUG
374 if (PredSU->NumSuccsLeft == 0) {
375 dbgs() << "*** Scheduling failed! ***\n";
376 PredSU->dump(this);
377 dbgs() << " has been released too many times!\n";
378 llvm_unreachable(0);
379 }
380#endif
381 --PredSU->NumSuccsLeft;
382 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
383 SchedImpl->releaseBottomNode(PredSU);
384}
385
386/// releasePredecessors - Call releasePred on each of SU's predecessors.
387void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
388 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
389 I != E; ++I) {
390 releasePred(SU, &*I);
391 }
392}
393
394void ScheduleDAGMI::moveInstruction(MachineInstr *MI,
395 MachineBasicBlock::iterator InsertPos) {
Andrew Trick811d92682012-05-17 18:35:03 +0000396 // Advance RegionBegin if the first instruction moves down.
Andrew Trick1ce062f2012-03-21 04:12:10 +0000397 if (&*RegionBegin == MI)
Andrew Trick811d92682012-05-17 18:35:03 +0000398 ++RegionBegin;
399
400 // Update the instruction stream.
Andrew Trick17d35e52012-03-14 04:00:41 +0000401 BB->splice(InsertPos, BB, MI);
Andrew Trick811d92682012-05-17 18:35:03 +0000402
403 // Update LiveIntervals
Andrew Trick27c28ce2012-10-16 00:22:51 +0000404 LIS->handleMove(MI, /*UpdateFlags=*/true);
Andrew Trick811d92682012-05-17 18:35:03 +0000405
406 // Recede RegionBegin if an instruction moves above the first.
Andrew Trick17d35e52012-03-14 04:00:41 +0000407 if (RegionBegin == InsertPos)
408 RegionBegin = MI;
409}
410
Andrew Trick0b0d8992012-03-21 04:12:07 +0000411bool ScheduleDAGMI::checkSchedLimit() {
412#ifndef NDEBUG
413 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
414 CurrentTop = CurrentBottom;
415 return false;
416 }
417 ++NumInstrsScheduled;
418#endif
419 return true;
420}
421
Andrew Trick006e1ab2012-04-24 17:56:43 +0000422/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
423/// crossing a scheduling boundary. [begin, end) includes all instructions in
424/// the region, including the boundary itself and single-instruction regions
425/// that don't get scheduled.
426void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
427 MachineBasicBlock::iterator begin,
428 MachineBasicBlock::iterator end,
429 unsigned endcount)
430{
431 ScheduleDAGInstrs::enterRegion(bb, begin, end, endcount);
Andrew Trick7f8ab782012-05-10 21:06:10 +0000432
433 // For convenience remember the end of the liveness region.
434 LiveRegionEnd =
435 (RegionEnd == bb->end()) ? RegionEnd : llvm::next(RegionEnd);
436}
437
438// Setup the register pressure trackers for the top scheduled top and bottom
439// scheduled regions.
440void ScheduleDAGMI::initRegPressure() {
441 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin);
442 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
443
444 // Close the RPTracker to finalize live ins.
445 RPTracker.closeRegion();
446
Andrew Trickbb0a2422012-05-24 22:11:14 +0000447 DEBUG(RPTracker.getPressure().dump(TRI));
448
Andrew Trick7f8ab782012-05-10 21:06:10 +0000449 // Initialize the live ins and live outs.
450 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
451 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
452
453 // Close one end of the tracker so we can call
454 // getMaxUpward/DownwardPressureDelta before advancing across any
455 // instructions. This converts currently live regs into live ins/outs.
456 TopRPTracker.closeTop();
457 BotRPTracker.closeBottom();
458
459 // Account for liveness generated by the region boundary.
460 if (LiveRegionEnd != RegionEnd)
461 BotRPTracker.recede();
462
463 assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000464
465 // Cache the list of excess pressure sets in this region. This will also track
466 // the max pressure in the scheduled code for these sets.
467 RegionCriticalPSets.clear();
468 std::vector<unsigned> RegionPressure = RPTracker.getPressure().MaxSetPressure;
469 for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
470 unsigned Limit = TRI->getRegPressureSetLimit(i);
Andrew Trick78e5efe2012-09-11 00:39:15 +0000471 DEBUG(dbgs() << TRI->getRegPressureSetName(i)
472 << "Limit " << Limit
473 << " Actual " << RegionPressure[i] << "\n");
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000474 if (RegionPressure[i] > Limit)
475 RegionCriticalPSets.push_back(PressureElement(i, 0));
476 }
477 DEBUG(dbgs() << "Excess PSets: ";
478 for (unsigned i = 0, e = RegionCriticalPSets.size(); i != e; ++i)
479 dbgs() << TRI->getRegPressureSetName(
480 RegionCriticalPSets[i].PSetID) << " ";
481 dbgs() << "\n");
482}
483
484// FIXME: When the pressure tracker deals in pressure differences then we won't
485// iterate over all RegionCriticalPSets[i].
486void ScheduleDAGMI::
487updateScheduledPressure(std::vector<unsigned> NewMaxPressure) {
488 for (unsigned i = 0, e = RegionCriticalPSets.size(); i < e; ++i) {
489 unsigned ID = RegionCriticalPSets[i].PSetID;
490 int &MaxUnits = RegionCriticalPSets[i].UnitIncrease;
491 if ((int)NewMaxPressure[ID] > MaxUnits)
492 MaxUnits = NewMaxPressure[ID];
493 }
Andrew Trick006e1ab2012-04-24 17:56:43 +0000494}
495
Andrew Trick17d35e52012-03-14 04:00:41 +0000496/// schedule - Called back from MachineScheduler::runOnMachineFunction
Andrew Trick006e1ab2012-04-24 17:56:43 +0000497/// after setting up the current scheduling region. [RegionBegin, RegionEnd)
498/// only includes instructions that have DAG nodes, not scheduling boundaries.
Andrew Trick78e5efe2012-09-11 00:39:15 +0000499///
500/// This is a skeletal driver, with all the functionality pushed into helpers,
501/// so that it can be easilly extended by experimental schedulers. Generally,
502/// implementing MachineSchedStrategy should be sufficient to implement a new
503/// scheduling algorithm. However, if a scheduler further subclasses
504/// ScheduleDAGMI then it will want to override this virtual method in order to
505/// update any specialized state.
Andrew Trick17d35e52012-03-14 04:00:41 +0000506void ScheduleDAGMI::schedule() {
Andrew Trick78e5efe2012-09-11 00:39:15 +0000507 buildDAGWithRegPressure();
508
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000509 Topo.InitDAGTopologicalSorting();
510
Andrew Trickd039b382012-09-14 17:22:42 +0000511 postprocessDAG();
512
Andrew Trick4e1fb182013-01-25 06:33:57 +0000513 SmallVector<SUnit*, 8> TopRoots, BotRoots;
514 findRootsAndBiasEdges(TopRoots, BotRoots);
515
516 // Initialize the strategy before modifying the DAG.
517 // This may initialize a DFSResult to be used for queue priority.
518 SchedImpl->initialize(this);
519
Andrew Trick78e5efe2012-09-11 00:39:15 +0000520 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
521 SUnits[su].dumpAll(this));
Andrew Trick4e1fb182013-01-25 06:33:57 +0000522 if (ViewMISchedDAGs) viewGraph();
Andrew Trick78e5efe2012-09-11 00:39:15 +0000523
Andrew Trick4e1fb182013-01-25 06:33:57 +0000524 // Initialize ready queues now that the DAG and priority data are finalized.
525 initQueues(TopRoots, BotRoots);
Andrew Trick78e5efe2012-09-11 00:39:15 +0000526
527 bool IsTopNode = false;
528 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
Andrew Trick30c6ec22012-10-08 18:53:53 +0000529 assert(!SU->isScheduled && "Node already scheduled");
Andrew Trick78e5efe2012-09-11 00:39:15 +0000530 if (!checkSchedLimit())
531 break;
532
533 scheduleMI(SU, IsTopNode);
534
535 updateQueues(SU, IsTopNode);
536 }
537 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
538
539 placeDebugValues();
Andrew Trick3b87f622012-11-07 07:05:09 +0000540
541 DEBUG({
Andrew Trickb4221042012-11-28 03:42:47 +0000542 unsigned BBNum = begin()->getParent()->getNumber();
Andrew Trick3b87f622012-11-07 07:05:09 +0000543 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
544 dumpSchedule();
545 dbgs() << '\n';
546 });
Andrew Trick78e5efe2012-09-11 00:39:15 +0000547}
548
549/// Build the DAG and setup three register pressure trackers.
550void ScheduleDAGMI::buildDAGWithRegPressure() {
Andrew Trick7f8ab782012-05-10 21:06:10 +0000551 // Initialize the register pressure tracker used by buildSchedGraph.
552 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
Andrew Trick006e1ab2012-04-24 17:56:43 +0000553
Andrew Trick7f8ab782012-05-10 21:06:10 +0000554 // Account for liveness generate by the region boundary.
555 if (LiveRegionEnd != RegionEnd)
556 RPTracker.recede();
557
558 // Build the DAG, and compute current register pressure.
Andrew Trick006e1ab2012-04-24 17:56:43 +0000559 buildSchedGraph(AA, &RPTracker);
Andrew Trick78e5efe2012-09-11 00:39:15 +0000560 if (ViewMISchedDAGs) viewGraph();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000561
Andrew Trick7f8ab782012-05-10 21:06:10 +0000562 // Initialize top/bottom trackers after computing region pressure.
563 initRegPressure();
Andrew Trick78e5efe2012-09-11 00:39:15 +0000564}
Andrew Trick7f8ab782012-05-10 21:06:10 +0000565
Andrew Trickd039b382012-09-14 17:22:42 +0000566/// Apply each ScheduleDAGMutation step in order.
567void ScheduleDAGMI::postprocessDAG() {
568 for (unsigned i = 0, e = Mutations.size(); i < e; ++i) {
569 Mutations[i]->apply(this);
570 }
571}
572
Andrew Trick4e1fb182013-01-25 06:33:57 +0000573void ScheduleDAGMI::computeDFSResult() {
Andrew Trick178f7d02013-01-25 04:01:04 +0000574 if (!DFSResult)
575 DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize);
576 DFSResult->clear();
Andrew Trick178f7d02013-01-25 04:01:04 +0000577 ScheduledTrees.clear();
Andrew Trick4e1fb182013-01-25 06:33:57 +0000578 DFSResult->resize(SUnits.size());
579 DFSResult->compute(SUnits);
Andrew Trick178f7d02013-01-25 04:01:04 +0000580 ScheduledTrees.resize(DFSResult->getNumSubtrees());
581}
582
Andrew Trick4e1fb182013-01-25 06:33:57 +0000583void ScheduleDAGMI::findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
584 SmallVectorImpl<SUnit*> &BotRoots) {
Andrew Trick1e94e982012-10-15 18:02:27 +0000585 for (std::vector<SUnit>::iterator
586 I = SUnits.begin(), E = SUnits.end(); I != E; ++I) {
Andrew Trickae692f22012-11-12 19:28:57 +0000587 SUnit *SU = &(*I);
Andrew Trickdb417062013-01-24 02:09:57 +0000588
589 // Order predecessors so DFSResult follows the critical path.
590 SU->biasCriticalPath();
591
Andrew Trick1e94e982012-10-15 18:02:27 +0000592 // A SUnit is ready to top schedule if it has no predecessors.
Andrew Trickae692f22012-11-12 19:28:57 +0000593 if (!I->NumPredsLeft && SU != &EntrySU)
Andrew Trick4e1fb182013-01-25 06:33:57 +0000594 TopRoots.push_back(SU);
Andrew Trick1e94e982012-10-15 18:02:27 +0000595 // A SUnit is ready to bottom schedule if it has no successors.
Andrew Trickae692f22012-11-12 19:28:57 +0000596 if (!I->NumSuccsLeft && SU != &ExitSU)
597 BotRoots.push_back(SU);
Andrew Trick1e94e982012-10-15 18:02:27 +0000598 }
Andrew Trick1e94e982012-10-15 18:02:27 +0000599}
600
Andrew Trick78e5efe2012-09-11 00:39:15 +0000601/// Identify DAG roots and setup scheduler queues.
Andrew Trick4e1fb182013-01-25 06:33:57 +0000602void ScheduleDAGMI::initQueues(ArrayRef<SUnit*> TopRoots,
603 ArrayRef<SUnit*> BotRoots) {
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000604 NextClusterSucc = NULL;
605 NextClusterPred = NULL;
Andrew Trick1e94e982012-10-15 18:02:27 +0000606
Andrew Trickae692f22012-11-12 19:28:57 +0000607 // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
Andrew Trick4e1fb182013-01-25 06:33:57 +0000608 //
609 // Nodes with unreleased weak edges can still be roots.
610 // Release top roots in forward order.
611 for (SmallVectorImpl<SUnit*>::const_iterator
612 I = TopRoots.begin(), E = TopRoots.end(); I != E; ++I) {
613 SchedImpl->releaseTopNode(*I);
614 }
615 // Release bottom roots in reverse order so the higher priority nodes appear
616 // first. This is more natural and slightly more efficient.
617 for (SmallVectorImpl<SUnit*>::const_reverse_iterator
618 I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I) {
619 SchedImpl->releaseBottomNode(*I);
620 }
Andrew Trickae692f22012-11-12 19:28:57 +0000621
Andrew Trickc174eaf2012-03-08 01:41:12 +0000622 releaseSuccessors(&EntrySU);
Andrew Trick17d35e52012-03-14 04:00:41 +0000623 releasePredecessors(&ExitSU);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000624
Andrew Trick1e94e982012-10-15 18:02:27 +0000625 SchedImpl->registerRoots();
626
Andrew Trick657b75b2012-12-01 01:22:49 +0000627 // Advance past initial DebugValues.
628 assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000629 CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
Andrew Trick657b75b2012-12-01 01:22:49 +0000630 TopRPTracker.setPos(CurrentTop);
631
Andrew Trick17d35e52012-03-14 04:00:41 +0000632 CurrentBottom = RegionEnd;
Andrew Trick78e5efe2012-09-11 00:39:15 +0000633}
Andrew Trickc174eaf2012-03-08 01:41:12 +0000634
Andrew Trick78e5efe2012-09-11 00:39:15 +0000635/// Move an instruction and update register pressure.
636void ScheduleDAGMI::scheduleMI(SUnit *SU, bool IsTopNode) {
637 // Move the instruction to its new location in the instruction stream.
638 MachineInstr *MI = SU->getInstr();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000639
Andrew Trick78e5efe2012-09-11 00:39:15 +0000640 if (IsTopNode) {
641 assert(SU->isTopReady() && "node still has unscheduled dependencies");
642 if (&*CurrentTop == MI)
643 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
Andrew Trick17d35e52012-03-14 04:00:41 +0000644 else {
Andrew Trick78e5efe2012-09-11 00:39:15 +0000645 moveInstruction(MI, CurrentTop);
646 TopRPTracker.setPos(MI);
Andrew Trick17d35e52012-03-14 04:00:41 +0000647 }
Andrew Trick000b2502012-04-24 18:04:37 +0000648
Andrew Trick78e5efe2012-09-11 00:39:15 +0000649 // Update top scheduled pressure.
650 TopRPTracker.advance();
651 assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
652 updateScheduledPressure(TopRPTracker.getPressure().MaxSetPressure);
653 }
654 else {
655 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
656 MachineBasicBlock::iterator priorII =
657 priorNonDebug(CurrentBottom, CurrentTop);
658 if (&*priorII == MI)
659 CurrentBottom = priorII;
660 else {
661 if (&*CurrentTop == MI) {
662 CurrentTop = nextIfDebug(++CurrentTop, priorII);
663 TopRPTracker.setPos(CurrentTop);
664 }
665 moveInstruction(MI, CurrentBottom);
666 CurrentBottom = MI;
667 }
668 // Update bottom scheduled pressure.
669 BotRPTracker.recede();
670 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
671 updateScheduledPressure(BotRPTracker.getPressure().MaxSetPressure);
672 }
673}
674
675/// Update scheduler queues after scheduling an instruction.
676void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
677 // Release dependent instructions for scheduling.
678 if (IsTopNode)
679 releaseSuccessors(SU);
680 else
681 releasePredecessors(SU);
682
683 SU->isScheduled = true;
684
Andrew Trick178f7d02013-01-25 04:01:04 +0000685 if (DFSResult) {
686 unsigned SubtreeID = DFSResult->getSubtreeID(SU);
687 if (!ScheduledTrees.test(SubtreeID)) {
688 ScheduledTrees.set(SubtreeID);
689 DFSResult->scheduleTree(SubtreeID);
690 SchedImpl->scheduleTree(SubtreeID);
691 }
692 }
693
Andrew Trick78e5efe2012-09-11 00:39:15 +0000694 // Notify the scheduling strategy after updating the DAG.
695 SchedImpl->schedNode(SU, IsTopNode);
Andrew Trick000b2502012-04-24 18:04:37 +0000696}
697
698/// Reinsert any remaining debug_values, just like the PostRA scheduler.
699void ScheduleDAGMI::placeDebugValues() {
700 // If first instruction was a DBG_VALUE then put it back.
701 if (FirstDbgValue) {
702 BB->splice(RegionBegin, BB, FirstDbgValue);
703 RegionBegin = FirstDbgValue;
704 }
705
706 for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
707 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
708 std::pair<MachineInstr *, MachineInstr *> P = *prior(DI);
709 MachineInstr *DbgValue = P.first;
710 MachineBasicBlock::iterator OrigPrevMI = P.second;
Andrew Trick67bdd422012-12-01 01:22:38 +0000711 if (&*RegionBegin == DbgValue)
712 ++RegionBegin;
Andrew Trick000b2502012-04-24 18:04:37 +0000713 BB->splice(++OrigPrevMI, BB, DbgValue);
714 if (OrigPrevMI == llvm::prior(RegionEnd))
715 RegionEnd = DbgValue;
716 }
717 DbgValues.clear();
718 FirstDbgValue = NULL;
Andrew Trickc174eaf2012-03-08 01:41:12 +0000719}
720
Andrew Trick3b87f622012-11-07 07:05:09 +0000721#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
722void ScheduleDAGMI::dumpSchedule() const {
723 for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
724 if (SUnit *SU = getSUnit(&(*MI)))
725 SU->dump(this);
726 else
727 dbgs() << "Missing SUnit\n";
728 }
729}
730#endif
731
Andrew Trick6996fd02012-11-12 19:52:20 +0000732//===----------------------------------------------------------------------===//
733// LoadClusterMutation - DAG post-processing to cluster loads.
734//===----------------------------------------------------------------------===//
735
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000736namespace {
737/// \brief Post-process the DAG to create cluster edges between neighboring
738/// loads.
739class LoadClusterMutation : public ScheduleDAGMutation {
740 struct LoadInfo {
741 SUnit *SU;
742 unsigned BaseReg;
743 unsigned Offset;
744 LoadInfo(SUnit *su, unsigned reg, unsigned ofs)
745 : SU(su), BaseReg(reg), Offset(ofs) {}
746 };
747 static bool LoadInfoLess(const LoadClusterMutation::LoadInfo &LHS,
748 const LoadClusterMutation::LoadInfo &RHS);
749
750 const TargetInstrInfo *TII;
751 const TargetRegisterInfo *TRI;
752public:
753 LoadClusterMutation(const TargetInstrInfo *tii,
754 const TargetRegisterInfo *tri)
755 : TII(tii), TRI(tri) {}
756
757 virtual void apply(ScheduleDAGMI *DAG);
758protected:
759 void clusterNeighboringLoads(ArrayRef<SUnit*> Loads, ScheduleDAGMI *DAG);
760};
761} // anonymous
762
763bool LoadClusterMutation::LoadInfoLess(
764 const LoadClusterMutation::LoadInfo &LHS,
765 const LoadClusterMutation::LoadInfo &RHS) {
766 if (LHS.BaseReg != RHS.BaseReg)
767 return LHS.BaseReg < RHS.BaseReg;
768 return LHS.Offset < RHS.Offset;
769}
770
771void LoadClusterMutation::clusterNeighboringLoads(ArrayRef<SUnit*> Loads,
772 ScheduleDAGMI *DAG) {
773 SmallVector<LoadClusterMutation::LoadInfo,32> LoadRecords;
774 for (unsigned Idx = 0, End = Loads.size(); Idx != End; ++Idx) {
775 SUnit *SU = Loads[Idx];
776 unsigned BaseReg;
777 unsigned Offset;
778 if (TII->getLdStBaseRegImmOfs(SU->getInstr(), BaseReg, Offset, TRI))
779 LoadRecords.push_back(LoadInfo(SU, BaseReg, Offset));
780 }
781 if (LoadRecords.size() < 2)
782 return;
783 std::sort(LoadRecords.begin(), LoadRecords.end(), LoadInfoLess);
784 unsigned ClusterLength = 1;
785 for (unsigned Idx = 0, End = LoadRecords.size(); Idx < (End - 1); ++Idx) {
786 if (LoadRecords[Idx].BaseReg != LoadRecords[Idx+1].BaseReg) {
787 ClusterLength = 1;
788 continue;
789 }
790
791 SUnit *SUa = LoadRecords[Idx].SU;
792 SUnit *SUb = LoadRecords[Idx+1].SU;
Andrew Tricka7d2d562012-11-12 21:28:10 +0000793 if (TII->shouldClusterLoads(SUa->getInstr(), SUb->getInstr(), ClusterLength)
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000794 && DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
795
796 DEBUG(dbgs() << "Cluster loads SU(" << SUa->NodeNum << ") - SU("
797 << SUb->NodeNum << ")\n");
798 // Copy successor edges from SUa to SUb. Interleaving computation
799 // dependent on SUa can prevent load combining due to register reuse.
800 // Predecessor edges do not need to be copied from SUb to SUa since nearby
801 // loads should have effectively the same inputs.
802 for (SUnit::const_succ_iterator
803 SI = SUa->Succs.begin(), SE = SUa->Succs.end(); SI != SE; ++SI) {
804 if (SI->getSUnit() == SUb)
805 continue;
806 DEBUG(dbgs() << " Copy Succ SU(" << SI->getSUnit()->NodeNum << ")\n");
807 DAG->addEdge(SI->getSUnit(), SDep(SUb, SDep::Artificial));
808 }
809 ++ClusterLength;
810 }
811 else
812 ClusterLength = 1;
813 }
814}
815
816/// \brief Callback from DAG postProcessing to create cluster edges for loads.
817void LoadClusterMutation::apply(ScheduleDAGMI *DAG) {
818 // Map DAG NodeNum to store chain ID.
819 DenseMap<unsigned, unsigned> StoreChainIDs;
820 // Map each store chain to a set of dependent loads.
821 SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
822 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
823 SUnit *SU = &DAG->SUnits[Idx];
824 if (!SU->getInstr()->mayLoad())
825 continue;
826 unsigned ChainPredID = DAG->SUnits.size();
827 for (SUnit::const_pred_iterator
828 PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
829 if (PI->isCtrl()) {
830 ChainPredID = PI->getSUnit()->NodeNum;
831 break;
832 }
833 }
834 // Check if this chain-like pred has been seen
835 // before. ChainPredID==MaxNodeID for loads at the top of the schedule.
836 unsigned NumChains = StoreChainDependents.size();
837 std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
838 StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
839 if (Result.second)
840 StoreChainDependents.resize(NumChains + 1);
841 StoreChainDependents[Result.first->second].push_back(SU);
842 }
843 // Iterate over the store chains.
844 for (unsigned Idx = 0, End = StoreChainDependents.size(); Idx != End; ++Idx)
845 clusterNeighboringLoads(StoreChainDependents[Idx], DAG);
846}
847
Andrew Trickc174eaf2012-03-08 01:41:12 +0000848//===----------------------------------------------------------------------===//
Andrew Trick6996fd02012-11-12 19:52:20 +0000849// MacroFusion - DAG post-processing to encourage fusion of macro ops.
850//===----------------------------------------------------------------------===//
851
852namespace {
853/// \brief Post-process the DAG to create cluster edges between instructions
854/// that may be fused by the processor into a single operation.
855class MacroFusion : public ScheduleDAGMutation {
856 const TargetInstrInfo *TII;
857public:
858 MacroFusion(const TargetInstrInfo *tii): TII(tii) {}
859
860 virtual void apply(ScheduleDAGMI *DAG);
861};
862} // anonymous
863
864/// \brief Callback from DAG postProcessing to create cluster edges to encourage
865/// fused operations.
866void MacroFusion::apply(ScheduleDAGMI *DAG) {
867 // For now, assume targets can only fuse with the branch.
868 MachineInstr *Branch = DAG->ExitSU.getInstr();
869 if (!Branch)
870 return;
871
872 for (unsigned Idx = DAG->SUnits.size(); Idx > 0;) {
873 SUnit *SU = &DAG->SUnits[--Idx];
874 if (!TII->shouldScheduleAdjacent(SU->getInstr(), Branch))
875 continue;
876
877 // Create a single weak edge from SU to ExitSU. The only effect is to cause
878 // bottom-up scheduling to heavily prioritize the clustered SU. There is no
879 // need to copy predecessor edges from ExitSU to SU, since top-down
880 // scheduling cannot prioritize ExitSU anyway. To defer top-down scheduling
881 // of SU, we could create an artificial edge from the deepest root, but it
882 // hasn't been needed yet.
883 bool Success = DAG->addEdge(&DAG->ExitSU, SDep(SU, SDep::Cluster));
884 (void)Success;
885 assert(Success && "No DAG nodes should be reachable from ExitSU");
886
887 DEBUG(dbgs() << "Macro Fuse SU(" << SU->NodeNum << ")\n");
888 break;
889 }
890}
891
892//===----------------------------------------------------------------------===//
Andrew Trick17d35e52012-03-14 04:00:41 +0000893// ConvergingScheduler - Implementation of the standard MachineSchedStrategy.
Andrew Trick42b7a712012-01-17 06:55:03 +0000894//===----------------------------------------------------------------------===//
895
896namespace {
Andrew Trick17d35e52012-03-14 04:00:41 +0000897/// ConvergingScheduler shrinks the unscheduled zone using heuristics to balance
898/// the schedule.
899class ConvergingScheduler : public MachineSchedStrategy {
Andrew Trick3b87f622012-11-07 07:05:09 +0000900public:
901 /// Represent the type of SchedCandidate found within a single queue.
902 /// pickNodeBidirectional depends on these listed by decreasing priority.
903 enum CandReason {
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000904 NoCand, SingleExcess, SingleCritical, Cluster,
905 ResourceReduce, ResourceDemand, BotHeightReduce, BotPathReduce,
906 TopDepthReduce, TopPathReduce, SingleMax, MultiPressure, NextDefUse,
907 NodeOrder};
Andrew Trick3b87f622012-11-07 07:05:09 +0000908
909#ifndef NDEBUG
910 static const char *getReasonStr(ConvergingScheduler::CandReason Reason);
911#endif
912
913 /// Policy for scheduling the next instruction in the candidate's zone.
914 struct CandPolicy {
915 bool ReduceLatency;
916 unsigned ReduceResIdx;
917 unsigned DemandResIdx;
918
919 CandPolicy(): ReduceLatency(false), ReduceResIdx(0), DemandResIdx(0) {}
920 };
921
922 /// Status of an instruction's critical resource consumption.
923 struct SchedResourceDelta {
924 // Count critical resources in the scheduled region required by SU.
925 unsigned CritResources;
926
927 // Count critical resources from another region consumed by SU.
928 unsigned DemandedResources;
929
930 SchedResourceDelta(): CritResources(0), DemandedResources(0) {}
931
932 bool operator==(const SchedResourceDelta &RHS) const {
933 return CritResources == RHS.CritResources
934 && DemandedResources == RHS.DemandedResources;
935 }
936 bool operator!=(const SchedResourceDelta &RHS) const {
937 return !operator==(RHS);
938 }
939 };
Andrew Trick7196a8f2012-05-10 21:06:16 +0000940
941 /// Store the state used by ConvergingScheduler heuristics, required for the
942 /// lifetime of one invocation of pickNode().
943 struct SchedCandidate {
Andrew Trick3b87f622012-11-07 07:05:09 +0000944 CandPolicy Policy;
945
Andrew Trick7196a8f2012-05-10 21:06:16 +0000946 // The best SUnit candidate.
947 SUnit *SU;
948
Andrew Trick3b87f622012-11-07 07:05:09 +0000949 // The reason for this candidate.
950 CandReason Reason;
951
Andrew Trick7196a8f2012-05-10 21:06:16 +0000952 // Register pressure values for the best candidate.
953 RegPressureDelta RPDelta;
954
Andrew Trick3b87f622012-11-07 07:05:09 +0000955 // Critical resource consumption of the best candidate.
956 SchedResourceDelta ResDelta;
957
958 SchedCandidate(const CandPolicy &policy)
959 : Policy(policy), SU(NULL), Reason(NoCand) {}
960
961 bool isValid() const { return SU; }
962
963 // Copy the status of another candidate without changing policy.
964 void setBest(SchedCandidate &Best) {
965 assert(Best.Reason != NoCand && "uninitialized Sched candidate");
966 SU = Best.SU;
967 Reason = Best.Reason;
968 RPDelta = Best.RPDelta;
969 ResDelta = Best.ResDelta;
970 }
971
972 void initResourceDelta(const ScheduleDAGMI *DAG,
973 const TargetSchedModel *SchedModel);
Andrew Trick7196a8f2012-05-10 21:06:16 +0000974 };
Andrew Trick3b87f622012-11-07 07:05:09 +0000975
976 /// Summarize the unscheduled region.
977 struct SchedRemainder {
978 // Critical path through the DAG in expected latency.
979 unsigned CriticalPath;
980
981 // Unscheduled resources
982 SmallVector<unsigned, 16> RemainingCounts;
983 // Critical resource for the unscheduled zone.
984 unsigned CritResIdx;
985 // Number of micro-ops left to schedule.
986 unsigned RemainingMicroOps;
Andrew Trick3b87f622012-11-07 07:05:09 +0000987
Andrew Trick3b87f622012-11-07 07:05:09 +0000988 void reset() {
989 CriticalPath = 0;
990 RemainingCounts.clear();
991 CritResIdx = 0;
992 RemainingMicroOps = 0;
Andrew Trick3b87f622012-11-07 07:05:09 +0000993 }
994
995 SchedRemainder() { reset(); }
996
997 void init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel);
Andrew Trick44fd0bc2012-12-18 20:52:56 +0000998
999 unsigned getMaxRemainingCount(const TargetSchedModel *SchedModel) const {
1000 if (!SchedModel->hasInstrSchedModel())
1001 return 0;
1002
1003 return std::max(
1004 RemainingMicroOps * SchedModel->getMicroOpFactor(),
1005 RemainingCounts[CritResIdx]);
1006 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001007 };
Andrew Trick7196a8f2012-05-10 21:06:16 +00001008
Andrew Trickf3234242012-05-24 22:11:12 +00001009 /// Each Scheduling boundary is associated with ready queues. It tracks the
Andrew Trick3b87f622012-11-07 07:05:09 +00001010 /// current cycle in the direction of movement, and maintains the state
Andrew Trickf3234242012-05-24 22:11:12 +00001011 /// of "hazards" and other interlocks at the current cycle.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001012 struct SchedBoundary {
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001013 ScheduleDAGMI *DAG;
Andrew Trick412cd2f2012-10-10 05:43:09 +00001014 const TargetSchedModel *SchedModel;
Andrew Trick3b87f622012-11-07 07:05:09 +00001015 SchedRemainder *Rem;
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001016
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001017 ReadyQueue Available;
1018 ReadyQueue Pending;
1019 bool CheckPending;
1020
Andrew Trick3b87f622012-11-07 07:05:09 +00001021 // For heuristics, keep a list of the nodes that immediately depend on the
1022 // most recently scheduled node.
1023 SmallPtrSet<const SUnit*, 8> NextSUs;
1024
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001025 ScheduleHazardRecognizer *HazardRec;
1026
1027 unsigned CurrCycle;
1028 unsigned IssueCount;
1029
1030 /// MinReadyCycle - Cycle of the soonest available instruction.
1031 unsigned MinReadyCycle;
1032
Andrew Trick3b87f622012-11-07 07:05:09 +00001033 // The expected latency of the critical path in this scheduled zone.
1034 unsigned ExpectedLatency;
1035
1036 // Resources used in the scheduled zone beyond this boundary.
1037 SmallVector<unsigned, 16> ResourceCounts;
1038
1039 // Cache the critical resources ID in this scheduled zone.
1040 unsigned CritResIdx;
1041
1042 // Is the scheduled region resource limited vs. latency limited.
1043 bool IsResourceLimited;
1044
1045 unsigned ExpectedCount;
1046
Andrew Trick3b87f622012-11-07 07:05:09 +00001047#ifndef NDEBUG
Andrew Trickb7e02892012-06-05 21:11:27 +00001048 // Remember the greatest min operand latency.
1049 unsigned MaxMinLatency;
Andrew Trick3b87f622012-11-07 07:05:09 +00001050#endif
1051
1052 void reset() {
1053 Available.clear();
1054 Pending.clear();
1055 CheckPending = false;
1056 NextSUs.clear();
1057 HazardRec = 0;
1058 CurrCycle = 0;
1059 IssueCount = 0;
1060 MinReadyCycle = UINT_MAX;
1061 ExpectedLatency = 0;
1062 ResourceCounts.resize(1);
1063 assert(!ResourceCounts[0] && "nonzero count for bad resource");
1064 CritResIdx = 0;
1065 IsResourceLimited = false;
1066 ExpectedCount = 0;
Andrew Trick3b87f622012-11-07 07:05:09 +00001067#ifndef NDEBUG
1068 MaxMinLatency = 0;
1069#endif
1070 // Reserve a zero-count for invalid CritResIdx.
1071 ResourceCounts.resize(1);
1072 }
Andrew Trickb7e02892012-06-05 21:11:27 +00001073
Andrew Trickf3234242012-05-24 22:11:12 +00001074 /// Pending queues extend the ready queues with the same ID and the
1075 /// PendingFlag set.
1076 SchedBoundary(unsigned ID, const Twine &Name):
Andrew Trick3b87f622012-11-07 07:05:09 +00001077 DAG(0), SchedModel(0), Rem(0), Available(ID, Name+".A"),
1078 Pending(ID << ConvergingScheduler::LogMaxQID, Name+".P") {
1079 reset();
1080 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001081
1082 ~SchedBoundary() { delete HazardRec; }
1083
Andrew Trick3b87f622012-11-07 07:05:09 +00001084 void init(ScheduleDAGMI *dag, const TargetSchedModel *smodel,
1085 SchedRemainder *rem);
Andrew Trick412cd2f2012-10-10 05:43:09 +00001086
Andrew Trickf3234242012-05-24 22:11:12 +00001087 bool isTop() const {
1088 return Available.getID() == ConvergingScheduler::TopQID;
1089 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001090
Andrew Trick3b87f622012-11-07 07:05:09 +00001091 unsigned getUnscheduledLatency(SUnit *SU) const {
1092 if (isTop())
1093 return SU->getHeight();
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001094 return SU->getDepth() + SU->Latency;
Andrew Trick3b87f622012-11-07 07:05:09 +00001095 }
1096
1097 unsigned getCriticalCount() const {
1098 return ResourceCounts[CritResIdx];
1099 }
1100
Andrew Trick5559ffa2012-06-29 03:23:24 +00001101 bool checkHazard(SUnit *SU);
1102
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001103 void setLatencyPolicy(CandPolicy &Policy);
Andrew Trick3b87f622012-11-07 07:05:09 +00001104
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001105 void releaseNode(SUnit *SU, unsigned ReadyCycle);
1106
1107 void bumpCycle();
1108
Andrew Trick3b87f622012-11-07 07:05:09 +00001109 void countResource(unsigned PIdx, unsigned Cycles);
1110
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001111 void bumpNode(SUnit *SU);
Andrew Trickb7e02892012-06-05 21:11:27 +00001112
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001113 void releasePending();
1114
1115 void removeReady(SUnit *SU);
1116
1117 SUnit *pickOnlyChoice();
1118 };
1119
Andrew Trick3b87f622012-11-07 07:05:09 +00001120private:
Andrew Trick17d35e52012-03-14 04:00:41 +00001121 ScheduleDAGMI *DAG;
Andrew Trick412cd2f2012-10-10 05:43:09 +00001122 const TargetSchedModel *SchedModel;
Andrew Trick7196a8f2012-05-10 21:06:16 +00001123 const TargetRegisterInfo *TRI;
Andrew Trick42b7a712012-01-17 06:55:03 +00001124
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001125 // State of the top and bottom scheduled instruction boundaries.
Andrew Trick3b87f622012-11-07 07:05:09 +00001126 SchedRemainder Rem;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001127 SchedBoundary Top;
1128 SchedBoundary Bot;
Andrew Trick17d35e52012-03-14 04:00:41 +00001129
1130public:
Andrew Trickf3234242012-05-24 22:11:12 +00001131 /// SUnit::NodeQueueId: 0 (none), 1 (top), 2 (bot), 3 (both)
Andrew Trick7196a8f2012-05-10 21:06:16 +00001132 enum {
1133 TopQID = 1,
Andrew Trickf3234242012-05-24 22:11:12 +00001134 BotQID = 2,
1135 LogMaxQID = 2
Andrew Trick7196a8f2012-05-10 21:06:16 +00001136 };
1137
Andrew Trickf3234242012-05-24 22:11:12 +00001138 ConvergingScheduler():
Andrew Trick412cd2f2012-10-10 05:43:09 +00001139 DAG(0), SchedModel(0), TRI(0), Top(TopQID, "TopQ"), Bot(BotQID, "BotQ") {}
Andrew Trickd38f87e2012-05-10 21:06:12 +00001140
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001141 virtual void initialize(ScheduleDAGMI *dag);
Andrew Trick17d35e52012-03-14 04:00:41 +00001142
Andrew Trick7196a8f2012-05-10 21:06:16 +00001143 virtual SUnit *pickNode(bool &IsTopNode);
Andrew Trick17d35e52012-03-14 04:00:41 +00001144
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001145 virtual void schedNode(SUnit *SU, bool IsTopNode);
1146
1147 virtual void releaseTopNode(SUnit *SU);
1148
1149 virtual void releaseBottomNode(SUnit *SU);
1150
Andrew Trick3b87f622012-11-07 07:05:09 +00001151 virtual void registerRoots();
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001152
Andrew Trick3b87f622012-11-07 07:05:09 +00001153protected:
1154 void balanceZones(
1155 ConvergingScheduler::SchedBoundary &CriticalZone,
1156 ConvergingScheduler::SchedCandidate &CriticalCand,
1157 ConvergingScheduler::SchedBoundary &OppositeZone,
1158 ConvergingScheduler::SchedCandidate &OppositeCand);
1159
1160 void checkResourceLimits(ConvergingScheduler::SchedCandidate &TopCand,
1161 ConvergingScheduler::SchedCandidate &BotCand);
1162
1163 void tryCandidate(SchedCandidate &Cand,
1164 SchedCandidate &TryCand,
1165 SchedBoundary &Zone,
1166 const RegPressureTracker &RPTracker,
1167 RegPressureTracker &TempTracker);
1168
1169 SUnit *pickNodeBidirectional(bool &IsTopNode);
1170
1171 void pickNodeFromQueue(SchedBoundary &Zone,
1172 const RegPressureTracker &RPTracker,
1173 SchedCandidate &Candidate);
1174
Andrew Trick28ebc892012-05-10 21:06:19 +00001175#ifndef NDEBUG
Andrew Trick3b87f622012-11-07 07:05:09 +00001176 void traceCandidate(const SchedCandidate &Cand, const SchedBoundary &Zone);
Andrew Trick28ebc892012-05-10 21:06:19 +00001177#endif
Andrew Trick42b7a712012-01-17 06:55:03 +00001178};
1179} // namespace
1180
Andrew Trick3b87f622012-11-07 07:05:09 +00001181void ConvergingScheduler::SchedRemainder::
1182init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
1183 reset();
1184 if (!SchedModel->hasInstrSchedModel())
1185 return;
1186 RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
1187 for (std::vector<SUnit>::iterator
1188 I = DAG->SUnits.begin(), E = DAG->SUnits.end(); I != E; ++I) {
1189 const MCSchedClassDesc *SC = DAG->getSchedClass(&*I);
1190 RemainingMicroOps += SchedModel->getNumMicroOps(I->getInstr(), SC);
1191 for (TargetSchedModel::ProcResIter
1192 PI = SchedModel->getWriteProcResBegin(SC),
1193 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1194 unsigned PIdx = PI->ProcResourceIdx;
1195 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1196 RemainingCounts[PIdx] += (Factor * PI->Cycles);
1197 }
1198 }
Andrew Trick071966f2012-12-18 20:52:49 +00001199 for (unsigned PIdx = 0, PEnd = SchedModel->getNumProcResourceKinds();
1200 PIdx != PEnd; ++PIdx) {
1201 if ((int)(RemainingCounts[PIdx] - RemainingCounts[CritResIdx])
1202 >= (int)SchedModel->getLatencyFactor()) {
1203 CritResIdx = PIdx;
1204 }
1205 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001206}
1207
1208void ConvergingScheduler::SchedBoundary::
1209init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
1210 reset();
1211 DAG = dag;
1212 SchedModel = smodel;
1213 Rem = rem;
1214 if (SchedModel->hasInstrSchedModel())
1215 ResourceCounts.resize(SchedModel->getNumProcResourceKinds());
1216}
1217
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001218void ConvergingScheduler::initialize(ScheduleDAGMI *dag) {
1219 DAG = dag;
Andrew Trick412cd2f2012-10-10 05:43:09 +00001220 SchedModel = DAG->getSchedModel();
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001221 TRI = DAG->TRI;
Andrew Trick3b87f622012-11-07 07:05:09 +00001222 Rem.init(DAG, SchedModel);
1223 Top.init(DAG, SchedModel, &Rem);
1224 Bot.init(DAG, SchedModel, &Rem);
1225
Andrew Trick4e1fb182013-01-25 06:33:57 +00001226 DAG->computeDFSResult();
Andrew Trick178f7d02013-01-25 04:01:04 +00001227
Andrew Trick3b87f622012-11-07 07:05:09 +00001228 // Initialize resource counts.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001229
Andrew Trick412cd2f2012-10-10 05:43:09 +00001230 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
1231 // are disabled, then these HazardRecs will be disabled.
1232 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001233 const TargetMachine &TM = DAG->MF.getTarget();
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001234 Top.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
1235 Bot.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
1236
1237 assert((!ForceTopDown || !ForceBottomUp) &&
1238 "-misched-topdown incompatible with -misched-bottomup");
1239}
1240
1241void ConvergingScheduler::releaseTopNode(SUnit *SU) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001242 if (SU->isScheduled)
1243 return;
1244
Andrew Trickd4539602012-12-18 20:52:52 +00001245 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
Andrew Trickb7e02892012-06-05 21:11:27 +00001246 I != E; ++I) {
1247 unsigned PredReadyCycle = I->getSUnit()->TopReadyCycle;
Andrew Trickffd25262012-08-23 00:39:43 +00001248 unsigned MinLatency = I->getMinLatency();
Andrew Trickb7e02892012-06-05 21:11:27 +00001249#ifndef NDEBUG
Andrew Trickffd25262012-08-23 00:39:43 +00001250 Top.MaxMinLatency = std::max(MinLatency, Top.MaxMinLatency);
Andrew Trickb7e02892012-06-05 21:11:27 +00001251#endif
Andrew Trickffd25262012-08-23 00:39:43 +00001252 if (SU->TopReadyCycle < PredReadyCycle + MinLatency)
1253 SU->TopReadyCycle = PredReadyCycle + MinLatency;
Andrew Trickb7e02892012-06-05 21:11:27 +00001254 }
1255 Top.releaseNode(SU, SU->TopReadyCycle);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001256}
1257
1258void ConvergingScheduler::releaseBottomNode(SUnit *SU) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001259 if (SU->isScheduled)
1260 return;
1261
1262 assert(SU->getInstr() && "Scheduled SUnit must have instr");
1263
1264 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1265 I != E; ++I) {
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001266 if (I->isWeak())
1267 continue;
Andrew Trickb7e02892012-06-05 21:11:27 +00001268 unsigned SuccReadyCycle = I->getSUnit()->BotReadyCycle;
Andrew Trickffd25262012-08-23 00:39:43 +00001269 unsigned MinLatency = I->getMinLatency();
Andrew Trickb7e02892012-06-05 21:11:27 +00001270#ifndef NDEBUG
Andrew Trickffd25262012-08-23 00:39:43 +00001271 Bot.MaxMinLatency = std::max(MinLatency, Bot.MaxMinLatency);
Andrew Trickb7e02892012-06-05 21:11:27 +00001272#endif
Andrew Trickffd25262012-08-23 00:39:43 +00001273 if (SU->BotReadyCycle < SuccReadyCycle + MinLatency)
1274 SU->BotReadyCycle = SuccReadyCycle + MinLatency;
Andrew Trickb7e02892012-06-05 21:11:27 +00001275 }
1276 Bot.releaseNode(SU, SU->BotReadyCycle);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001277}
1278
Andrew Trick3b87f622012-11-07 07:05:09 +00001279void ConvergingScheduler::registerRoots() {
1280 Rem.CriticalPath = DAG->ExitSU.getDepth();
1281 // Some roots may not feed into ExitSU. Check all of them in case.
1282 for (std::vector<SUnit*>::const_iterator
1283 I = Bot.Available.begin(), E = Bot.Available.end(); I != E; ++I) {
1284 if ((*I)->getDepth() > Rem.CriticalPath)
1285 Rem.CriticalPath = (*I)->getDepth();
1286 }
1287 DEBUG(dbgs() << "Critical Path: " << Rem.CriticalPath << '\n');
1288}
1289
Andrew Trick5559ffa2012-06-29 03:23:24 +00001290/// Does this SU have a hazard within the current instruction group.
1291///
1292/// The scheduler supports two modes of hazard recognition. The first is the
1293/// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
1294/// supports highly complicated in-order reservation tables
1295/// (ScoreboardHazardRecognizer) and arbitraty target-specific logic.
1296///
1297/// The second is a streamlined mechanism that checks for hazards based on
1298/// simple counters that the scheduler itself maintains. It explicitly checks
1299/// for instruction dispatch limitations, including the number of micro-ops that
1300/// can dispatch per cycle.
1301///
1302/// TODO: Also check whether the SU must start a new group.
1303bool ConvergingScheduler::SchedBoundary::checkHazard(SUnit *SU) {
1304 if (HazardRec->isEnabled())
1305 return HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard;
1306
Andrew Trick412cd2f2012-10-10 05:43:09 +00001307 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
Andrew Trick3b87f622012-11-07 07:05:09 +00001308 if ((IssueCount > 0) && (IssueCount + uops > SchedModel->getIssueWidth())) {
1309 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") uops="
1310 << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
Andrew Trick5559ffa2012-06-29 03:23:24 +00001311 return true;
Andrew Trick3b87f622012-11-07 07:05:09 +00001312 }
Andrew Trick5559ffa2012-06-29 03:23:24 +00001313 return false;
1314}
1315
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001316/// Compute the remaining latency to determine whether ILP should be increased.
1317void ConvergingScheduler::SchedBoundary::setLatencyPolicy(CandPolicy &Policy) {
1318 // FIXME: compile time. In all, we visit four queues here one we should only
1319 // need to visit the one that was last popped if we cache the result.
1320 unsigned RemLatency = 0;
1321 for (ReadyQueue::iterator I = Available.begin(), E = Available.end();
1322 I != E; ++I) {
1323 unsigned L = getUnscheduledLatency(*I);
1324 if (L > RemLatency)
1325 RemLatency = L;
1326 }
1327 for (ReadyQueue::iterator I = Pending.begin(), E = Pending.end();
1328 I != E; ++I) {
1329 unsigned L = getUnscheduledLatency(*I);
1330 if (L > RemLatency)
1331 RemLatency = L;
1332 }
Andrew Trick47579cf2013-01-09 03:36:49 +00001333 unsigned CriticalPathLimit = Rem->CriticalPath + SchedModel->getILPWindow();
1334 if (RemLatency + ExpectedLatency >= CriticalPathLimit
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001335 && RemLatency > Rem->getMaxRemainingCount(SchedModel)) {
1336 Policy.ReduceLatency = true;
1337 DEBUG(dbgs() << "Increase ILP: " << Available.getName() << '\n');
Andrew Trick3b87f622012-11-07 07:05:09 +00001338 }
1339}
1340
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001341void ConvergingScheduler::SchedBoundary::releaseNode(SUnit *SU,
1342 unsigned ReadyCycle) {
Andrew Trick3b87f622012-11-07 07:05:09 +00001343
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001344 if (ReadyCycle < MinReadyCycle)
1345 MinReadyCycle = ReadyCycle;
1346
1347 // Check for interlocks first. For the purpose of other heuristics, an
1348 // instruction that cannot issue appears as if it's not in the ReadyQueue.
Andrew Trick5559ffa2012-06-29 03:23:24 +00001349 if (ReadyCycle > CurrCycle || checkHazard(SU))
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001350 Pending.push(SU);
1351 else
1352 Available.push(SU);
Andrew Trick3b87f622012-11-07 07:05:09 +00001353
1354 // Record this node as an immediate dependent of the scheduled node.
1355 NextSUs.insert(SU);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001356}
1357
1358/// Move the boundary of scheduled code by one cycle.
1359void ConvergingScheduler::SchedBoundary::bumpCycle() {
Andrew Trick412cd2f2012-10-10 05:43:09 +00001360 unsigned Width = SchedModel->getIssueWidth();
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001361 IssueCount = (IssueCount <= Width) ? 0 : IssueCount - Width;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001362
Andrew Trick3b87f622012-11-07 07:05:09 +00001363 unsigned NextCycle = CurrCycle + 1;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001364 assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
Andrew Trick3b87f622012-11-07 07:05:09 +00001365 if (MinReadyCycle > NextCycle) {
1366 IssueCount = 0;
1367 NextCycle = MinReadyCycle;
1368 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001369
1370 if (!HazardRec->isEnabled()) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001371 // Bypass HazardRec virtual calls.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001372 CurrCycle = NextCycle;
1373 }
1374 else {
Andrew Trickb7e02892012-06-05 21:11:27 +00001375 // Bypass getHazardType calls in case of long latency.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001376 for (; CurrCycle != NextCycle; ++CurrCycle) {
1377 if (isTop())
1378 HazardRec->AdvanceCycle();
1379 else
1380 HazardRec->RecedeCycle();
1381 }
1382 }
1383 CheckPending = true;
Andrew Trick3b87f622012-11-07 07:05:09 +00001384 IsResourceLimited = getCriticalCount() > std::max(ExpectedLatency, CurrCycle);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001385
Andrew Trick3b87f622012-11-07 07:05:09 +00001386 DEBUG(dbgs() << " *** " << Available.getName() << " cycle "
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001387 << CurrCycle << '\n');
1388}
1389
Andrew Trick3b87f622012-11-07 07:05:09 +00001390/// Add the given processor resource to this scheduled zone.
1391void ConvergingScheduler::SchedBoundary::countResource(unsigned PIdx,
1392 unsigned Cycles) {
1393 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1394 DEBUG(dbgs() << " " << SchedModel->getProcResource(PIdx)->Name
1395 << " +(" << Cycles << "x" << Factor
1396 << ") / " << SchedModel->getLatencyFactor() << '\n');
1397
1398 unsigned Count = Factor * Cycles;
1399 ResourceCounts[PIdx] += Count;
1400 assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
1401 Rem->RemainingCounts[PIdx] -= Count;
1402
Andrew Trick3b87f622012-11-07 07:05:09 +00001403 // Check if this resource exceeds the current critical resource by a full
1404 // cycle. If so, it becomes the critical resource.
1405 if ((int)(ResourceCounts[PIdx] - ResourceCounts[CritResIdx])
1406 >= (int)SchedModel->getLatencyFactor()) {
1407 CritResIdx = PIdx;
1408 DEBUG(dbgs() << " *** Critical resource "
1409 << SchedModel->getProcResource(PIdx)->Name << " x"
1410 << ResourceCounts[PIdx] << '\n');
1411 }
1412}
1413
Andrew Trickb7e02892012-06-05 21:11:27 +00001414/// Move the boundary of scheduled code by one SUnit.
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001415void ConvergingScheduler::SchedBoundary::bumpNode(SUnit *SU) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001416 // Update the reservation table.
1417 if (HazardRec->isEnabled()) {
1418 if (!isTop() && SU->isCall) {
1419 // Calls are scheduled with their preceding instructions. For bottom-up
1420 // scheduling, clear the pipeline state before emitting.
1421 HazardRec->Reset();
1422 }
1423 HazardRec->EmitInstruction(SU);
1424 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001425 // Update resource counts and critical resource.
1426 if (SchedModel->hasInstrSchedModel()) {
1427 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1428 Rem->RemainingMicroOps -= SchedModel->getNumMicroOps(SU->getInstr(), SC);
1429 for (TargetSchedModel::ProcResIter
1430 PI = SchedModel->getWriteProcResBegin(SC),
1431 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1432 countResource(PI->ProcResourceIdx, PI->Cycles);
1433 }
1434 }
1435 if (isTop()) {
1436 if (SU->getDepth() > ExpectedLatency)
1437 ExpectedLatency = SU->getDepth();
1438 }
1439 else {
1440 if (SU->getHeight() > ExpectedLatency)
1441 ExpectedLatency = SU->getHeight();
1442 }
1443
1444 IsResourceLimited = getCriticalCount() > std::max(ExpectedLatency, CurrCycle);
1445
Andrew Trick5559ffa2012-06-29 03:23:24 +00001446 // Check the instruction group dispatch limit.
1447 // TODO: Check if this SU must end a dispatch group.
Andrew Trick412cd2f2012-10-10 05:43:09 +00001448 IssueCount += SchedModel->getNumMicroOps(SU->getInstr());
Andrew Trick3b87f622012-11-07 07:05:09 +00001449
1450 // checkHazard prevents scheduling multiple instructions per cycle that exceed
1451 // issue width. However, we commonly reach the maximum. In this case
1452 // opportunistically bump the cycle to avoid uselessly checking everything in
1453 // the readyQ. Furthermore, a single instruction may produce more than one
1454 // cycle's worth of micro-ops.
Andrew Trick412cd2f2012-10-10 05:43:09 +00001455 if (IssueCount >= SchedModel->getIssueWidth()) {
Andrew Trick3b87f622012-11-07 07:05:09 +00001456 DEBUG(dbgs() << " *** Max instrs at cycle " << CurrCycle << '\n');
Andrew Trickb7e02892012-06-05 21:11:27 +00001457 bumpCycle();
1458 }
1459}
1460
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001461/// Release pending ready nodes in to the available queue. This makes them
1462/// visible to heuristics.
1463void ConvergingScheduler::SchedBoundary::releasePending() {
1464 // If the available queue is empty, it is safe to reset MinReadyCycle.
1465 if (Available.empty())
1466 MinReadyCycle = UINT_MAX;
1467
1468 // Check to see if any of the pending instructions are ready to issue. If
1469 // so, add them to the available queue.
1470 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
1471 SUnit *SU = *(Pending.begin()+i);
Andrew Trickb7e02892012-06-05 21:11:27 +00001472 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001473
1474 if (ReadyCycle < MinReadyCycle)
1475 MinReadyCycle = ReadyCycle;
1476
1477 if (ReadyCycle > CurrCycle)
1478 continue;
1479
Andrew Trick5559ffa2012-06-29 03:23:24 +00001480 if (checkHazard(SU))
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001481 continue;
1482
1483 Available.push(SU);
1484 Pending.remove(Pending.begin()+i);
1485 --i; --e;
1486 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001487 DEBUG(if (!Pending.empty()) Pending.dump());
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001488 CheckPending = false;
1489}
1490
1491/// Remove SU from the ready set for this boundary.
1492void ConvergingScheduler::SchedBoundary::removeReady(SUnit *SU) {
1493 if (Available.isInQueue(SU))
1494 Available.remove(Available.find(SU));
1495 else {
1496 assert(Pending.isInQueue(SU) && "bad ready count");
1497 Pending.remove(Pending.find(SU));
1498 }
1499}
1500
1501/// If this queue only has one ready candidate, return it. As a side effect,
Andrew Trick3b87f622012-11-07 07:05:09 +00001502/// defer any nodes that now hit a hazard, and advance the cycle until at least
1503/// one node is ready. If multiple instructions are ready, return NULL.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001504SUnit *ConvergingScheduler::SchedBoundary::pickOnlyChoice() {
1505 if (CheckPending)
1506 releasePending();
1507
Andrew Trick3b87f622012-11-07 07:05:09 +00001508 if (IssueCount > 0) {
1509 // Defer any ready instrs that now have a hazard.
1510 for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
1511 if (checkHazard(*I)) {
1512 Pending.push(*I);
1513 I = Available.remove(I);
1514 continue;
1515 }
1516 ++I;
1517 }
1518 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001519 for (unsigned i = 0; Available.empty(); ++i) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001520 assert(i <= (HazardRec->getMaxLookAhead() + MaxMinLatency) &&
1521 "permanent hazard"); (void)i;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001522 bumpCycle();
1523 releasePending();
1524 }
1525 if (Available.size() == 1)
1526 return *Available.begin();
1527 return NULL;
1528}
1529
Andrew Trick3b87f622012-11-07 07:05:09 +00001530/// Record the candidate policy for opposite zones with different critical
1531/// resources.
1532///
1533/// If the CriticalZone is latency limited, don't force a policy for the
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001534/// candidates here. Instead, setLatencyPolicy sets ReduceLatency if needed.
Andrew Trick3b87f622012-11-07 07:05:09 +00001535void ConvergingScheduler::balanceZones(
1536 ConvergingScheduler::SchedBoundary &CriticalZone,
1537 ConvergingScheduler::SchedCandidate &CriticalCand,
1538 ConvergingScheduler::SchedBoundary &OppositeZone,
1539 ConvergingScheduler::SchedCandidate &OppositeCand) {
1540
1541 if (!CriticalZone.IsResourceLimited)
1542 return;
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001543 assert(SchedModel->hasInstrSchedModel() && "required schedmodel");
Andrew Trick3b87f622012-11-07 07:05:09 +00001544
1545 SchedRemainder *Rem = CriticalZone.Rem;
1546
1547 // If the critical zone is overconsuming a resource relative to the
1548 // remainder, try to reduce it.
1549 unsigned RemainingCritCount =
1550 Rem->RemainingCounts[CriticalZone.CritResIdx];
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001551 if ((int)(Rem->getMaxRemainingCount(SchedModel) - RemainingCritCount)
Andrew Trick3b87f622012-11-07 07:05:09 +00001552 > (int)SchedModel->getLatencyFactor()) {
1553 CriticalCand.Policy.ReduceResIdx = CriticalZone.CritResIdx;
1554 DEBUG(dbgs() << "Balance " << CriticalZone.Available.getName() << " reduce "
1555 << SchedModel->getProcResource(CriticalZone.CritResIdx)->Name
1556 << '\n');
1557 }
1558 // If the other zone is underconsuming a resource relative to the full zone,
1559 // try to increase it.
1560 unsigned OppositeCount =
1561 OppositeZone.ResourceCounts[CriticalZone.CritResIdx];
1562 if ((int)(OppositeZone.ExpectedCount - OppositeCount)
1563 > (int)SchedModel->getLatencyFactor()) {
1564 OppositeCand.Policy.DemandResIdx = CriticalZone.CritResIdx;
1565 DEBUG(dbgs() << "Balance " << OppositeZone.Available.getName() << " demand "
1566 << SchedModel->getProcResource(OppositeZone.CritResIdx)->Name
1567 << '\n');
1568 }
Andrew Trick28ebc892012-05-10 21:06:19 +00001569}
Andrew Trick3b87f622012-11-07 07:05:09 +00001570
1571/// Determine if the scheduled zones exceed resource limits or critical path and
1572/// set each candidate's ReduceHeight policy accordingly.
1573void ConvergingScheduler::checkResourceLimits(
1574 ConvergingScheduler::SchedCandidate &TopCand,
1575 ConvergingScheduler::SchedCandidate &BotCand) {
1576
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001577 // Set ReduceLatency to true if needed.
Andrew Trickeed4e012013-01-11 17:51:16 +00001578 Bot.setLatencyPolicy(BotCand.Policy);
1579 Top.setLatencyPolicy(TopCand.Policy);
Andrew Trick3b87f622012-11-07 07:05:09 +00001580
1581 // Handle resource-limited regions.
1582 if (Top.IsResourceLimited && Bot.IsResourceLimited
1583 && Top.CritResIdx == Bot.CritResIdx) {
1584 // If the scheduled critical resource in both zones is no longer the
1585 // critical remaining resource, attempt to reduce resource height both ways.
1586 if (Top.CritResIdx != Rem.CritResIdx) {
1587 TopCand.Policy.ReduceResIdx = Top.CritResIdx;
1588 BotCand.Policy.ReduceResIdx = Bot.CritResIdx;
1589 DEBUG(dbgs() << "Reduce scheduled "
1590 << SchedModel->getProcResource(Top.CritResIdx)->Name << '\n');
1591 }
1592 return;
1593 }
1594 // Handle latency-limited regions.
1595 if (!Top.IsResourceLimited && !Bot.IsResourceLimited) {
1596 // If the total scheduled expected latency exceeds the region's critical
1597 // path then reduce latency both ways.
1598 //
1599 // Just because a zone is not resource limited does not mean it is latency
1600 // limited. Unbuffered resource, such as max micro-ops may cause CurrCycle
1601 // to exceed expected latency.
1602 if ((Top.ExpectedLatency + Bot.ExpectedLatency >= Rem.CriticalPath)
1603 && (Rem.CriticalPath > Top.CurrCycle + Bot.CurrCycle)) {
1604 TopCand.Policy.ReduceLatency = true;
1605 BotCand.Policy.ReduceLatency = true;
1606 DEBUG(dbgs() << "Reduce scheduled latency " << Top.ExpectedLatency
1607 << " + " << Bot.ExpectedLatency << '\n');
1608 }
1609 return;
1610 }
1611 // The critical resource is different in each zone, so request balancing.
1612
1613 // Compute the cost of each zone.
Andrew Trick3b87f622012-11-07 07:05:09 +00001614 Top.ExpectedCount = std::max(Top.ExpectedLatency, Top.CurrCycle);
1615 Top.ExpectedCount = std::max(
1616 Top.getCriticalCount(),
1617 Top.ExpectedCount * SchedModel->getLatencyFactor());
1618 Bot.ExpectedCount = std::max(Bot.ExpectedLatency, Bot.CurrCycle);
1619 Bot.ExpectedCount = std::max(
1620 Bot.getCriticalCount(),
1621 Bot.ExpectedCount * SchedModel->getLatencyFactor());
1622
1623 balanceZones(Top, TopCand, Bot, BotCand);
1624 balanceZones(Bot, BotCand, Top, TopCand);
1625}
1626
1627void ConvergingScheduler::SchedCandidate::
1628initResourceDelta(const ScheduleDAGMI *DAG,
1629 const TargetSchedModel *SchedModel) {
1630 if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
1631 return;
1632
1633 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1634 for (TargetSchedModel::ProcResIter
1635 PI = SchedModel->getWriteProcResBegin(SC),
1636 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1637 if (PI->ProcResourceIdx == Policy.ReduceResIdx)
1638 ResDelta.CritResources += PI->Cycles;
1639 if (PI->ProcResourceIdx == Policy.DemandResIdx)
1640 ResDelta.DemandedResources += PI->Cycles;
1641 }
1642}
1643
1644/// Return true if this heuristic determines order.
1645static bool tryLess(unsigned TryVal, unsigned CandVal,
1646 ConvergingScheduler::SchedCandidate &TryCand,
1647 ConvergingScheduler::SchedCandidate &Cand,
1648 ConvergingScheduler::CandReason Reason) {
1649 if (TryVal < CandVal) {
1650 TryCand.Reason = Reason;
1651 return true;
1652 }
1653 if (TryVal > CandVal) {
1654 if (Cand.Reason > Reason)
1655 Cand.Reason = Reason;
1656 return true;
1657 }
1658 return false;
1659}
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001660
Andrew Trick3b87f622012-11-07 07:05:09 +00001661static bool tryGreater(unsigned TryVal, unsigned CandVal,
1662 ConvergingScheduler::SchedCandidate &TryCand,
1663 ConvergingScheduler::SchedCandidate &Cand,
1664 ConvergingScheduler::CandReason Reason) {
1665 if (TryVal > CandVal) {
1666 TryCand.Reason = Reason;
1667 return true;
1668 }
1669 if (TryVal < CandVal) {
1670 if (Cand.Reason > Reason)
1671 Cand.Reason = Reason;
1672 return true;
1673 }
1674 return false;
1675}
1676
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001677static unsigned getWeakLeft(const SUnit *SU, bool isTop) {
1678 return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
1679}
1680
Andrew Trick3b87f622012-11-07 07:05:09 +00001681/// Apply a set of heursitics to a new candidate. Heuristics are currently
1682/// hierarchical. This may be more efficient than a graduated cost model because
1683/// we don't need to evaluate all aspects of the model for each node in the
1684/// queue. But it's really done to make the heuristics easier to debug and
1685/// statistically analyze.
1686///
1687/// \param Cand provides the policy and current best candidate.
1688/// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
1689/// \param Zone describes the scheduled zone that we are extending.
1690/// \param RPTracker describes reg pressure within the scheduled zone.
1691/// \param TempTracker is a scratch pressure tracker to reuse in queries.
1692void ConvergingScheduler::tryCandidate(SchedCandidate &Cand,
1693 SchedCandidate &TryCand,
1694 SchedBoundary &Zone,
1695 const RegPressureTracker &RPTracker,
1696 RegPressureTracker &TempTracker) {
1697
1698 // Always initialize TryCand's RPDelta.
1699 TempTracker.getMaxPressureDelta(TryCand.SU->getInstr(), TryCand.RPDelta,
1700 DAG->getRegionCriticalPSets(),
1701 DAG->getRegPressure().MaxSetPressure);
1702
1703 // Initialize the candidate if needed.
1704 if (!Cand.isValid()) {
1705 TryCand.Reason = NodeOrder;
1706 return;
1707 }
1708 // Avoid exceeding the target's limit.
1709 if (tryLess(TryCand.RPDelta.Excess.UnitIncrease,
1710 Cand.RPDelta.Excess.UnitIncrease, TryCand, Cand, SingleExcess))
1711 return;
1712 if (Cand.Reason == SingleExcess)
1713 Cand.Reason = MultiPressure;
1714
1715 // Avoid increasing the max critical pressure in the scheduled region.
1716 if (tryLess(TryCand.RPDelta.CriticalMax.UnitIncrease,
1717 Cand.RPDelta.CriticalMax.UnitIncrease,
1718 TryCand, Cand, SingleCritical))
1719 return;
1720 if (Cand.Reason == SingleCritical)
1721 Cand.Reason = MultiPressure;
1722
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001723 // Keep clustered nodes together to encourage downstream peephole
1724 // optimizations which may reduce resource requirements.
1725 //
1726 // This is a best effort to set things up for a post-RA pass. Optimizations
1727 // like generating loads of multiple registers should ideally be done within
1728 // the scheduler pass by combining the loads during DAG postprocessing.
1729 const SUnit *NextClusterSU =
1730 Zone.isTop() ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
1731 if (tryGreater(TryCand.SU == NextClusterSU, Cand.SU == NextClusterSU,
1732 TryCand, Cand, Cluster))
1733 return;
1734 // Currently, weak edges are for clustering, so we hard-code that reason.
1735 // However, deferring the current TryCand will not change Cand's reason.
1736 CandReason OrigReason = Cand.Reason;
1737 if (tryLess(getWeakLeft(TryCand.SU, Zone.isTop()),
1738 getWeakLeft(Cand.SU, Zone.isTop()),
1739 TryCand, Cand, Cluster)) {
1740 Cand.Reason = OrigReason;
1741 return;
1742 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001743 // Avoid critical resource consumption and balance the schedule.
1744 TryCand.initResourceDelta(DAG, SchedModel);
1745 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
1746 TryCand, Cand, ResourceReduce))
1747 return;
1748 if (tryGreater(TryCand.ResDelta.DemandedResources,
1749 Cand.ResDelta.DemandedResources,
1750 TryCand, Cand, ResourceDemand))
1751 return;
1752
1753 // Avoid serializing long latency dependence chains.
1754 if (Cand.Policy.ReduceLatency) {
1755 if (Zone.isTop()) {
1756 if (Cand.SU->getDepth() * SchedModel->getLatencyFactor()
1757 > Zone.ExpectedCount) {
1758 if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
1759 TryCand, Cand, TopDepthReduce))
1760 return;
1761 }
1762 if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
1763 TryCand, Cand, TopPathReduce))
1764 return;
1765 }
1766 else {
1767 if (Cand.SU->getHeight() * SchedModel->getLatencyFactor()
1768 > Zone.ExpectedCount) {
1769 if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
1770 TryCand, Cand, BotHeightReduce))
1771 return;
1772 }
1773 if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
1774 TryCand, Cand, BotPathReduce))
1775 return;
1776 }
1777 }
1778
1779 // Avoid increasing the max pressure of the entire region.
1780 if (tryLess(TryCand.RPDelta.CurrentMax.UnitIncrease,
1781 Cand.RPDelta.CurrentMax.UnitIncrease, TryCand, Cand, SingleMax))
1782 return;
1783 if (Cand.Reason == SingleMax)
1784 Cand.Reason = MultiPressure;
1785
1786 // Prefer immediate defs/users of the last scheduled instruction. This is a
1787 // nice pressure avoidance strategy that also conserves the processor's
1788 // register renaming resources and keeps the machine code readable.
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001789 if (tryGreater(Zone.NextSUs.count(TryCand.SU), Zone.NextSUs.count(Cand.SU),
1790 TryCand, Cand, NextDefUse))
Andrew Trick3b87f622012-11-07 07:05:09 +00001791 return;
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001792
Andrew Trick3b87f622012-11-07 07:05:09 +00001793 // Fall through to original instruction order.
1794 if ((Zone.isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
1795 || (!Zone.isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
1796 TryCand.Reason = NodeOrder;
1797 }
1798}
Andrew Trick28ebc892012-05-10 21:06:19 +00001799
Andrew Trick5429a6b2012-05-17 22:37:09 +00001800/// pickNodeFromQueue helper that returns true if the LHS reg pressure effect is
1801/// more desirable than RHS from scheduling standpoint.
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001802static bool compareRPDelta(const RegPressureDelta &LHS,
1803 const RegPressureDelta &RHS) {
1804 // Compare each component of pressure in decreasing order of importance
1805 // without checking if any are valid. Invalid PressureElements are assumed to
1806 // have UnitIncrease==0, so are neutral.
Andrew Trickc8fe4ec2012-05-24 22:11:01 +00001807
1808 // Avoid increasing the max critical pressure in the scheduled region.
Andrew Trick3b87f622012-11-07 07:05:09 +00001809 if (LHS.Excess.UnitIncrease != RHS.Excess.UnitIncrease) {
1810 DEBUG(dbgs() << "RP excess top - bot: "
1811 << (LHS.Excess.UnitIncrease - RHS.Excess.UnitIncrease) << '\n');
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001812 return LHS.Excess.UnitIncrease < RHS.Excess.UnitIncrease;
Andrew Trick3b87f622012-11-07 07:05:09 +00001813 }
Andrew Trickc8fe4ec2012-05-24 22:11:01 +00001814 // Avoid increasing the max critical pressure in the scheduled region.
Andrew Trick3b87f622012-11-07 07:05:09 +00001815 if (LHS.CriticalMax.UnitIncrease != RHS.CriticalMax.UnitIncrease) {
1816 DEBUG(dbgs() << "RP critical top - bot: "
1817 << (LHS.CriticalMax.UnitIncrease - RHS.CriticalMax.UnitIncrease)
1818 << '\n');
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001819 return LHS.CriticalMax.UnitIncrease < RHS.CriticalMax.UnitIncrease;
Andrew Trick3b87f622012-11-07 07:05:09 +00001820 }
Andrew Trickc8fe4ec2012-05-24 22:11:01 +00001821 // Avoid increasing the max pressure of the entire region.
Andrew Trick3b87f622012-11-07 07:05:09 +00001822 if (LHS.CurrentMax.UnitIncrease != RHS.CurrentMax.UnitIncrease) {
1823 DEBUG(dbgs() << "RP current top - bot: "
1824 << (LHS.CurrentMax.UnitIncrease - RHS.CurrentMax.UnitIncrease)
1825 << '\n');
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001826 return LHS.CurrentMax.UnitIncrease < RHS.CurrentMax.UnitIncrease;
Andrew Trick3b87f622012-11-07 07:05:09 +00001827 }
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001828 return false;
1829}
1830
Andrew Trick3b87f622012-11-07 07:05:09 +00001831#ifndef NDEBUG
1832const char *ConvergingScheduler::getReasonStr(
1833 ConvergingScheduler::CandReason Reason) {
1834 switch (Reason) {
1835 case NoCand: return "NOCAND ";
1836 case SingleExcess: return "REG-EXCESS";
1837 case SingleCritical: return "REG-CRIT ";
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001838 case Cluster: return "CLUSTER ";
Andrew Trick3b87f622012-11-07 07:05:09 +00001839 case SingleMax: return "REG-MAX ";
1840 case MultiPressure: return "REG-MULTI ";
1841 case ResourceReduce: return "RES-REDUCE";
1842 case ResourceDemand: return "RES-DEMAND";
1843 case TopDepthReduce: return "TOP-DEPTH ";
1844 case TopPathReduce: return "TOP-PATH ";
1845 case BotHeightReduce:return "BOT-HEIGHT";
1846 case BotPathReduce: return "BOT-PATH ";
1847 case NextDefUse: return "DEF-USE ";
1848 case NodeOrder: return "ORDER ";
1849 };
Benjamin Kramerb7546872012-11-09 15:45:22 +00001850 llvm_unreachable("Unknown reason!");
Andrew Trick3b87f622012-11-07 07:05:09 +00001851}
1852
1853void ConvergingScheduler::traceCandidate(const SchedCandidate &Cand,
1854 const SchedBoundary &Zone) {
1855 const char *Label = getReasonStr(Cand.Reason);
1856 PressureElement P;
1857 unsigned ResIdx = 0;
1858 unsigned Latency = 0;
1859 switch (Cand.Reason) {
1860 default:
1861 break;
1862 case SingleExcess:
1863 P = Cand.RPDelta.Excess;
1864 break;
1865 case SingleCritical:
1866 P = Cand.RPDelta.CriticalMax;
1867 break;
1868 case SingleMax:
1869 P = Cand.RPDelta.CurrentMax;
1870 break;
1871 case ResourceReduce:
1872 ResIdx = Cand.Policy.ReduceResIdx;
1873 break;
1874 case ResourceDemand:
1875 ResIdx = Cand.Policy.DemandResIdx;
1876 break;
1877 case TopDepthReduce:
1878 Latency = Cand.SU->getDepth();
1879 break;
1880 case TopPathReduce:
1881 Latency = Cand.SU->getHeight();
1882 break;
1883 case BotHeightReduce:
1884 Latency = Cand.SU->getHeight();
1885 break;
1886 case BotPathReduce:
1887 Latency = Cand.SU->getDepth();
1888 break;
1889 }
1890 dbgs() << Label << " " << Zone.Available.getName() << " ";
1891 if (P.isValid())
1892 dbgs() << TRI->getRegPressureSetName(P.PSetID) << ":" << P.UnitIncrease
1893 << " ";
1894 else
1895 dbgs() << " ";
1896 if (ResIdx)
1897 dbgs() << SchedModel->getProcResource(ResIdx)->Name << " ";
1898 else
1899 dbgs() << " ";
1900 if (Latency)
1901 dbgs() << Latency << " cycles ";
1902 else
1903 dbgs() << " ";
1904 Cand.SU->dump(DAG);
1905}
1906#endif
1907
Andrew Trick7196a8f2012-05-10 21:06:16 +00001908/// Pick the best candidate from the top queue.
1909///
1910/// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
1911/// DAG building. To adjust for the current scheduling location we need to
1912/// maintain the number of vreg uses remaining to be top-scheduled.
Andrew Trick3b87f622012-11-07 07:05:09 +00001913void ConvergingScheduler::pickNodeFromQueue(SchedBoundary &Zone,
1914 const RegPressureTracker &RPTracker,
1915 SchedCandidate &Cand) {
1916 ReadyQueue &Q = Zone.Available;
1917
Andrew Trickf3234242012-05-24 22:11:12 +00001918 DEBUG(Q.dump());
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001919
Andrew Trick7196a8f2012-05-10 21:06:16 +00001920 // getMaxPressureDelta temporarily modifies the tracker.
1921 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
1922
Andrew Trick8c2d9212012-05-24 22:11:03 +00001923 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
Andrew Trick7196a8f2012-05-10 21:06:16 +00001924
Andrew Trick3b87f622012-11-07 07:05:09 +00001925 SchedCandidate TryCand(Cand.Policy);
1926 TryCand.SU = *I;
1927 tryCandidate(Cand, TryCand, Zone, RPTracker, TempTracker);
1928 if (TryCand.Reason != NoCand) {
1929 // Initialize resource delta if needed in case future heuristics query it.
1930 if (TryCand.ResDelta == SchedResourceDelta())
1931 TryCand.initResourceDelta(DAG, SchedModel);
1932 Cand.setBest(TryCand);
1933 DEBUG(traceCandidate(Cand, Zone));
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001934 }
Andrew Trick7196a8f2012-05-10 21:06:16 +00001935 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001936}
1937
1938static void tracePick(const ConvergingScheduler::SchedCandidate &Cand,
1939 bool IsTop) {
1940 DEBUG(dbgs() << "Pick " << (IsTop ? "top" : "bot")
1941 << " SU(" << Cand.SU->NodeNum << ") "
1942 << ConvergingScheduler::getReasonStr(Cand.Reason) << '\n');
Andrew Trick7196a8f2012-05-10 21:06:16 +00001943}
1944
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001945/// Pick the best candidate node from either the top or bottom queue.
Andrew Trick3b87f622012-11-07 07:05:09 +00001946SUnit *ConvergingScheduler::pickNodeBidirectional(bool &IsTopNode) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001947 // Schedule as far as possible in the direction of no choice. This is most
1948 // efficient, but also provides the best heuristics for CriticalPSets.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001949 if (SUnit *SU = Bot.pickOnlyChoice()) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001950 IsTopNode = false;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001951 return SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001952 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001953 if (SUnit *SU = Top.pickOnlyChoice()) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001954 IsTopNode = true;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001955 return SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001956 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001957 CandPolicy NoPolicy;
1958 SchedCandidate BotCand(NoPolicy);
1959 SchedCandidate TopCand(NoPolicy);
1960 checkResourceLimits(TopCand, BotCand);
1961
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001962 // Prefer bottom scheduling when heuristics are silent.
Andrew Trick3b87f622012-11-07 07:05:09 +00001963 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
1964 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001965
1966 // If either Q has a single candidate that provides the least increase in
1967 // Excess pressure, we can immediately schedule from that Q.
1968 //
1969 // RegionCriticalPSets summarizes the pressure within the scheduled region and
1970 // affects picking from either Q. If scheduling in one direction must
1971 // increase pressure for one of the excess PSets, then schedule in that
1972 // direction first to provide more freedom in the other direction.
Andrew Trick3b87f622012-11-07 07:05:09 +00001973 if (BotCand.Reason == SingleExcess || BotCand.Reason == SingleCritical) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001974 IsTopNode = false;
Andrew Trick3b87f622012-11-07 07:05:09 +00001975 tracePick(BotCand, IsTopNode);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001976 return BotCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001977 }
1978 // Check if the top Q has a better candidate.
Andrew Trick3b87f622012-11-07 07:05:09 +00001979 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
1980 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001981
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001982 // If either Q has a single candidate that minimizes pressure above the
1983 // original region's pressure pick it.
Andrew Trick3b87f622012-11-07 07:05:09 +00001984 if (TopCand.Reason <= SingleMax || BotCand.Reason <= SingleMax) {
1985 if (TopCand.Reason < BotCand.Reason) {
1986 IsTopNode = true;
1987 tracePick(TopCand, IsTopNode);
1988 return TopCand.SU;
1989 }
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001990 IsTopNode = false;
Andrew Trick3b87f622012-11-07 07:05:09 +00001991 tracePick(BotCand, IsTopNode);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001992 return BotCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001993 }
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001994 // Check for a salient pressure difference and pick the best from either side.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001995 if (compareRPDelta(TopCand.RPDelta, BotCand.RPDelta)) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001996 IsTopNode = true;
Andrew Trick3b87f622012-11-07 07:05:09 +00001997 tracePick(TopCand, IsTopNode);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001998 return TopCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001999 }
Andrew Trick3b87f622012-11-07 07:05:09 +00002000 // Otherwise prefer the bottom candidate, in node order if all else failed.
2001 if (TopCand.Reason < BotCand.Reason) {
2002 IsTopNode = true;
2003 tracePick(TopCand, IsTopNode);
2004 return TopCand.SU;
2005 }
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002006 IsTopNode = false;
Andrew Trick3b87f622012-11-07 07:05:09 +00002007 tracePick(BotCand, IsTopNode);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002008 return BotCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002009}
2010
2011/// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
Andrew Trick7196a8f2012-05-10 21:06:16 +00002012SUnit *ConvergingScheduler::pickNode(bool &IsTopNode) {
2013 if (DAG->top() == DAG->bottom()) {
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002014 assert(Top.Available.empty() && Top.Pending.empty() &&
2015 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
Andrew Trick7196a8f2012-05-10 21:06:16 +00002016 return NULL;
2017 }
Andrew Trick7196a8f2012-05-10 21:06:16 +00002018 SUnit *SU;
Andrew Trick30c6ec22012-10-08 18:53:53 +00002019 do {
2020 if (ForceTopDown) {
2021 SU = Top.pickOnlyChoice();
2022 if (!SU) {
Andrew Trick3b87f622012-11-07 07:05:09 +00002023 CandPolicy NoPolicy;
2024 SchedCandidate TopCand(NoPolicy);
2025 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
2026 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick30c6ec22012-10-08 18:53:53 +00002027 SU = TopCand.SU;
2028 }
2029 IsTopNode = true;
Andrew Trick8ddd9d52012-05-24 23:11:17 +00002030 }
Andrew Trick30c6ec22012-10-08 18:53:53 +00002031 else if (ForceBottomUp) {
2032 SU = Bot.pickOnlyChoice();
2033 if (!SU) {
Andrew Trick3b87f622012-11-07 07:05:09 +00002034 CandPolicy NoPolicy;
2035 SchedCandidate BotCand(NoPolicy);
2036 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
2037 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick30c6ec22012-10-08 18:53:53 +00002038 SU = BotCand.SU;
2039 }
2040 IsTopNode = false;
Andrew Trick8ddd9d52012-05-24 23:11:17 +00002041 }
Andrew Trick30c6ec22012-10-08 18:53:53 +00002042 else {
Andrew Trick3b87f622012-11-07 07:05:09 +00002043 SU = pickNodeBidirectional(IsTopNode);
Andrew Trick30c6ec22012-10-08 18:53:53 +00002044 }
2045 } while (SU->isScheduled);
2046
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002047 if (SU->isTopReady())
2048 Top.removeReady(SU);
2049 if (SU->isBottomReady())
2050 Bot.removeReady(SU);
Andrew Trickc7a098f2012-05-25 02:02:39 +00002051
2052 DEBUG(dbgs() << "*** " << (IsTopNode ? "Top" : "Bottom")
2053 << " Scheduling Instruction in cycle "
2054 << (IsTopNode ? Top.CurrCycle : Bot.CurrCycle) << '\n';
2055 SU->dump(DAG));
Andrew Trick7196a8f2012-05-10 21:06:16 +00002056 return SU;
2057}
2058
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002059/// Update the scheduler's state after scheduling a node. This is the same node
2060/// that was just returned by pickNode(). However, ScheduleDAGMI needs to update
Andrew Trickb7e02892012-06-05 21:11:27 +00002061/// it's state based on the current cycle before MachineSchedStrategy does.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002062void ConvergingScheduler::schedNode(SUnit *SU, bool IsTopNode) {
Andrew Trickb7e02892012-06-05 21:11:27 +00002063 if (IsTopNode) {
2064 SU->TopReadyCycle = Top.CurrCycle;
Andrew Trick7f8c74c2012-06-29 03:23:22 +00002065 Top.bumpNode(SU);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002066 }
Andrew Trickb7e02892012-06-05 21:11:27 +00002067 else {
2068 SU->BotReadyCycle = Bot.CurrCycle;
Andrew Trick7f8c74c2012-06-29 03:23:22 +00002069 Bot.bumpNode(SU);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002070 }
2071}
2072
Andrew Trick17d35e52012-03-14 04:00:41 +00002073/// Create the standard converging machine scheduler. This will be used as the
2074/// default scheduler if the target does not set a default.
2075static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C) {
Benjamin Kramer689e0b42012-03-14 11:26:37 +00002076 assert((!ForceTopDown || !ForceBottomUp) &&
Andrew Trick17d35e52012-03-14 04:00:41 +00002077 "-misched-topdown incompatible with -misched-bottomup");
Andrew Trick9b5caaa2012-11-12 19:40:10 +00002078 ScheduleDAGMI *DAG = new ScheduleDAGMI(C, new ConvergingScheduler());
2079 // Register DAG post-processors.
2080 if (EnableLoadCluster)
2081 DAG->addMutation(new LoadClusterMutation(DAG->TII, DAG->TRI));
Andrew Trick6996fd02012-11-12 19:52:20 +00002082 if (EnableMacroFusion)
2083 DAG->addMutation(new MacroFusion(DAG->TII));
Andrew Trick9b5caaa2012-11-12 19:40:10 +00002084 return DAG;
Andrew Trick42b7a712012-01-17 06:55:03 +00002085}
2086static MachineSchedRegistry
Andrew Trick17d35e52012-03-14 04:00:41 +00002087ConvergingSchedRegistry("converge", "Standard converging scheduler.",
2088 createConvergingSched);
Andrew Trick42b7a712012-01-17 06:55:03 +00002089
2090//===----------------------------------------------------------------------===//
Andrew Trick1e94e982012-10-15 18:02:27 +00002091// ILP Scheduler. Currently for experimental analysis of heuristics.
2092//===----------------------------------------------------------------------===//
2093
2094namespace {
2095/// \brief Order nodes by the ILP metric.
2096struct ILPOrder {
Andrew Trick178f7d02013-01-25 04:01:04 +00002097 const SchedDFSResult *DFSResult;
2098 const BitVector *ScheduledTrees;
Andrew Trick1e94e982012-10-15 18:02:27 +00002099 bool MaximizeILP;
2100
Andrew Trick178f7d02013-01-25 04:01:04 +00002101 ILPOrder(bool MaxILP): DFSResult(0), ScheduledTrees(0), MaximizeILP(MaxILP) {}
Andrew Trick1e94e982012-10-15 18:02:27 +00002102
2103 /// \brief Apply a less-than relation on node priority.
Andrew Trick8b1496c2012-11-28 05:13:28 +00002104 ///
2105 /// (Return true if A comes after B in the Q.)
Andrew Trick1e94e982012-10-15 18:02:27 +00002106 bool operator()(const SUnit *A, const SUnit *B) const {
Andrew Trick8b1496c2012-11-28 05:13:28 +00002107 unsigned SchedTreeA = DFSResult->getSubtreeID(A);
2108 unsigned SchedTreeB = DFSResult->getSubtreeID(B);
2109 if (SchedTreeA != SchedTreeB) {
2110 // Unscheduled trees have lower priority.
2111 if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
2112 return ScheduledTrees->test(SchedTreeB);
2113
2114 // Trees with shallower connections have have lower priority.
2115 if (DFSResult->getSubtreeLevel(SchedTreeA)
2116 != DFSResult->getSubtreeLevel(SchedTreeB)) {
2117 return DFSResult->getSubtreeLevel(SchedTreeA)
2118 < DFSResult->getSubtreeLevel(SchedTreeB);
2119 }
2120 }
Andrew Trick1e94e982012-10-15 18:02:27 +00002121 if (MaximizeILP)
Andrew Trick8b1496c2012-11-28 05:13:28 +00002122 return DFSResult->getILP(A) < DFSResult->getILP(B);
Andrew Trick1e94e982012-10-15 18:02:27 +00002123 else
Andrew Trick8b1496c2012-11-28 05:13:28 +00002124 return DFSResult->getILP(A) > DFSResult->getILP(B);
Andrew Trick1e94e982012-10-15 18:02:27 +00002125 }
2126};
2127
2128/// \brief Schedule based on the ILP metric.
2129class ILPScheduler : public MachineSchedStrategy {
Andrew Trick8b1496c2012-11-28 05:13:28 +00002130 /// In case all subtrees are eventually connected to a common root through
2131 /// data dependence (e.g. reduction), place an upper limit on their size.
2132 ///
2133 /// FIXME: A subtree limit is generally good, but in the situation commented
2134 /// above, where multiple similar subtrees feed a common root, we should
2135 /// only split at a point where the resulting subtrees will be balanced.
2136 /// (a motivating test case must be found).
2137 static const unsigned SubtreeLimit = 16;
2138
Andrew Trick178f7d02013-01-25 04:01:04 +00002139 ScheduleDAGMI *DAG;
Andrew Trick1e94e982012-10-15 18:02:27 +00002140 ILPOrder Cmp;
2141
2142 std::vector<SUnit*> ReadyQ;
2143public:
Andrew Trick178f7d02013-01-25 04:01:04 +00002144 ILPScheduler(bool MaximizeILP): DAG(0), Cmp(MaximizeILP) {}
Andrew Trick1e94e982012-10-15 18:02:27 +00002145
Andrew Trick178f7d02013-01-25 04:01:04 +00002146 virtual void initialize(ScheduleDAGMI *dag) {
2147 DAG = dag;
Andrew Trick4e1fb182013-01-25 06:33:57 +00002148 DAG->computeDFSResult();
Andrew Trick178f7d02013-01-25 04:01:04 +00002149 Cmp.DFSResult = DAG->getDFSResult();
2150 Cmp.ScheduledTrees = &DAG->getScheduledTrees();
Andrew Trick1e94e982012-10-15 18:02:27 +00002151 ReadyQ.clear();
Andrew Trick1e94e982012-10-15 18:02:27 +00002152 }
2153
2154 virtual void registerRoots() {
Benjamin Kramer5175fd92012-11-29 14:36:26 +00002155 // Restore the heap in ReadyQ with the updated DFS results.
2156 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
Andrew Trick1e94e982012-10-15 18:02:27 +00002157 }
2158
2159 /// Implement MachineSchedStrategy interface.
2160 /// -----------------------------------------
2161
Andrew Trick8b1496c2012-11-28 05:13:28 +00002162 /// Callback to select the highest priority node from the ready Q.
Andrew Trick1e94e982012-10-15 18:02:27 +00002163 virtual SUnit *pickNode(bool &IsTopNode) {
2164 if (ReadyQ.empty()) return NULL;
2165 pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2166 SUnit *SU = ReadyQ.back();
2167 ReadyQ.pop_back();
2168 IsTopNode = false;
Andrew Trick8b1496c2012-11-28 05:13:28 +00002169 DEBUG(dbgs() << "*** Scheduling " << "SU(" << SU->NodeNum << "): "
2170 << *SU->getInstr()
Andrew Trick178f7d02013-01-25 04:01:04 +00002171 << " ILP: " << DAG->getDFSResult()->getILP(SU)
2172 << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU) << " @"
2173 << DAG->getDFSResult()->getSubtreeLevel(
2174 DAG->getDFSResult()->getSubtreeID(SU)) << '\n');
Andrew Trick1e94e982012-10-15 18:02:27 +00002175 return SU;
2176 }
2177
Andrew Trick178f7d02013-01-25 04:01:04 +00002178 /// \brief Scheduler callback to notify that a new subtree is scheduled.
2179 virtual void scheduleTree(unsigned SubtreeID) {
2180 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2181 }
2182
Andrew Trick8b1496c2012-11-28 05:13:28 +00002183 /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
2184 /// DFSResults, and resort the priority Q.
2185 virtual void schedNode(SUnit *SU, bool IsTopNode) {
2186 assert(!IsTopNode && "SchedDFSResult needs bottom-up");
Andrew Trick8b1496c2012-11-28 05:13:28 +00002187 }
Andrew Trick1e94e982012-10-15 18:02:27 +00002188
2189 virtual void releaseTopNode(SUnit *) { /*only called for top roots*/ }
2190
2191 virtual void releaseBottomNode(SUnit *SU) {
2192 ReadyQ.push_back(SU);
2193 std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2194 }
2195};
2196} // namespace
2197
2198static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
2199 return new ScheduleDAGMI(C, new ILPScheduler(true));
2200}
2201static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
2202 return new ScheduleDAGMI(C, new ILPScheduler(false));
2203}
2204static MachineSchedRegistry ILPMaxRegistry(
2205 "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
2206static MachineSchedRegistry ILPMinRegistry(
2207 "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
2208
2209//===----------------------------------------------------------------------===//
Andrew Trick5edf2f02012-01-14 02:17:06 +00002210// Machine Instruction Shuffler for Correctness Testing
2211//===----------------------------------------------------------------------===//
2212
Andrew Trick96f678f2012-01-13 06:30:30 +00002213#ifndef NDEBUG
2214namespace {
Andrew Trick17d35e52012-03-14 04:00:41 +00002215/// Apply a less-than relation on the node order, which corresponds to the
2216/// instruction order prior to scheduling. IsReverse implements greater-than.
2217template<bool IsReverse>
2218struct SUnitOrder {
Andrew Trickc6cf11b2012-01-17 06:55:07 +00002219 bool operator()(SUnit *A, SUnit *B) const {
Andrew Trick17d35e52012-03-14 04:00:41 +00002220 if (IsReverse)
2221 return A->NodeNum > B->NodeNum;
2222 else
2223 return A->NodeNum < B->NodeNum;
Andrew Trickc6cf11b2012-01-17 06:55:07 +00002224 }
2225};
2226
Andrew Trick96f678f2012-01-13 06:30:30 +00002227/// Reorder instructions as much as possible.
Andrew Trick17d35e52012-03-14 04:00:41 +00002228class InstructionShuffler : public MachineSchedStrategy {
2229 bool IsAlternating;
2230 bool IsTopDown;
2231
2232 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
2233 // gives nodes with a higher number higher priority causing the latest
2234 // instructions to be scheduled first.
2235 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
2236 TopQ;
2237 // When scheduling bottom-up, use greater-than as the queue priority.
2238 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
2239 BottomQ;
Andrew Trick96f678f2012-01-13 06:30:30 +00002240public:
Andrew Trick17d35e52012-03-14 04:00:41 +00002241 InstructionShuffler(bool alternate, bool topdown)
2242 : IsAlternating(alternate), IsTopDown(topdown) {}
Andrew Trick96f678f2012-01-13 06:30:30 +00002243
Andrew Trick17d35e52012-03-14 04:00:41 +00002244 virtual void initialize(ScheduleDAGMI *) {
2245 TopQ.clear();
2246 BottomQ.clear();
2247 }
Andrew Trickc6cf11b2012-01-17 06:55:07 +00002248
Andrew Trick17d35e52012-03-14 04:00:41 +00002249 /// Implement MachineSchedStrategy interface.
2250 /// -----------------------------------------
2251
2252 virtual SUnit *pickNode(bool &IsTopNode) {
2253 SUnit *SU;
2254 if (IsTopDown) {
2255 do {
2256 if (TopQ.empty()) return NULL;
2257 SU = TopQ.top();
2258 TopQ.pop();
2259 } while (SU->isScheduled);
2260 IsTopNode = true;
2261 }
2262 else {
2263 do {
2264 if (BottomQ.empty()) return NULL;
2265 SU = BottomQ.top();
2266 BottomQ.pop();
2267 } while (SU->isScheduled);
2268 IsTopNode = false;
2269 }
2270 if (IsAlternating)
2271 IsTopDown = !IsTopDown;
Andrew Trickc6cf11b2012-01-17 06:55:07 +00002272 return SU;
2273 }
2274
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002275 virtual void schedNode(SUnit *SU, bool IsTopNode) {}
2276
Andrew Trick17d35e52012-03-14 04:00:41 +00002277 virtual void releaseTopNode(SUnit *SU) {
2278 TopQ.push(SU);
2279 }
2280 virtual void releaseBottomNode(SUnit *SU) {
2281 BottomQ.push(SU);
Andrew Trick96f678f2012-01-13 06:30:30 +00002282 }
2283};
2284} // namespace
2285
Andrew Trickc174eaf2012-03-08 01:41:12 +00002286static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
Andrew Trick17d35e52012-03-14 04:00:41 +00002287 bool Alternate = !ForceTopDown && !ForceBottomUp;
2288 bool TopDown = !ForceBottomUp;
Benjamin Kramer689e0b42012-03-14 11:26:37 +00002289 assert((TopDown || !ForceTopDown) &&
Andrew Trick17d35e52012-03-14 04:00:41 +00002290 "-misched-topdown incompatible with -misched-bottomup");
2291 return new ScheduleDAGMI(C, new InstructionShuffler(Alternate, TopDown));
Andrew Trick96f678f2012-01-13 06:30:30 +00002292}
Andrew Trick17d35e52012-03-14 04:00:41 +00002293static MachineSchedRegistry ShufflerRegistry(
2294 "shuffle", "Shuffle machine instructions alternating directions",
2295 createInstructionShuffler);
Andrew Trick96f678f2012-01-13 06:30:30 +00002296#endif // !NDEBUG