blob: 589fa1fa02958696b45d4b7ac22ab68931c609b0 [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"
Andrew Trick30849792013-01-25 07:45:29 +000029#include "llvm/Support/GraphWriter.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000030#include "llvm/Support/raw_ostream.h"
Andrew Trickc6cf11b2012-01-17 06:55:07 +000031#include <queue>
32
Andrew Trick96f678f2012-01-13 06:30:30 +000033using namespace llvm;
34
Andrew Trick78e5efe2012-09-11 00:39:15 +000035namespace llvm {
36cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
37 cl::desc("Force top-down list scheduling"));
38cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
39 cl::desc("Force bottom-up list scheduling"));
40}
Andrew Trick17d35e52012-03-14 04:00:41 +000041
Andrew Trick0df7f882012-03-07 00:18:25 +000042#ifndef NDEBUG
43static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
44 cl::desc("Pop up a window to show MISched dags after they are processed"));
Lang Hames23f1cbb2012-03-19 18:38:38 +000045
46static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
47 cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
Andrew Trick0df7f882012-03-07 00:18:25 +000048#else
49static bool ViewMISchedDAGs = false;
50#endif // NDEBUG
51
Andrew Trick9b5caaa2012-11-12 19:40:10 +000052// Experimental heuristics
53static cl::opt<bool> EnableLoadCluster("misched-cluster", cl::Hidden,
Andrew Trickad1cc1d2012-11-13 08:47:29 +000054 cl::desc("Enable load clustering."), cl::init(true));
Andrew Trick9b5caaa2012-11-12 19:40:10 +000055
Andrew Trick6996fd02012-11-12 19:52:20 +000056// Experimental heuristics
57static cl::opt<bool> EnableMacroFusion("misched-fusion", cl::Hidden,
Andrew Trickad1cc1d2012-11-13 08:47:29 +000058 cl::desc("Enable scheduling for macro fusion."), cl::init(true));
Andrew Trick6996fd02012-11-12 19:52:20 +000059
Andrew Trick178f7d02013-01-25 04:01:04 +000060// DAG subtrees must have at least this many nodes.
61static const unsigned MinSubtreeSize = 8;
62
Andrew Trick5edf2f02012-01-14 02:17:06 +000063//===----------------------------------------------------------------------===//
64// Machine Instruction Scheduling Pass and Registry
65//===----------------------------------------------------------------------===//
66
Andrew Trick86b7e2a2012-04-24 20:36:19 +000067MachineSchedContext::MachineSchedContext():
68 MF(0), MLI(0), MDT(0), PassConfig(0), AA(0), LIS(0) {
69 RegClassInfo = new RegisterClassInfo();
70}
71
72MachineSchedContext::~MachineSchedContext() {
73 delete RegClassInfo;
74}
75
Andrew Trick96f678f2012-01-13 06:30:30 +000076namespace {
Andrew Trick42b7a712012-01-17 06:55:03 +000077/// MachineScheduler runs after coalescing and before register allocation.
Andrew Trickc174eaf2012-03-08 01:41:12 +000078class MachineScheduler : public MachineSchedContext,
79 public MachineFunctionPass {
Andrew Trick96f678f2012-01-13 06:30:30 +000080public:
Andrew Trick42b7a712012-01-17 06:55:03 +000081 MachineScheduler();
Andrew Trick96f678f2012-01-13 06:30:30 +000082
83 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
84
85 virtual void releaseMemory() {}
86
87 virtual bool runOnMachineFunction(MachineFunction&);
88
89 virtual void print(raw_ostream &O, const Module* = 0) const;
90
91 static char ID; // Class identification, replacement for typeinfo
92};
93} // namespace
94
Andrew Trick42b7a712012-01-17 06:55:03 +000095char MachineScheduler::ID = 0;
Andrew Trick96f678f2012-01-13 06:30:30 +000096
Andrew Trick42b7a712012-01-17 06:55:03 +000097char &llvm::MachineSchedulerID = MachineScheduler::ID;
Andrew Trick96f678f2012-01-13 06:30:30 +000098
Andrew Trick42b7a712012-01-17 06:55:03 +000099INITIALIZE_PASS_BEGIN(MachineScheduler, "misched",
Andrew Trick96f678f2012-01-13 06:30:30 +0000100 "Machine Instruction Scheduler", false, false)
101INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
102INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
103INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
Andrew Trick42b7a712012-01-17 06:55:03 +0000104INITIALIZE_PASS_END(MachineScheduler, "misched",
Andrew Trick96f678f2012-01-13 06:30:30 +0000105 "Machine Instruction Scheduler", false, false)
106
Andrew Trick42b7a712012-01-17 06:55:03 +0000107MachineScheduler::MachineScheduler()
Andrew Trickc174eaf2012-03-08 01:41:12 +0000108: MachineFunctionPass(ID) {
Andrew Trick42b7a712012-01-17 06:55:03 +0000109 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Andrew Trick96f678f2012-01-13 06:30:30 +0000110}
111
Andrew Trick42b7a712012-01-17 06:55:03 +0000112void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
Andrew Trick96f678f2012-01-13 06:30:30 +0000113 AU.setPreservesCFG();
114 AU.addRequiredID(MachineDominatorsID);
115 AU.addRequired<MachineLoopInfo>();
116 AU.addRequired<AliasAnalysis>();
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000117 AU.addRequired<TargetPassConfig>();
Andrew Trick96f678f2012-01-13 06:30:30 +0000118 AU.addRequired<SlotIndexes>();
119 AU.addPreserved<SlotIndexes>();
120 AU.addRequired<LiveIntervals>();
121 AU.addPreserved<LiveIntervals>();
Andrew Trick96f678f2012-01-13 06:30:30 +0000122 MachineFunctionPass::getAnalysisUsage(AU);
123}
124
Andrew Trick96f678f2012-01-13 06:30:30 +0000125MachinePassRegistry MachineSchedRegistry::Registry;
126
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000127/// A dummy default scheduler factory indicates whether the scheduler
128/// is overridden on the command line.
129static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
130 return 0;
131}
Andrew Trick96f678f2012-01-13 06:30:30 +0000132
133/// MachineSchedOpt allows command line selection of the scheduler.
134static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
135 RegisterPassParser<MachineSchedRegistry> >
136MachineSchedOpt("misched",
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000137 cl::init(&useDefaultMachineSched), cl::Hidden,
Andrew Trick96f678f2012-01-13 06:30:30 +0000138 cl::desc("Machine instruction scheduler to use"));
139
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000140static MachineSchedRegistry
Andrew Trick17d35e52012-03-14 04:00:41 +0000141DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000142 useDefaultMachineSched);
143
Andrew Trick17d35e52012-03-14 04:00:41 +0000144/// Forward declare the standard machine scheduler. This will be used as the
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000145/// default scheduler if the target does not set a default.
Andrew Trick17d35e52012-03-14 04:00:41 +0000146static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C);
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000147
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000148
149/// Decrement this iterator until reaching the top or a non-debug instr.
150static MachineBasicBlock::iterator
151priorNonDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator Beg) {
152 assert(I != Beg && "reached the top of the region, cannot decrement");
153 while (--I != Beg) {
154 if (!I->isDebugValue())
155 break;
156 }
157 return I;
158}
159
160/// If this iterator is a debug value, increment until reaching the End or a
161/// non-debug instruction.
162static MachineBasicBlock::iterator
163nextIfDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator End) {
Andrew Trick811d92682012-05-17 18:35:03 +0000164 for(; I != End; ++I) {
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000165 if (!I->isDebugValue())
166 break;
167 }
168 return I;
169}
170
Andrew Trickcb058d52012-03-14 04:00:38 +0000171/// Top-level MachineScheduler pass driver.
172///
173/// Visit blocks in function order. Divide each block into scheduling regions
Andrew Trick17d35e52012-03-14 04:00:41 +0000174/// and visit them bottom-up. Visiting regions bottom-up is not required, but is
175/// consistent with the DAG builder, which traverses the interior of the
176/// scheduling regions bottom-up.
Andrew Trickcb058d52012-03-14 04:00:38 +0000177///
178/// This design avoids exposing scheduling boundaries to the DAG builder,
Andrew Trick17d35e52012-03-14 04:00:41 +0000179/// simplifying the DAG builder's support for "special" target instructions.
180/// At the same time the design allows target schedulers to operate across
Andrew Trickcb058d52012-03-14 04:00:38 +0000181/// scheduling boundaries, for example to bundle the boudary instructions
182/// without reordering them. This creates complexity, because the target
183/// scheduler must update the RegionBegin and RegionEnd positions cached by
184/// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
185/// design would be to split blocks at scheduling boundaries, but LLVM has a
186/// general bias against block splitting purely for implementation simplicity.
Andrew Trick42b7a712012-01-17 06:55:03 +0000187bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
Andrew Trick89c324b2012-05-10 21:06:21 +0000188 DEBUG(dbgs() << "Before MISsched:\n"; mf.print(dbgs()));
189
Andrew Trick96f678f2012-01-13 06:30:30 +0000190 // Initialize the context of the pass.
191 MF = &mf;
192 MLI = &getAnalysis<MachineLoopInfo>();
193 MDT = &getAnalysis<MachineDominatorTree>();
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000194 PassConfig = &getAnalysis<TargetPassConfig>();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000195 AA = &getAnalysis<AliasAnalysis>();
196
Lang Hames907cc8f2012-01-27 22:36:19 +0000197 LIS = &getAnalysis<LiveIntervals>();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000198 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
Andrew Trick96f678f2012-01-13 06:30:30 +0000199
Andrew Trick86b7e2a2012-04-24 20:36:19 +0000200 RegClassInfo->runOnMachineFunction(*MF);
Andrew Trick006e1ab2012-04-24 17:56:43 +0000201
Andrew Trick96f678f2012-01-13 06:30:30 +0000202 // Select the scheduler, or set the default.
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000203 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
204 if (Ctor == useDefaultMachineSched) {
205 // Get the default scheduler set by the target.
206 Ctor = MachineSchedRegistry::getDefault();
207 if (!Ctor) {
Andrew Trick17d35e52012-03-14 04:00:41 +0000208 Ctor = createConvergingSched;
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000209 MachineSchedRegistry::setDefault(Ctor);
210 }
Andrew Trick96f678f2012-01-13 06:30:30 +0000211 }
212 // Instantiate the selected scheduler.
213 OwningPtr<ScheduleDAGInstrs> Scheduler(Ctor(this));
214
215 // Visit all machine basic blocks.
Andrew Trick006e1ab2012-04-24 17:56:43 +0000216 //
217 // TODO: Visit blocks in global postorder or postorder within the bottom-up
218 // loop tree. Then we can optionally compute global RegPressure.
Andrew Trick96f678f2012-01-13 06:30:30 +0000219 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
220 MBB != MBBEnd; ++MBB) {
221
Andrew Trick1fabd9f2012-03-09 08:02:51 +0000222 Scheduler->startBlock(MBB);
223
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000224 // Break the block into scheduling regions [I, RegionEnd), and schedule each
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +0000225 // region as soon as it is discovered. RegionEnd points the scheduling
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000226 // boundary at the bottom of the region. The DAG does not include RegionEnd,
227 // but the region does (i.e. the next RegionEnd is above the previous
228 // RegionBegin). If the current block has no terminator then RegionEnd ==
229 // MBB->end() for the bottom region.
230 //
231 // The Scheduler may insert instructions during either schedule() or
232 // exitRegion(), even for empty regions. So the local iterators 'I' and
233 // 'RegionEnd' are invalid across these calls.
Andrew Trick22764532012-11-06 07:10:34 +0000234 unsigned RemainingInstrs = MBB->size();
Andrew Trick7799eb42012-03-09 03:46:39 +0000235 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000236 RegionEnd != MBB->begin(); RegionEnd = Scheduler->begin()) {
Andrew Trick006e1ab2012-04-24 17:56:43 +0000237
Andrew Trick1fabd9f2012-03-09 08:02:51 +0000238 // Avoid decrementing RegionEnd for blocks with no terminator.
239 if (RegionEnd != MBB->end()
240 || TII->isSchedulingBoundary(llvm::prior(RegionEnd), MBB, *MF)) {
241 --RegionEnd;
242 // Count the boundary instruction.
Andrew Trick22764532012-11-06 07:10:34 +0000243 --RemainingInstrs;
Andrew Trick1fabd9f2012-03-09 08:02:51 +0000244 }
245
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000246 // The next region starts above the previous region. Look backward in the
247 // instruction stream until we find the nearest boundary.
248 MachineBasicBlock::iterator I = RegionEnd;
Andrew Trick22764532012-11-06 07:10:34 +0000249 for(;I != MBB->begin(); --I, --RemainingInstrs) {
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000250 if (TII->isSchedulingBoundary(llvm::prior(I), MBB, *MF))
251 break;
252 }
Andrew Trick47c14452012-03-07 05:21:52 +0000253 // Notify the scheduler of the region, even if we may skip scheduling
254 // it. Perhaps it still needs to be bundled.
Andrew Trick22764532012-11-06 07:10:34 +0000255 Scheduler->enterRegion(MBB, I, RegionEnd, RemainingInstrs);
Andrew Trick47c14452012-03-07 05:21:52 +0000256
257 // Skip empty scheduling regions (0 or 1 schedulable instructions).
258 if (I == RegionEnd || I == llvm::prior(RegionEnd)) {
Andrew Trick47c14452012-03-07 05:21:52 +0000259 // Close the current region. Bundle the terminator if needed.
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000260 // This invalidates 'RegionEnd' and 'I'.
Andrew Trick47c14452012-03-07 05:21:52 +0000261 Scheduler->exitRegion();
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000262 continue;
Andrew Trick3c58ba82012-01-14 02:17:18 +0000263 }
Andrew Trickbb0a2422012-05-24 22:11:14 +0000264 DEBUG(dbgs() << "********** MI Scheduling **********\n");
Craig Topper96601ca2012-08-22 06:07:19 +0000265 DEBUG(dbgs() << MF->getName()
Andrew Trickc8554232013-01-25 07:45:31 +0000266 << ":BB#" << MBB->getNumber() << " " << MBB->getName()
267 << "\n From: " << *I << " To: ";
Andrew Trick291411c2012-02-08 02:17:21 +0000268 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
269 else dbgs() << "End";
Andrew Trick22764532012-11-06 07:10:34 +0000270 dbgs() << " Remaining: " << RemainingInstrs << "\n");
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000271
Andrew Trickd24da972012-03-09 03:46:42 +0000272 // Schedule a region: possibly reorder instructions.
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000273 // This invalidates 'RegionEnd' and 'I'.
Andrew Trick953be892012-03-07 23:00:49 +0000274 Scheduler->schedule();
Andrew Trickd24da972012-03-09 03:46:42 +0000275
276 // Close the current region.
Andrew Trick47c14452012-03-07 05:21:52 +0000277 Scheduler->exitRegion();
278
279 // Scheduling has invalidated the current iterator 'I'. Ask the
280 // scheduler for the top of it's scheduled region.
281 RegionEnd = Scheduler->begin();
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000282 }
Andrew Trick22764532012-11-06 07:10:34 +0000283 assert(RemainingInstrs == 0 && "Instruction count mismatch!");
Andrew Trick953be892012-03-07 23:00:49 +0000284 Scheduler->finishBlock();
Andrew Trick96f678f2012-01-13 06:30:30 +0000285 }
Andrew Trick830da402012-04-01 07:24:23 +0000286 Scheduler->finalizeSchedule();
Andrew Trickaad37f12012-03-21 04:12:12 +0000287 DEBUG(LIS->print(dbgs()));
Andrew Trick96f678f2012-01-13 06:30:30 +0000288 return true;
289}
290
Andrew Trick42b7a712012-01-17 06:55:03 +0000291void MachineScheduler::print(raw_ostream &O, const Module* m) const {
Andrew Trick96f678f2012-01-13 06:30:30 +0000292 // unimplemented
293}
294
Manman Renb720be62012-09-11 22:23:19 +0000295#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Andrew Trick78e5efe2012-09-11 00:39:15 +0000296void ReadyQueue::dump() {
297 dbgs() << Name << ": ";
298 for (unsigned i = 0, e = Queue.size(); i < e; ++i)
299 dbgs() << Queue[i]->NodeNum << " ";
300 dbgs() << "\n";
301}
302#endif
Andrew Trick17d35e52012-03-14 04:00:41 +0000303
304//===----------------------------------------------------------------------===//
305// ScheduleDAGMI - Base class for MachineInstr scheduling with LiveIntervals
306// preservation.
307//===----------------------------------------------------------------------===//
308
Andrew Trick178f7d02013-01-25 04:01:04 +0000309ScheduleDAGMI::~ScheduleDAGMI() {
310 delete DFSResult;
311 DeleteContainerPointers(Mutations);
312 delete SchedImpl;
313}
314
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000315bool ScheduleDAGMI::addEdge(SUnit *SuccSU, const SDep &PredDep) {
Andrew Trick6996fd02012-11-12 19:52:20 +0000316 if (SuccSU != &ExitSU) {
317 // Do not use WillCreateCycle, it assumes SD scheduling.
318 // If Pred is reachable from Succ, then the edge creates a cycle.
319 if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
320 return false;
321 Topo.AddPred(SuccSU, PredDep.getSUnit());
322 }
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000323 SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
324 // Return true regardless of whether a new edge needed to be inserted.
325 return true;
326}
327
Andrew Trickc174eaf2012-03-08 01:41:12 +0000328/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
329/// NumPredsLeft reaches zero, release the successor node.
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000330///
331/// FIXME: Adjust SuccSU height based on MinLatency.
Andrew Trick17d35e52012-03-14 04:00:41 +0000332void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
Andrew Trickc174eaf2012-03-08 01:41:12 +0000333 SUnit *SuccSU = SuccEdge->getSUnit();
334
Andrew Trickae692f22012-11-12 19:28:57 +0000335 if (SuccEdge->isWeak()) {
336 --SuccSU->WeakPredsLeft;
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000337 if (SuccEdge->isCluster())
338 NextClusterSucc = SuccSU;
Andrew Trickae692f22012-11-12 19:28:57 +0000339 return;
340 }
Andrew Trickc174eaf2012-03-08 01:41:12 +0000341#ifndef NDEBUG
342 if (SuccSU->NumPredsLeft == 0) {
343 dbgs() << "*** Scheduling failed! ***\n";
344 SuccSU->dump(this);
345 dbgs() << " has been released too many times!\n";
346 llvm_unreachable(0);
347 }
348#endif
349 --SuccSU->NumPredsLeft;
350 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
Andrew Trick17d35e52012-03-14 04:00:41 +0000351 SchedImpl->releaseTopNode(SuccSU);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000352}
353
354/// releaseSuccessors - Call releaseSucc on each of SU's successors.
Andrew Trick17d35e52012-03-14 04:00:41 +0000355void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
Andrew Trickc174eaf2012-03-08 01:41:12 +0000356 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
357 I != E; ++I) {
358 releaseSucc(SU, &*I);
359 }
360}
361
Andrew Trick17d35e52012-03-14 04:00:41 +0000362/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
363/// NumSuccsLeft reaches zero, release the predecessor node.
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000364///
365/// FIXME: Adjust PredSU height based on MinLatency.
Andrew Trick17d35e52012-03-14 04:00:41 +0000366void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
367 SUnit *PredSU = PredEdge->getSUnit();
368
Andrew Trickae692f22012-11-12 19:28:57 +0000369 if (PredEdge->isWeak()) {
370 --PredSU->WeakSuccsLeft;
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000371 if (PredEdge->isCluster())
372 NextClusterPred = PredSU;
Andrew Trickae692f22012-11-12 19:28:57 +0000373 return;
374 }
Andrew Trick17d35e52012-03-14 04:00:41 +0000375#ifndef NDEBUG
376 if (PredSU->NumSuccsLeft == 0) {
377 dbgs() << "*** Scheduling failed! ***\n";
378 PredSU->dump(this);
379 dbgs() << " has been released too many times!\n";
380 llvm_unreachable(0);
381 }
382#endif
383 --PredSU->NumSuccsLeft;
384 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
385 SchedImpl->releaseBottomNode(PredSU);
386}
387
388/// releasePredecessors - Call releasePred on each of SU's predecessors.
389void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
390 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
391 I != E; ++I) {
392 releasePred(SU, &*I);
393 }
394}
395
396void ScheduleDAGMI::moveInstruction(MachineInstr *MI,
397 MachineBasicBlock::iterator InsertPos) {
Andrew Trick811d92682012-05-17 18:35:03 +0000398 // Advance RegionBegin if the first instruction moves down.
Andrew Trick1ce062f2012-03-21 04:12:10 +0000399 if (&*RegionBegin == MI)
Andrew Trick811d92682012-05-17 18:35:03 +0000400 ++RegionBegin;
401
402 // Update the instruction stream.
Andrew Trick17d35e52012-03-14 04:00:41 +0000403 BB->splice(InsertPos, BB, MI);
Andrew Trick811d92682012-05-17 18:35:03 +0000404
405 // Update LiveIntervals
Andrew Trick27c28ce2012-10-16 00:22:51 +0000406 LIS->handleMove(MI, /*UpdateFlags=*/true);
Andrew Trick811d92682012-05-17 18:35:03 +0000407
408 // Recede RegionBegin if an instruction moves above the first.
Andrew Trick17d35e52012-03-14 04:00:41 +0000409 if (RegionBegin == InsertPos)
410 RegionBegin = MI;
411}
412
Andrew Trick0b0d8992012-03-21 04:12:07 +0000413bool ScheduleDAGMI::checkSchedLimit() {
414#ifndef NDEBUG
415 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
416 CurrentTop = CurrentBottom;
417 return false;
418 }
419 ++NumInstrsScheduled;
420#endif
421 return true;
422}
423
Andrew Trick006e1ab2012-04-24 17:56:43 +0000424/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
425/// crossing a scheduling boundary. [begin, end) includes all instructions in
426/// the region, including the boundary itself and single-instruction regions
427/// that don't get scheduled.
428void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
429 MachineBasicBlock::iterator begin,
430 MachineBasicBlock::iterator end,
431 unsigned endcount)
432{
433 ScheduleDAGInstrs::enterRegion(bb, begin, end, endcount);
Andrew Trick7f8ab782012-05-10 21:06:10 +0000434
435 // For convenience remember the end of the liveness region.
436 LiveRegionEnd =
437 (RegionEnd == bb->end()) ? RegionEnd : llvm::next(RegionEnd);
438}
439
440// Setup the register pressure trackers for the top scheduled top and bottom
441// scheduled regions.
442void ScheduleDAGMI::initRegPressure() {
443 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin);
444 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
445
446 // Close the RPTracker to finalize live ins.
447 RPTracker.closeRegion();
448
Andrew Trickbb0a2422012-05-24 22:11:14 +0000449 DEBUG(RPTracker.getPressure().dump(TRI));
450
Andrew Trick7f8ab782012-05-10 21:06:10 +0000451 // Initialize the live ins and live outs.
452 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
453 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
454
455 // Close one end of the tracker so we can call
456 // getMaxUpward/DownwardPressureDelta before advancing across any
457 // instructions. This converts currently live regs into live ins/outs.
458 TopRPTracker.closeTop();
459 BotRPTracker.closeBottom();
460
461 // Account for liveness generated by the region boundary.
462 if (LiveRegionEnd != RegionEnd)
463 BotRPTracker.recede();
464
465 assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000466
467 // Cache the list of excess pressure sets in this region. This will also track
468 // the max pressure in the scheduled code for these sets.
469 RegionCriticalPSets.clear();
Jakub Staszakb74564a2013-01-25 21:44:27 +0000470 const std::vector<unsigned> &RegionPressure =
471 RPTracker.getPressure().MaxSetPressure;
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000472 for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
473 unsigned Limit = TRI->getRegPressureSetLimit(i);
Andrew Trick78e5efe2012-09-11 00:39:15 +0000474 DEBUG(dbgs() << TRI->getRegPressureSetName(i)
475 << "Limit " << Limit
476 << " Actual " << RegionPressure[i] << "\n");
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000477 if (RegionPressure[i] > Limit)
478 RegionCriticalPSets.push_back(PressureElement(i, 0));
479 }
480 DEBUG(dbgs() << "Excess PSets: ";
481 for (unsigned i = 0, e = RegionCriticalPSets.size(); i != e; ++i)
482 dbgs() << TRI->getRegPressureSetName(
483 RegionCriticalPSets[i].PSetID) << " ";
484 dbgs() << "\n");
485}
486
487// FIXME: When the pressure tracker deals in pressure differences then we won't
488// iterate over all RegionCriticalPSets[i].
489void ScheduleDAGMI::
Jakub Staszakb717a502013-02-16 15:47:26 +0000490updateScheduledPressure(const std::vector<unsigned> &NewMaxPressure) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000491 for (unsigned i = 0, e = RegionCriticalPSets.size(); i < e; ++i) {
492 unsigned ID = RegionCriticalPSets[i].PSetID;
493 int &MaxUnits = RegionCriticalPSets[i].UnitIncrease;
494 if ((int)NewMaxPressure[ID] > MaxUnits)
495 MaxUnits = NewMaxPressure[ID];
496 }
Andrew Trick006e1ab2012-04-24 17:56:43 +0000497}
498
Andrew Trick17d35e52012-03-14 04:00:41 +0000499/// schedule - Called back from MachineScheduler::runOnMachineFunction
Andrew Trick006e1ab2012-04-24 17:56:43 +0000500/// after setting up the current scheduling region. [RegionBegin, RegionEnd)
501/// only includes instructions that have DAG nodes, not scheduling boundaries.
Andrew Trick78e5efe2012-09-11 00:39:15 +0000502///
503/// This is a skeletal driver, with all the functionality pushed into helpers,
504/// so that it can be easilly extended by experimental schedulers. Generally,
505/// implementing MachineSchedStrategy should be sufficient to implement a new
506/// scheduling algorithm. However, if a scheduler further subclasses
507/// ScheduleDAGMI then it will want to override this virtual method in order to
508/// update any specialized state.
Andrew Trick17d35e52012-03-14 04:00:41 +0000509void ScheduleDAGMI::schedule() {
Andrew Trick78e5efe2012-09-11 00:39:15 +0000510 buildDAGWithRegPressure();
511
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000512 Topo.InitDAGTopologicalSorting();
513
Andrew Trickd039b382012-09-14 17:22:42 +0000514 postprocessDAG();
515
Andrew Trick4e1fb182013-01-25 06:33:57 +0000516 SmallVector<SUnit*, 8> TopRoots, BotRoots;
517 findRootsAndBiasEdges(TopRoots, BotRoots);
518
519 // Initialize the strategy before modifying the DAG.
520 // This may initialize a DFSResult to be used for queue priority.
521 SchedImpl->initialize(this);
522
Andrew Trick78e5efe2012-09-11 00:39:15 +0000523 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
524 SUnits[su].dumpAll(this));
Andrew Trick4e1fb182013-01-25 06:33:57 +0000525 if (ViewMISchedDAGs) viewGraph();
Andrew Trick78e5efe2012-09-11 00:39:15 +0000526
Andrew Trick4e1fb182013-01-25 06:33:57 +0000527 // Initialize ready queues now that the DAG and priority data are finalized.
528 initQueues(TopRoots, BotRoots);
Andrew Trick78e5efe2012-09-11 00:39:15 +0000529
530 bool IsTopNode = false;
531 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
Andrew Trick30c6ec22012-10-08 18:53:53 +0000532 assert(!SU->isScheduled && "Node already scheduled");
Andrew Trick78e5efe2012-09-11 00:39:15 +0000533 if (!checkSchedLimit())
534 break;
535
536 scheduleMI(SU, IsTopNode);
537
538 updateQueues(SU, IsTopNode);
539 }
540 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
541
542 placeDebugValues();
Andrew Trick3b87f622012-11-07 07:05:09 +0000543
544 DEBUG({
Andrew Trickb4221042012-11-28 03:42:47 +0000545 unsigned BBNum = begin()->getParent()->getNumber();
Andrew Trick3b87f622012-11-07 07:05:09 +0000546 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
547 dumpSchedule();
548 dbgs() << '\n';
549 });
Andrew Trick78e5efe2012-09-11 00:39:15 +0000550}
551
552/// Build the DAG and setup three register pressure trackers.
553void ScheduleDAGMI::buildDAGWithRegPressure() {
Andrew Trick7f8ab782012-05-10 21:06:10 +0000554 // Initialize the register pressure tracker used by buildSchedGraph.
555 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
Andrew Trick006e1ab2012-04-24 17:56:43 +0000556
Andrew Trick7f8ab782012-05-10 21:06:10 +0000557 // Account for liveness generate by the region boundary.
558 if (LiveRegionEnd != RegionEnd)
559 RPTracker.recede();
560
561 // Build the DAG, and compute current register pressure.
Andrew Trick006e1ab2012-04-24 17:56:43 +0000562 buildSchedGraph(AA, &RPTracker);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000563
Andrew Trick7f8ab782012-05-10 21:06:10 +0000564 // Initialize top/bottom trackers after computing region pressure.
565 initRegPressure();
Andrew Trick78e5efe2012-09-11 00:39:15 +0000566}
Andrew Trick7f8ab782012-05-10 21:06:10 +0000567
Andrew Trickd039b382012-09-14 17:22:42 +0000568/// Apply each ScheduleDAGMutation step in order.
569void ScheduleDAGMI::postprocessDAG() {
570 for (unsigned i = 0, e = Mutations.size(); i < e; ++i) {
571 Mutations[i]->apply(this);
572 }
573}
574
Andrew Trick4e1fb182013-01-25 06:33:57 +0000575void ScheduleDAGMI::computeDFSResult() {
Andrew Trick178f7d02013-01-25 04:01:04 +0000576 if (!DFSResult)
577 DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize);
578 DFSResult->clear();
Andrew Trick178f7d02013-01-25 04:01:04 +0000579 ScheduledTrees.clear();
Andrew Trick4e1fb182013-01-25 06:33:57 +0000580 DFSResult->resize(SUnits.size());
581 DFSResult->compute(SUnits);
Andrew Trick178f7d02013-01-25 04:01:04 +0000582 ScheduledTrees.resize(DFSResult->getNumSubtrees());
583}
584
Andrew Trick4e1fb182013-01-25 06:33:57 +0000585void ScheduleDAGMI::findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
586 SmallVectorImpl<SUnit*> &BotRoots) {
Andrew Trick1e94e982012-10-15 18:02:27 +0000587 for (std::vector<SUnit>::iterator
588 I = SUnits.begin(), E = SUnits.end(); I != E; ++I) {
Andrew Trickae692f22012-11-12 19:28:57 +0000589 SUnit *SU = &(*I);
Andrew Trick4c6a2ba2013-01-29 06:26:35 +0000590 assert(!SU->isBoundaryNode() && "Boundary node should not be in SUnits");
Andrew Trickdb417062013-01-24 02:09:57 +0000591
592 // Order predecessors so DFSResult follows the critical path.
593 SU->biasCriticalPath();
594
Andrew Trick1e94e982012-10-15 18:02:27 +0000595 // A SUnit is ready to top schedule if it has no predecessors.
Andrew Trick4c6a2ba2013-01-29 06:26:35 +0000596 if (!I->NumPredsLeft)
Andrew Trick4e1fb182013-01-25 06:33:57 +0000597 TopRoots.push_back(SU);
Andrew Trick1e94e982012-10-15 18:02:27 +0000598 // A SUnit is ready to bottom schedule if it has no successors.
Andrew Trick4c6a2ba2013-01-29 06:26:35 +0000599 if (!I->NumSuccsLeft)
Andrew Trickae692f22012-11-12 19:28:57 +0000600 BotRoots.push_back(SU);
Andrew Trick1e94e982012-10-15 18:02:27 +0000601 }
Andrew Trick4c6a2ba2013-01-29 06:26:35 +0000602 ExitSU.biasCriticalPath();
Andrew Trick1e94e982012-10-15 18:02:27 +0000603}
604
Andrew Trick78e5efe2012-09-11 00:39:15 +0000605/// Identify DAG roots and setup scheduler queues.
Andrew Trick4e1fb182013-01-25 06:33:57 +0000606void ScheduleDAGMI::initQueues(ArrayRef<SUnit*> TopRoots,
607 ArrayRef<SUnit*> BotRoots) {
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000608 NextClusterSucc = NULL;
609 NextClusterPred = NULL;
Andrew Trick1e94e982012-10-15 18:02:27 +0000610
Andrew Trickae692f22012-11-12 19:28:57 +0000611 // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
Andrew Trick4e1fb182013-01-25 06:33:57 +0000612 //
613 // Nodes with unreleased weak edges can still be roots.
614 // Release top roots in forward order.
615 for (SmallVectorImpl<SUnit*>::const_iterator
616 I = TopRoots.begin(), E = TopRoots.end(); I != E; ++I) {
617 SchedImpl->releaseTopNode(*I);
618 }
619 // Release bottom roots in reverse order so the higher priority nodes appear
620 // first. This is more natural and slightly more efficient.
621 for (SmallVectorImpl<SUnit*>::const_reverse_iterator
622 I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I) {
623 SchedImpl->releaseBottomNode(*I);
624 }
Andrew Trickae692f22012-11-12 19:28:57 +0000625
Andrew Trickc174eaf2012-03-08 01:41:12 +0000626 releaseSuccessors(&EntrySU);
Andrew Trick17d35e52012-03-14 04:00:41 +0000627 releasePredecessors(&ExitSU);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000628
Andrew Trick1e94e982012-10-15 18:02:27 +0000629 SchedImpl->registerRoots();
630
Andrew Trick657b75b2012-12-01 01:22:49 +0000631 // Advance past initial DebugValues.
632 assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000633 CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
Andrew Trick657b75b2012-12-01 01:22:49 +0000634 TopRPTracker.setPos(CurrentTop);
635
Andrew Trick17d35e52012-03-14 04:00:41 +0000636 CurrentBottom = RegionEnd;
Andrew Trick78e5efe2012-09-11 00:39:15 +0000637}
Andrew Trickc174eaf2012-03-08 01:41:12 +0000638
Andrew Trick78e5efe2012-09-11 00:39:15 +0000639/// Move an instruction and update register pressure.
640void ScheduleDAGMI::scheduleMI(SUnit *SU, bool IsTopNode) {
641 // Move the instruction to its new location in the instruction stream.
642 MachineInstr *MI = SU->getInstr();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000643
Andrew Trick78e5efe2012-09-11 00:39:15 +0000644 if (IsTopNode) {
645 assert(SU->isTopReady() && "node still has unscheduled dependencies");
646 if (&*CurrentTop == MI)
647 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
Andrew Trick17d35e52012-03-14 04:00:41 +0000648 else {
Andrew Trick78e5efe2012-09-11 00:39:15 +0000649 moveInstruction(MI, CurrentTop);
650 TopRPTracker.setPos(MI);
Andrew Trick17d35e52012-03-14 04:00:41 +0000651 }
Andrew Trick000b2502012-04-24 18:04:37 +0000652
Andrew Trick78e5efe2012-09-11 00:39:15 +0000653 // Update top scheduled pressure.
654 TopRPTracker.advance();
655 assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
656 updateScheduledPressure(TopRPTracker.getPressure().MaxSetPressure);
657 }
658 else {
659 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
660 MachineBasicBlock::iterator priorII =
661 priorNonDebug(CurrentBottom, CurrentTop);
662 if (&*priorII == MI)
663 CurrentBottom = priorII;
664 else {
665 if (&*CurrentTop == MI) {
666 CurrentTop = nextIfDebug(++CurrentTop, priorII);
667 TopRPTracker.setPos(CurrentTop);
668 }
669 moveInstruction(MI, CurrentBottom);
670 CurrentBottom = MI;
671 }
672 // Update bottom scheduled pressure.
673 BotRPTracker.recede();
674 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
675 updateScheduledPressure(BotRPTracker.getPressure().MaxSetPressure);
676 }
677}
678
679/// Update scheduler queues after scheduling an instruction.
680void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
681 // Release dependent instructions for scheduling.
682 if (IsTopNode)
683 releaseSuccessors(SU);
684 else
685 releasePredecessors(SU);
686
687 SU->isScheduled = true;
688
Andrew Trick178f7d02013-01-25 04:01:04 +0000689 if (DFSResult) {
690 unsigned SubtreeID = DFSResult->getSubtreeID(SU);
691 if (!ScheduledTrees.test(SubtreeID)) {
692 ScheduledTrees.set(SubtreeID);
693 DFSResult->scheduleTree(SubtreeID);
694 SchedImpl->scheduleTree(SubtreeID);
695 }
696 }
697
Andrew Trick78e5efe2012-09-11 00:39:15 +0000698 // Notify the scheduling strategy after updating the DAG.
699 SchedImpl->schedNode(SU, IsTopNode);
Andrew Trick000b2502012-04-24 18:04:37 +0000700}
701
702/// Reinsert any remaining debug_values, just like the PostRA scheduler.
703void ScheduleDAGMI::placeDebugValues() {
704 // If first instruction was a DBG_VALUE then put it back.
705 if (FirstDbgValue) {
706 BB->splice(RegionBegin, BB, FirstDbgValue);
707 RegionBegin = FirstDbgValue;
708 }
709
710 for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
711 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
712 std::pair<MachineInstr *, MachineInstr *> P = *prior(DI);
713 MachineInstr *DbgValue = P.first;
714 MachineBasicBlock::iterator OrigPrevMI = P.second;
Andrew Trick67bdd422012-12-01 01:22:38 +0000715 if (&*RegionBegin == DbgValue)
716 ++RegionBegin;
Andrew Trick000b2502012-04-24 18:04:37 +0000717 BB->splice(++OrigPrevMI, BB, DbgValue);
718 if (OrigPrevMI == llvm::prior(RegionEnd))
719 RegionEnd = DbgValue;
720 }
721 DbgValues.clear();
722 FirstDbgValue = NULL;
Andrew Trickc174eaf2012-03-08 01:41:12 +0000723}
724
Andrew Trick3b87f622012-11-07 07:05:09 +0000725#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
726void ScheduleDAGMI::dumpSchedule() const {
727 for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
728 if (SUnit *SU = getSUnit(&(*MI)))
729 SU->dump(this);
730 else
731 dbgs() << "Missing SUnit\n";
732 }
733}
734#endif
735
Andrew Trick6996fd02012-11-12 19:52:20 +0000736//===----------------------------------------------------------------------===//
737// LoadClusterMutation - DAG post-processing to cluster loads.
738//===----------------------------------------------------------------------===//
739
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000740namespace {
741/// \brief Post-process the DAG to create cluster edges between neighboring
742/// loads.
743class LoadClusterMutation : public ScheduleDAGMutation {
744 struct LoadInfo {
745 SUnit *SU;
746 unsigned BaseReg;
747 unsigned Offset;
748 LoadInfo(SUnit *su, unsigned reg, unsigned ofs)
749 : SU(su), BaseReg(reg), Offset(ofs) {}
750 };
751 static bool LoadInfoLess(const LoadClusterMutation::LoadInfo &LHS,
752 const LoadClusterMutation::LoadInfo &RHS);
753
754 const TargetInstrInfo *TII;
755 const TargetRegisterInfo *TRI;
756public:
757 LoadClusterMutation(const TargetInstrInfo *tii,
758 const TargetRegisterInfo *tri)
759 : TII(tii), TRI(tri) {}
760
761 virtual void apply(ScheduleDAGMI *DAG);
762protected:
763 void clusterNeighboringLoads(ArrayRef<SUnit*> Loads, ScheduleDAGMI *DAG);
764};
765} // anonymous
766
767bool LoadClusterMutation::LoadInfoLess(
768 const LoadClusterMutation::LoadInfo &LHS,
769 const LoadClusterMutation::LoadInfo &RHS) {
770 if (LHS.BaseReg != RHS.BaseReg)
771 return LHS.BaseReg < RHS.BaseReg;
772 return LHS.Offset < RHS.Offset;
773}
774
775void LoadClusterMutation::clusterNeighboringLoads(ArrayRef<SUnit*> Loads,
776 ScheduleDAGMI *DAG) {
777 SmallVector<LoadClusterMutation::LoadInfo,32> LoadRecords;
778 for (unsigned Idx = 0, End = Loads.size(); Idx != End; ++Idx) {
779 SUnit *SU = Loads[Idx];
780 unsigned BaseReg;
781 unsigned Offset;
782 if (TII->getLdStBaseRegImmOfs(SU->getInstr(), BaseReg, Offset, TRI))
783 LoadRecords.push_back(LoadInfo(SU, BaseReg, Offset));
784 }
785 if (LoadRecords.size() < 2)
786 return;
787 std::sort(LoadRecords.begin(), LoadRecords.end(), LoadInfoLess);
788 unsigned ClusterLength = 1;
789 for (unsigned Idx = 0, End = LoadRecords.size(); Idx < (End - 1); ++Idx) {
790 if (LoadRecords[Idx].BaseReg != LoadRecords[Idx+1].BaseReg) {
791 ClusterLength = 1;
792 continue;
793 }
794
795 SUnit *SUa = LoadRecords[Idx].SU;
796 SUnit *SUb = LoadRecords[Idx+1].SU;
Andrew Tricka7d2d562012-11-12 21:28:10 +0000797 if (TII->shouldClusterLoads(SUa->getInstr(), SUb->getInstr(), ClusterLength)
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000798 && DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
799
800 DEBUG(dbgs() << "Cluster loads SU(" << SUa->NodeNum << ") - SU("
801 << SUb->NodeNum << ")\n");
802 // Copy successor edges from SUa to SUb. Interleaving computation
803 // dependent on SUa can prevent load combining due to register reuse.
804 // Predecessor edges do not need to be copied from SUb to SUa since nearby
805 // loads should have effectively the same inputs.
806 for (SUnit::const_succ_iterator
807 SI = SUa->Succs.begin(), SE = SUa->Succs.end(); SI != SE; ++SI) {
808 if (SI->getSUnit() == SUb)
809 continue;
810 DEBUG(dbgs() << " Copy Succ SU(" << SI->getSUnit()->NodeNum << ")\n");
811 DAG->addEdge(SI->getSUnit(), SDep(SUb, SDep::Artificial));
812 }
813 ++ClusterLength;
814 }
815 else
816 ClusterLength = 1;
817 }
818}
819
820/// \brief Callback from DAG postProcessing to create cluster edges for loads.
821void LoadClusterMutation::apply(ScheduleDAGMI *DAG) {
822 // Map DAG NodeNum to store chain ID.
823 DenseMap<unsigned, unsigned> StoreChainIDs;
824 // Map each store chain to a set of dependent loads.
825 SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
826 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
827 SUnit *SU = &DAG->SUnits[Idx];
828 if (!SU->getInstr()->mayLoad())
829 continue;
830 unsigned ChainPredID = DAG->SUnits.size();
831 for (SUnit::const_pred_iterator
832 PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
833 if (PI->isCtrl()) {
834 ChainPredID = PI->getSUnit()->NodeNum;
835 break;
836 }
837 }
838 // Check if this chain-like pred has been seen
839 // before. ChainPredID==MaxNodeID for loads at the top of the schedule.
840 unsigned NumChains = StoreChainDependents.size();
841 std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
842 StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
843 if (Result.second)
844 StoreChainDependents.resize(NumChains + 1);
845 StoreChainDependents[Result.first->second].push_back(SU);
846 }
847 // Iterate over the store chains.
848 for (unsigned Idx = 0, End = StoreChainDependents.size(); Idx != End; ++Idx)
849 clusterNeighboringLoads(StoreChainDependents[Idx], DAG);
850}
851
Andrew Trickc174eaf2012-03-08 01:41:12 +0000852//===----------------------------------------------------------------------===//
Andrew Trick6996fd02012-11-12 19:52:20 +0000853// MacroFusion - DAG post-processing to encourage fusion of macro ops.
854//===----------------------------------------------------------------------===//
855
856namespace {
857/// \brief Post-process the DAG to create cluster edges between instructions
858/// that may be fused by the processor into a single operation.
859class MacroFusion : public ScheduleDAGMutation {
860 const TargetInstrInfo *TII;
861public:
862 MacroFusion(const TargetInstrInfo *tii): TII(tii) {}
863
864 virtual void apply(ScheduleDAGMI *DAG);
865};
866} // anonymous
867
868/// \brief Callback from DAG postProcessing to create cluster edges to encourage
869/// fused operations.
870void MacroFusion::apply(ScheduleDAGMI *DAG) {
871 // For now, assume targets can only fuse with the branch.
872 MachineInstr *Branch = DAG->ExitSU.getInstr();
873 if (!Branch)
874 return;
875
876 for (unsigned Idx = DAG->SUnits.size(); Idx > 0;) {
877 SUnit *SU = &DAG->SUnits[--Idx];
878 if (!TII->shouldScheduleAdjacent(SU->getInstr(), Branch))
879 continue;
880
881 // Create a single weak edge from SU to ExitSU. The only effect is to cause
882 // bottom-up scheduling to heavily prioritize the clustered SU. There is no
883 // need to copy predecessor edges from ExitSU to SU, since top-down
884 // scheduling cannot prioritize ExitSU anyway. To defer top-down scheduling
885 // of SU, we could create an artificial edge from the deepest root, but it
886 // hasn't been needed yet.
887 bool Success = DAG->addEdge(&DAG->ExitSU, SDep(SU, SDep::Cluster));
888 (void)Success;
889 assert(Success && "No DAG nodes should be reachable from ExitSU");
890
891 DEBUG(dbgs() << "Macro Fuse SU(" << SU->NodeNum << ")\n");
892 break;
893 }
894}
895
896//===----------------------------------------------------------------------===//
Andrew Trick17d35e52012-03-14 04:00:41 +0000897// ConvergingScheduler - Implementation of the standard MachineSchedStrategy.
Andrew Trick42b7a712012-01-17 06:55:03 +0000898//===----------------------------------------------------------------------===//
899
900namespace {
Andrew Trick17d35e52012-03-14 04:00:41 +0000901/// ConvergingScheduler shrinks the unscheduled zone using heuristics to balance
902/// the schedule.
903class ConvergingScheduler : public MachineSchedStrategy {
Andrew Trick3b87f622012-11-07 07:05:09 +0000904public:
905 /// Represent the type of SchedCandidate found within a single queue.
906 /// pickNodeBidirectional depends on these listed by decreasing priority.
907 enum CandReason {
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000908 NoCand, SingleExcess, SingleCritical, Cluster,
909 ResourceReduce, ResourceDemand, BotHeightReduce, BotPathReduce,
910 TopDepthReduce, TopPathReduce, SingleMax, MultiPressure, NextDefUse,
911 NodeOrder};
Andrew Trick3b87f622012-11-07 07:05:09 +0000912
913#ifndef NDEBUG
914 static const char *getReasonStr(ConvergingScheduler::CandReason Reason);
915#endif
916
917 /// Policy for scheduling the next instruction in the candidate's zone.
918 struct CandPolicy {
919 bool ReduceLatency;
920 unsigned ReduceResIdx;
921 unsigned DemandResIdx;
922
923 CandPolicy(): ReduceLatency(false), ReduceResIdx(0), DemandResIdx(0) {}
924 };
925
926 /// Status of an instruction's critical resource consumption.
927 struct SchedResourceDelta {
928 // Count critical resources in the scheduled region required by SU.
929 unsigned CritResources;
930
931 // Count critical resources from another region consumed by SU.
932 unsigned DemandedResources;
933
934 SchedResourceDelta(): CritResources(0), DemandedResources(0) {}
935
936 bool operator==(const SchedResourceDelta &RHS) const {
937 return CritResources == RHS.CritResources
938 && DemandedResources == RHS.DemandedResources;
939 }
940 bool operator!=(const SchedResourceDelta &RHS) const {
941 return !operator==(RHS);
942 }
943 };
Andrew Trick7196a8f2012-05-10 21:06:16 +0000944
945 /// Store the state used by ConvergingScheduler heuristics, required for the
946 /// lifetime of one invocation of pickNode().
947 struct SchedCandidate {
Andrew Trick3b87f622012-11-07 07:05:09 +0000948 CandPolicy Policy;
949
Andrew Trick7196a8f2012-05-10 21:06:16 +0000950 // The best SUnit candidate.
951 SUnit *SU;
952
Andrew Trick3b87f622012-11-07 07:05:09 +0000953 // The reason for this candidate.
954 CandReason Reason;
955
Andrew Trick7196a8f2012-05-10 21:06:16 +0000956 // Register pressure values for the best candidate.
957 RegPressureDelta RPDelta;
958
Andrew Trick3b87f622012-11-07 07:05:09 +0000959 // Critical resource consumption of the best candidate.
960 SchedResourceDelta ResDelta;
961
962 SchedCandidate(const CandPolicy &policy)
963 : Policy(policy), SU(NULL), Reason(NoCand) {}
964
965 bool isValid() const { return SU; }
966
967 // Copy the status of another candidate without changing policy.
968 void setBest(SchedCandidate &Best) {
969 assert(Best.Reason != NoCand && "uninitialized Sched candidate");
970 SU = Best.SU;
971 Reason = Best.Reason;
972 RPDelta = Best.RPDelta;
973 ResDelta = Best.ResDelta;
974 }
975
976 void initResourceDelta(const ScheduleDAGMI *DAG,
977 const TargetSchedModel *SchedModel);
Andrew Trick7196a8f2012-05-10 21:06:16 +0000978 };
Andrew Trick3b87f622012-11-07 07:05:09 +0000979
980 /// Summarize the unscheduled region.
981 struct SchedRemainder {
982 // Critical path through the DAG in expected latency.
983 unsigned CriticalPath;
984
985 // Unscheduled resources
986 SmallVector<unsigned, 16> RemainingCounts;
987 // Critical resource for the unscheduled zone.
988 unsigned CritResIdx;
989 // Number of micro-ops left to schedule.
990 unsigned RemainingMicroOps;
Andrew Trick3b87f622012-11-07 07:05:09 +0000991
Andrew Trick3b87f622012-11-07 07:05:09 +0000992 void reset() {
993 CriticalPath = 0;
994 RemainingCounts.clear();
995 CritResIdx = 0;
996 RemainingMicroOps = 0;
Andrew Trick3b87f622012-11-07 07:05:09 +0000997 }
998
999 SchedRemainder() { reset(); }
1000
1001 void init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel);
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001002
1003 unsigned getMaxRemainingCount(const TargetSchedModel *SchedModel) const {
1004 if (!SchedModel->hasInstrSchedModel())
1005 return 0;
1006
1007 return std::max(
1008 RemainingMicroOps * SchedModel->getMicroOpFactor(),
1009 RemainingCounts[CritResIdx]);
1010 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001011 };
Andrew Trick7196a8f2012-05-10 21:06:16 +00001012
Andrew Trickf3234242012-05-24 22:11:12 +00001013 /// Each Scheduling boundary is associated with ready queues. It tracks the
Andrew Trick3b87f622012-11-07 07:05:09 +00001014 /// current cycle in the direction of movement, and maintains the state
Andrew Trickf3234242012-05-24 22:11:12 +00001015 /// of "hazards" and other interlocks at the current cycle.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001016 struct SchedBoundary {
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001017 ScheduleDAGMI *DAG;
Andrew Trick412cd2f2012-10-10 05:43:09 +00001018 const TargetSchedModel *SchedModel;
Andrew Trick3b87f622012-11-07 07:05:09 +00001019 SchedRemainder *Rem;
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001020
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001021 ReadyQueue Available;
1022 ReadyQueue Pending;
1023 bool CheckPending;
1024
Andrew Trick3b87f622012-11-07 07:05:09 +00001025 // For heuristics, keep a list of the nodes that immediately depend on the
1026 // most recently scheduled node.
1027 SmallPtrSet<const SUnit*, 8> NextSUs;
1028
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001029 ScheduleHazardRecognizer *HazardRec;
1030
1031 unsigned CurrCycle;
1032 unsigned IssueCount;
1033
1034 /// MinReadyCycle - Cycle of the soonest available instruction.
1035 unsigned MinReadyCycle;
1036
Andrew Trick3b87f622012-11-07 07:05:09 +00001037 // The expected latency of the critical path in this scheduled zone.
1038 unsigned ExpectedLatency;
1039
1040 // Resources used in the scheduled zone beyond this boundary.
1041 SmallVector<unsigned, 16> ResourceCounts;
1042
1043 // Cache the critical resources ID in this scheduled zone.
1044 unsigned CritResIdx;
1045
1046 // Is the scheduled region resource limited vs. latency limited.
1047 bool IsResourceLimited;
1048
1049 unsigned ExpectedCount;
1050
Andrew Trick3b87f622012-11-07 07:05:09 +00001051#ifndef NDEBUG
Andrew Trickb7e02892012-06-05 21:11:27 +00001052 // Remember the greatest min operand latency.
1053 unsigned MaxMinLatency;
Andrew Trick3b87f622012-11-07 07:05:09 +00001054#endif
1055
1056 void reset() {
Andrew Trickecb8c2b2013-02-13 19:22:27 +00001057 // A new HazardRec is created for each DAG and owned by SchedBoundary.
1058 delete HazardRec;
1059
Andrew Trick3b87f622012-11-07 07:05:09 +00001060 Available.clear();
1061 Pending.clear();
1062 CheckPending = false;
1063 NextSUs.clear();
1064 HazardRec = 0;
1065 CurrCycle = 0;
1066 IssueCount = 0;
1067 MinReadyCycle = UINT_MAX;
1068 ExpectedLatency = 0;
1069 ResourceCounts.resize(1);
1070 assert(!ResourceCounts[0] && "nonzero count for bad resource");
1071 CritResIdx = 0;
1072 IsResourceLimited = false;
1073 ExpectedCount = 0;
Andrew Trick3b87f622012-11-07 07:05:09 +00001074#ifndef NDEBUG
1075 MaxMinLatency = 0;
1076#endif
1077 // Reserve a zero-count for invalid CritResIdx.
1078 ResourceCounts.resize(1);
1079 }
Andrew Trickb7e02892012-06-05 21:11:27 +00001080
Andrew Trickf3234242012-05-24 22:11:12 +00001081 /// Pending queues extend the ready queues with the same ID and the
1082 /// PendingFlag set.
1083 SchedBoundary(unsigned ID, const Twine &Name):
Andrew Trick3b87f622012-11-07 07:05:09 +00001084 DAG(0), SchedModel(0), Rem(0), Available(ID, Name+".A"),
Andrew Trickecb8c2b2013-02-13 19:22:27 +00001085 Pending(ID << ConvergingScheduler::LogMaxQID, Name+".P"),
1086 HazardRec(0) {
Andrew Trick3b87f622012-11-07 07:05:09 +00001087 reset();
1088 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001089
1090 ~SchedBoundary() { delete HazardRec; }
1091
Andrew Trick3b87f622012-11-07 07:05:09 +00001092 void init(ScheduleDAGMI *dag, const TargetSchedModel *smodel,
1093 SchedRemainder *rem);
Andrew Trick412cd2f2012-10-10 05:43:09 +00001094
Andrew Trickf3234242012-05-24 22:11:12 +00001095 bool isTop() const {
1096 return Available.getID() == ConvergingScheduler::TopQID;
1097 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001098
Andrew Trick3b87f622012-11-07 07:05:09 +00001099 unsigned getUnscheduledLatency(SUnit *SU) const {
1100 if (isTop())
1101 return SU->getHeight();
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001102 return SU->getDepth() + SU->Latency;
Andrew Trick3b87f622012-11-07 07:05:09 +00001103 }
1104
1105 unsigned getCriticalCount() const {
1106 return ResourceCounts[CritResIdx];
1107 }
1108
Andrew Trick5559ffa2012-06-29 03:23:24 +00001109 bool checkHazard(SUnit *SU);
1110
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001111 void setLatencyPolicy(CandPolicy &Policy);
Andrew Trick3b87f622012-11-07 07:05:09 +00001112
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001113 void releaseNode(SUnit *SU, unsigned ReadyCycle);
1114
1115 void bumpCycle();
1116
Andrew Trick3b87f622012-11-07 07:05:09 +00001117 void countResource(unsigned PIdx, unsigned Cycles);
1118
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001119 void bumpNode(SUnit *SU);
Andrew Trickb7e02892012-06-05 21:11:27 +00001120
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001121 void releasePending();
1122
1123 void removeReady(SUnit *SU);
1124
1125 SUnit *pickOnlyChoice();
1126 };
1127
Andrew Trick3b87f622012-11-07 07:05:09 +00001128private:
Andrew Trick17d35e52012-03-14 04:00:41 +00001129 ScheduleDAGMI *DAG;
Andrew Trick412cd2f2012-10-10 05:43:09 +00001130 const TargetSchedModel *SchedModel;
Andrew Trick7196a8f2012-05-10 21:06:16 +00001131 const TargetRegisterInfo *TRI;
Andrew Trick42b7a712012-01-17 06:55:03 +00001132
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001133 // State of the top and bottom scheduled instruction boundaries.
Andrew Trick3b87f622012-11-07 07:05:09 +00001134 SchedRemainder Rem;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001135 SchedBoundary Top;
1136 SchedBoundary Bot;
Andrew Trick17d35e52012-03-14 04:00:41 +00001137
1138public:
Andrew Trickf3234242012-05-24 22:11:12 +00001139 /// SUnit::NodeQueueId: 0 (none), 1 (top), 2 (bot), 3 (both)
Andrew Trick7196a8f2012-05-10 21:06:16 +00001140 enum {
1141 TopQID = 1,
Andrew Trickf3234242012-05-24 22:11:12 +00001142 BotQID = 2,
1143 LogMaxQID = 2
Andrew Trick7196a8f2012-05-10 21:06:16 +00001144 };
1145
Andrew Trickf3234242012-05-24 22:11:12 +00001146 ConvergingScheduler():
Andrew Trick412cd2f2012-10-10 05:43:09 +00001147 DAG(0), SchedModel(0), TRI(0), Top(TopQID, "TopQ"), Bot(BotQID, "BotQ") {}
Andrew Trickd38f87e2012-05-10 21:06:12 +00001148
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001149 virtual void initialize(ScheduleDAGMI *dag);
Andrew Trick17d35e52012-03-14 04:00:41 +00001150
Andrew Trick7196a8f2012-05-10 21:06:16 +00001151 virtual SUnit *pickNode(bool &IsTopNode);
Andrew Trick17d35e52012-03-14 04:00:41 +00001152
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001153 virtual void schedNode(SUnit *SU, bool IsTopNode);
1154
1155 virtual void releaseTopNode(SUnit *SU);
1156
1157 virtual void releaseBottomNode(SUnit *SU);
1158
Andrew Trick3b87f622012-11-07 07:05:09 +00001159 virtual void registerRoots();
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001160
Andrew Trick3b87f622012-11-07 07:05:09 +00001161protected:
1162 void balanceZones(
1163 ConvergingScheduler::SchedBoundary &CriticalZone,
1164 ConvergingScheduler::SchedCandidate &CriticalCand,
1165 ConvergingScheduler::SchedBoundary &OppositeZone,
1166 ConvergingScheduler::SchedCandidate &OppositeCand);
1167
1168 void checkResourceLimits(ConvergingScheduler::SchedCandidate &TopCand,
1169 ConvergingScheduler::SchedCandidate &BotCand);
1170
1171 void tryCandidate(SchedCandidate &Cand,
1172 SchedCandidate &TryCand,
1173 SchedBoundary &Zone,
1174 const RegPressureTracker &RPTracker,
1175 RegPressureTracker &TempTracker);
1176
1177 SUnit *pickNodeBidirectional(bool &IsTopNode);
1178
1179 void pickNodeFromQueue(SchedBoundary &Zone,
1180 const RegPressureTracker &RPTracker,
1181 SchedCandidate &Candidate);
1182
Andrew Trick28ebc892012-05-10 21:06:19 +00001183#ifndef NDEBUG
Andrew Trick3b87f622012-11-07 07:05:09 +00001184 void traceCandidate(const SchedCandidate &Cand, const SchedBoundary &Zone);
Andrew Trick28ebc892012-05-10 21:06:19 +00001185#endif
Andrew Trick42b7a712012-01-17 06:55:03 +00001186};
1187} // namespace
1188
Andrew Trick3b87f622012-11-07 07:05:09 +00001189void ConvergingScheduler::SchedRemainder::
1190init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
1191 reset();
1192 if (!SchedModel->hasInstrSchedModel())
1193 return;
1194 RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
1195 for (std::vector<SUnit>::iterator
1196 I = DAG->SUnits.begin(), E = DAG->SUnits.end(); I != E; ++I) {
1197 const MCSchedClassDesc *SC = DAG->getSchedClass(&*I);
1198 RemainingMicroOps += SchedModel->getNumMicroOps(I->getInstr(), SC);
1199 for (TargetSchedModel::ProcResIter
1200 PI = SchedModel->getWriteProcResBegin(SC),
1201 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1202 unsigned PIdx = PI->ProcResourceIdx;
1203 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1204 RemainingCounts[PIdx] += (Factor * PI->Cycles);
1205 }
1206 }
Andrew Trick071966f2012-12-18 20:52:49 +00001207 for (unsigned PIdx = 0, PEnd = SchedModel->getNumProcResourceKinds();
1208 PIdx != PEnd; ++PIdx) {
1209 if ((int)(RemainingCounts[PIdx] - RemainingCounts[CritResIdx])
1210 >= (int)SchedModel->getLatencyFactor()) {
1211 CritResIdx = PIdx;
1212 }
1213 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001214}
1215
1216void ConvergingScheduler::SchedBoundary::
1217init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
1218 reset();
1219 DAG = dag;
1220 SchedModel = smodel;
1221 Rem = rem;
1222 if (SchedModel->hasInstrSchedModel())
1223 ResourceCounts.resize(SchedModel->getNumProcResourceKinds());
1224}
1225
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001226void ConvergingScheduler::initialize(ScheduleDAGMI *dag) {
1227 DAG = dag;
Andrew Trick412cd2f2012-10-10 05:43:09 +00001228 SchedModel = DAG->getSchedModel();
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001229 TRI = DAG->TRI;
Andrew Trickecb8c2b2013-02-13 19:22:27 +00001230
Andrew Trick3b87f622012-11-07 07:05:09 +00001231 Rem.init(DAG, SchedModel);
1232 Top.init(DAG, SchedModel, &Rem);
1233 Bot.init(DAG, SchedModel, &Rem);
1234
Andrew Trick4e1fb182013-01-25 06:33:57 +00001235 DAG->computeDFSResult();
Andrew Trick178f7d02013-01-25 04:01:04 +00001236
Andrew Trick3b87f622012-11-07 07:05:09 +00001237 // Initialize resource counts.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001238
Andrew Trick412cd2f2012-10-10 05:43:09 +00001239 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
1240 // are disabled, then these HazardRecs will be disabled.
1241 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001242 const TargetMachine &TM = DAG->MF.getTarget();
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001243 Top.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
1244 Bot.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
1245
1246 assert((!ForceTopDown || !ForceBottomUp) &&
1247 "-misched-topdown incompatible with -misched-bottomup");
1248}
1249
1250void ConvergingScheduler::releaseTopNode(SUnit *SU) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001251 if (SU->isScheduled)
1252 return;
1253
Andrew Trickd4539602012-12-18 20:52:52 +00001254 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
Andrew Trickb7e02892012-06-05 21:11:27 +00001255 I != E; ++I) {
1256 unsigned PredReadyCycle = I->getSUnit()->TopReadyCycle;
Andrew Trickffd25262012-08-23 00:39:43 +00001257 unsigned MinLatency = I->getMinLatency();
Andrew Trickb7e02892012-06-05 21:11:27 +00001258#ifndef NDEBUG
Andrew Trickffd25262012-08-23 00:39:43 +00001259 Top.MaxMinLatency = std::max(MinLatency, Top.MaxMinLatency);
Andrew Trickb7e02892012-06-05 21:11:27 +00001260#endif
Andrew Trickffd25262012-08-23 00:39:43 +00001261 if (SU->TopReadyCycle < PredReadyCycle + MinLatency)
1262 SU->TopReadyCycle = PredReadyCycle + MinLatency;
Andrew Trickb7e02892012-06-05 21:11:27 +00001263 }
1264 Top.releaseNode(SU, SU->TopReadyCycle);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001265}
1266
1267void ConvergingScheduler::releaseBottomNode(SUnit *SU) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001268 if (SU->isScheduled)
1269 return;
1270
1271 assert(SU->getInstr() && "Scheduled SUnit must have instr");
1272
1273 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1274 I != E; ++I) {
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001275 if (I->isWeak())
1276 continue;
Andrew Trickb7e02892012-06-05 21:11:27 +00001277 unsigned SuccReadyCycle = I->getSUnit()->BotReadyCycle;
Andrew Trickffd25262012-08-23 00:39:43 +00001278 unsigned MinLatency = I->getMinLatency();
Andrew Trickb7e02892012-06-05 21:11:27 +00001279#ifndef NDEBUG
Andrew Trickffd25262012-08-23 00:39:43 +00001280 Bot.MaxMinLatency = std::max(MinLatency, Bot.MaxMinLatency);
Andrew Trickb7e02892012-06-05 21:11:27 +00001281#endif
Andrew Trickffd25262012-08-23 00:39:43 +00001282 if (SU->BotReadyCycle < SuccReadyCycle + MinLatency)
1283 SU->BotReadyCycle = SuccReadyCycle + MinLatency;
Andrew Trickb7e02892012-06-05 21:11:27 +00001284 }
1285 Bot.releaseNode(SU, SU->BotReadyCycle);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001286}
1287
Andrew Trick3b87f622012-11-07 07:05:09 +00001288void ConvergingScheduler::registerRoots() {
1289 Rem.CriticalPath = DAG->ExitSU.getDepth();
1290 // Some roots may not feed into ExitSU. Check all of them in case.
1291 for (std::vector<SUnit*>::const_iterator
1292 I = Bot.Available.begin(), E = Bot.Available.end(); I != E; ++I) {
1293 if ((*I)->getDepth() > Rem.CriticalPath)
1294 Rem.CriticalPath = (*I)->getDepth();
1295 }
1296 DEBUG(dbgs() << "Critical Path: " << Rem.CriticalPath << '\n');
1297}
1298
Andrew Trick5559ffa2012-06-29 03:23:24 +00001299/// Does this SU have a hazard within the current instruction group.
1300///
1301/// The scheduler supports two modes of hazard recognition. The first is the
1302/// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
1303/// supports highly complicated in-order reservation tables
1304/// (ScoreboardHazardRecognizer) and arbitraty target-specific logic.
1305///
1306/// The second is a streamlined mechanism that checks for hazards based on
1307/// simple counters that the scheduler itself maintains. It explicitly checks
1308/// for instruction dispatch limitations, including the number of micro-ops that
1309/// can dispatch per cycle.
1310///
1311/// TODO: Also check whether the SU must start a new group.
1312bool ConvergingScheduler::SchedBoundary::checkHazard(SUnit *SU) {
1313 if (HazardRec->isEnabled())
1314 return HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard;
1315
Andrew Trick412cd2f2012-10-10 05:43:09 +00001316 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
Andrew Trick3b87f622012-11-07 07:05:09 +00001317 if ((IssueCount > 0) && (IssueCount + uops > SchedModel->getIssueWidth())) {
1318 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") uops="
1319 << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
Andrew Trick5559ffa2012-06-29 03:23:24 +00001320 return true;
Andrew Trick3b87f622012-11-07 07:05:09 +00001321 }
Andrew Trick5559ffa2012-06-29 03:23:24 +00001322 return false;
1323}
1324
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001325/// Compute the remaining latency to determine whether ILP should be increased.
1326void ConvergingScheduler::SchedBoundary::setLatencyPolicy(CandPolicy &Policy) {
1327 // FIXME: compile time. In all, we visit four queues here one we should only
1328 // need to visit the one that was last popped if we cache the result.
1329 unsigned RemLatency = 0;
1330 for (ReadyQueue::iterator I = Available.begin(), E = Available.end();
1331 I != E; ++I) {
1332 unsigned L = getUnscheduledLatency(*I);
1333 if (L > RemLatency)
1334 RemLatency = L;
1335 }
1336 for (ReadyQueue::iterator I = Pending.begin(), E = Pending.end();
1337 I != E; ++I) {
1338 unsigned L = getUnscheduledLatency(*I);
1339 if (L > RemLatency)
1340 RemLatency = L;
1341 }
Andrew Trick47579cf2013-01-09 03:36:49 +00001342 unsigned CriticalPathLimit = Rem->CriticalPath + SchedModel->getILPWindow();
1343 if (RemLatency + ExpectedLatency >= CriticalPathLimit
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001344 && RemLatency > Rem->getMaxRemainingCount(SchedModel)) {
1345 Policy.ReduceLatency = true;
1346 DEBUG(dbgs() << "Increase ILP: " << Available.getName() << '\n');
Andrew Trick3b87f622012-11-07 07:05:09 +00001347 }
1348}
1349
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001350void ConvergingScheduler::SchedBoundary::releaseNode(SUnit *SU,
1351 unsigned ReadyCycle) {
Andrew Trick3b87f622012-11-07 07:05:09 +00001352
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001353 if (ReadyCycle < MinReadyCycle)
1354 MinReadyCycle = ReadyCycle;
1355
1356 // Check for interlocks first. For the purpose of other heuristics, an
1357 // instruction that cannot issue appears as if it's not in the ReadyQueue.
Andrew Trick5559ffa2012-06-29 03:23:24 +00001358 if (ReadyCycle > CurrCycle || checkHazard(SU))
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001359 Pending.push(SU);
1360 else
1361 Available.push(SU);
Andrew Trick3b87f622012-11-07 07:05:09 +00001362
1363 // Record this node as an immediate dependent of the scheduled node.
1364 NextSUs.insert(SU);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001365}
1366
1367/// Move the boundary of scheduled code by one cycle.
1368void ConvergingScheduler::SchedBoundary::bumpCycle() {
Andrew Trick412cd2f2012-10-10 05:43:09 +00001369 unsigned Width = SchedModel->getIssueWidth();
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001370 IssueCount = (IssueCount <= Width) ? 0 : IssueCount - Width;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001371
Andrew Trick3b87f622012-11-07 07:05:09 +00001372 unsigned NextCycle = CurrCycle + 1;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001373 assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
Andrew Trick3b87f622012-11-07 07:05:09 +00001374 if (MinReadyCycle > NextCycle) {
1375 IssueCount = 0;
1376 NextCycle = MinReadyCycle;
1377 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001378
1379 if (!HazardRec->isEnabled()) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001380 // Bypass HazardRec virtual calls.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001381 CurrCycle = NextCycle;
1382 }
1383 else {
Andrew Trickb7e02892012-06-05 21:11:27 +00001384 // Bypass getHazardType calls in case of long latency.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001385 for (; CurrCycle != NextCycle; ++CurrCycle) {
1386 if (isTop())
1387 HazardRec->AdvanceCycle();
1388 else
1389 HazardRec->RecedeCycle();
1390 }
1391 }
1392 CheckPending = true;
Andrew Trick3b87f622012-11-07 07:05:09 +00001393 IsResourceLimited = getCriticalCount() > std::max(ExpectedLatency, CurrCycle);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001394
Andrew Trick3b87f622012-11-07 07:05:09 +00001395 DEBUG(dbgs() << " *** " << Available.getName() << " cycle "
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001396 << CurrCycle << '\n');
1397}
1398
Andrew Trick3b87f622012-11-07 07:05:09 +00001399/// Add the given processor resource to this scheduled zone.
1400void ConvergingScheduler::SchedBoundary::countResource(unsigned PIdx,
1401 unsigned Cycles) {
1402 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1403 DEBUG(dbgs() << " " << SchedModel->getProcResource(PIdx)->Name
1404 << " +(" << Cycles << "x" << Factor
1405 << ") / " << SchedModel->getLatencyFactor() << '\n');
1406
1407 unsigned Count = Factor * Cycles;
1408 ResourceCounts[PIdx] += Count;
1409 assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
1410 Rem->RemainingCounts[PIdx] -= Count;
1411
Andrew Trick3b87f622012-11-07 07:05:09 +00001412 // Check if this resource exceeds the current critical resource by a full
1413 // cycle. If so, it becomes the critical resource.
1414 if ((int)(ResourceCounts[PIdx] - ResourceCounts[CritResIdx])
1415 >= (int)SchedModel->getLatencyFactor()) {
1416 CritResIdx = PIdx;
1417 DEBUG(dbgs() << " *** Critical resource "
1418 << SchedModel->getProcResource(PIdx)->Name << " x"
1419 << ResourceCounts[PIdx] << '\n');
1420 }
1421}
1422
Andrew Trickb7e02892012-06-05 21:11:27 +00001423/// Move the boundary of scheduled code by one SUnit.
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001424void ConvergingScheduler::SchedBoundary::bumpNode(SUnit *SU) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001425 // Update the reservation table.
1426 if (HazardRec->isEnabled()) {
1427 if (!isTop() && SU->isCall) {
1428 // Calls are scheduled with their preceding instructions. For bottom-up
1429 // scheduling, clear the pipeline state before emitting.
1430 HazardRec->Reset();
1431 }
1432 HazardRec->EmitInstruction(SU);
1433 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001434 // Update resource counts and critical resource.
1435 if (SchedModel->hasInstrSchedModel()) {
1436 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1437 Rem->RemainingMicroOps -= SchedModel->getNumMicroOps(SU->getInstr(), SC);
1438 for (TargetSchedModel::ProcResIter
1439 PI = SchedModel->getWriteProcResBegin(SC),
1440 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1441 countResource(PI->ProcResourceIdx, PI->Cycles);
1442 }
1443 }
1444 if (isTop()) {
1445 if (SU->getDepth() > ExpectedLatency)
1446 ExpectedLatency = SU->getDepth();
1447 }
1448 else {
1449 if (SU->getHeight() > ExpectedLatency)
1450 ExpectedLatency = SU->getHeight();
1451 }
1452
1453 IsResourceLimited = getCriticalCount() > std::max(ExpectedLatency, CurrCycle);
1454
Andrew Trick5559ffa2012-06-29 03:23:24 +00001455 // Check the instruction group dispatch limit.
1456 // TODO: Check if this SU must end a dispatch group.
Andrew Trick412cd2f2012-10-10 05:43:09 +00001457 IssueCount += SchedModel->getNumMicroOps(SU->getInstr());
Andrew Trick3b87f622012-11-07 07:05:09 +00001458
1459 // checkHazard prevents scheduling multiple instructions per cycle that exceed
1460 // issue width. However, we commonly reach the maximum. In this case
1461 // opportunistically bump the cycle to avoid uselessly checking everything in
1462 // the readyQ. Furthermore, a single instruction may produce more than one
1463 // cycle's worth of micro-ops.
Andrew Trick412cd2f2012-10-10 05:43:09 +00001464 if (IssueCount >= SchedModel->getIssueWidth()) {
Andrew Trick3b87f622012-11-07 07:05:09 +00001465 DEBUG(dbgs() << " *** Max instrs at cycle " << CurrCycle << '\n');
Andrew Trickb7e02892012-06-05 21:11:27 +00001466 bumpCycle();
1467 }
1468}
1469
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001470/// Release pending ready nodes in to the available queue. This makes them
1471/// visible to heuristics.
1472void ConvergingScheduler::SchedBoundary::releasePending() {
1473 // If the available queue is empty, it is safe to reset MinReadyCycle.
1474 if (Available.empty())
1475 MinReadyCycle = UINT_MAX;
1476
1477 // Check to see if any of the pending instructions are ready to issue. If
1478 // so, add them to the available queue.
1479 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
1480 SUnit *SU = *(Pending.begin()+i);
Andrew Trickb7e02892012-06-05 21:11:27 +00001481 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001482
1483 if (ReadyCycle < MinReadyCycle)
1484 MinReadyCycle = ReadyCycle;
1485
1486 if (ReadyCycle > CurrCycle)
1487 continue;
1488
Andrew Trick5559ffa2012-06-29 03:23:24 +00001489 if (checkHazard(SU))
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001490 continue;
1491
1492 Available.push(SU);
1493 Pending.remove(Pending.begin()+i);
1494 --i; --e;
1495 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001496 DEBUG(if (!Pending.empty()) Pending.dump());
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001497 CheckPending = false;
1498}
1499
1500/// Remove SU from the ready set for this boundary.
1501void ConvergingScheduler::SchedBoundary::removeReady(SUnit *SU) {
1502 if (Available.isInQueue(SU))
1503 Available.remove(Available.find(SU));
1504 else {
1505 assert(Pending.isInQueue(SU) && "bad ready count");
1506 Pending.remove(Pending.find(SU));
1507 }
1508}
1509
1510/// If this queue only has one ready candidate, return it. As a side effect,
Andrew Trick3b87f622012-11-07 07:05:09 +00001511/// defer any nodes that now hit a hazard, and advance the cycle until at least
1512/// one node is ready. If multiple instructions are ready, return NULL.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001513SUnit *ConvergingScheduler::SchedBoundary::pickOnlyChoice() {
1514 if (CheckPending)
1515 releasePending();
1516
Andrew Trick3b87f622012-11-07 07:05:09 +00001517 if (IssueCount > 0) {
1518 // Defer any ready instrs that now have a hazard.
1519 for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
1520 if (checkHazard(*I)) {
1521 Pending.push(*I);
1522 I = Available.remove(I);
1523 continue;
1524 }
1525 ++I;
1526 }
1527 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001528 for (unsigned i = 0; Available.empty(); ++i) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001529 assert(i <= (HazardRec->getMaxLookAhead() + MaxMinLatency) &&
1530 "permanent hazard"); (void)i;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001531 bumpCycle();
1532 releasePending();
1533 }
1534 if (Available.size() == 1)
1535 return *Available.begin();
1536 return NULL;
1537}
1538
Andrew Trick3b87f622012-11-07 07:05:09 +00001539/// Record the candidate policy for opposite zones with different critical
1540/// resources.
1541///
1542/// If the CriticalZone is latency limited, don't force a policy for the
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001543/// candidates here. Instead, setLatencyPolicy sets ReduceLatency if needed.
Andrew Trick3b87f622012-11-07 07:05:09 +00001544void ConvergingScheduler::balanceZones(
1545 ConvergingScheduler::SchedBoundary &CriticalZone,
1546 ConvergingScheduler::SchedCandidate &CriticalCand,
1547 ConvergingScheduler::SchedBoundary &OppositeZone,
1548 ConvergingScheduler::SchedCandidate &OppositeCand) {
1549
1550 if (!CriticalZone.IsResourceLimited)
1551 return;
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001552 assert(SchedModel->hasInstrSchedModel() && "required schedmodel");
Andrew Trick3b87f622012-11-07 07:05:09 +00001553
1554 SchedRemainder *Rem = CriticalZone.Rem;
1555
1556 // If the critical zone is overconsuming a resource relative to the
1557 // remainder, try to reduce it.
1558 unsigned RemainingCritCount =
1559 Rem->RemainingCounts[CriticalZone.CritResIdx];
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001560 if ((int)(Rem->getMaxRemainingCount(SchedModel) - RemainingCritCount)
Andrew Trick3b87f622012-11-07 07:05:09 +00001561 > (int)SchedModel->getLatencyFactor()) {
1562 CriticalCand.Policy.ReduceResIdx = CriticalZone.CritResIdx;
1563 DEBUG(dbgs() << "Balance " << CriticalZone.Available.getName() << " reduce "
1564 << SchedModel->getProcResource(CriticalZone.CritResIdx)->Name
1565 << '\n');
1566 }
1567 // If the other zone is underconsuming a resource relative to the full zone,
1568 // try to increase it.
1569 unsigned OppositeCount =
1570 OppositeZone.ResourceCounts[CriticalZone.CritResIdx];
1571 if ((int)(OppositeZone.ExpectedCount - OppositeCount)
1572 > (int)SchedModel->getLatencyFactor()) {
1573 OppositeCand.Policy.DemandResIdx = CriticalZone.CritResIdx;
1574 DEBUG(dbgs() << "Balance " << OppositeZone.Available.getName() << " demand "
1575 << SchedModel->getProcResource(OppositeZone.CritResIdx)->Name
1576 << '\n');
1577 }
Andrew Trick28ebc892012-05-10 21:06:19 +00001578}
Andrew Trick3b87f622012-11-07 07:05:09 +00001579
1580/// Determine if the scheduled zones exceed resource limits or critical path and
1581/// set each candidate's ReduceHeight policy accordingly.
1582void ConvergingScheduler::checkResourceLimits(
1583 ConvergingScheduler::SchedCandidate &TopCand,
1584 ConvergingScheduler::SchedCandidate &BotCand) {
1585
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001586 // Set ReduceLatency to true if needed.
Andrew Trickeed4e012013-01-11 17:51:16 +00001587 Bot.setLatencyPolicy(BotCand.Policy);
1588 Top.setLatencyPolicy(TopCand.Policy);
Andrew Trick3b87f622012-11-07 07:05:09 +00001589
1590 // Handle resource-limited regions.
1591 if (Top.IsResourceLimited && Bot.IsResourceLimited
1592 && Top.CritResIdx == Bot.CritResIdx) {
1593 // If the scheduled critical resource in both zones is no longer the
1594 // critical remaining resource, attempt to reduce resource height both ways.
1595 if (Top.CritResIdx != Rem.CritResIdx) {
1596 TopCand.Policy.ReduceResIdx = Top.CritResIdx;
1597 BotCand.Policy.ReduceResIdx = Bot.CritResIdx;
1598 DEBUG(dbgs() << "Reduce scheduled "
1599 << SchedModel->getProcResource(Top.CritResIdx)->Name << '\n');
1600 }
1601 return;
1602 }
1603 // Handle latency-limited regions.
1604 if (!Top.IsResourceLimited && !Bot.IsResourceLimited) {
1605 // If the total scheduled expected latency exceeds the region's critical
1606 // path then reduce latency both ways.
1607 //
1608 // Just because a zone is not resource limited does not mean it is latency
1609 // limited. Unbuffered resource, such as max micro-ops may cause CurrCycle
1610 // to exceed expected latency.
1611 if ((Top.ExpectedLatency + Bot.ExpectedLatency >= Rem.CriticalPath)
1612 && (Rem.CriticalPath > Top.CurrCycle + Bot.CurrCycle)) {
1613 TopCand.Policy.ReduceLatency = true;
1614 BotCand.Policy.ReduceLatency = true;
1615 DEBUG(dbgs() << "Reduce scheduled latency " << Top.ExpectedLatency
1616 << " + " << Bot.ExpectedLatency << '\n');
1617 }
1618 return;
1619 }
1620 // The critical resource is different in each zone, so request balancing.
1621
1622 // Compute the cost of each zone.
Andrew Trick3b87f622012-11-07 07:05:09 +00001623 Top.ExpectedCount = std::max(Top.ExpectedLatency, Top.CurrCycle);
1624 Top.ExpectedCount = std::max(
1625 Top.getCriticalCount(),
1626 Top.ExpectedCount * SchedModel->getLatencyFactor());
1627 Bot.ExpectedCount = std::max(Bot.ExpectedLatency, Bot.CurrCycle);
1628 Bot.ExpectedCount = std::max(
1629 Bot.getCriticalCount(),
1630 Bot.ExpectedCount * SchedModel->getLatencyFactor());
1631
1632 balanceZones(Top, TopCand, Bot, BotCand);
1633 balanceZones(Bot, BotCand, Top, TopCand);
1634}
1635
1636void ConvergingScheduler::SchedCandidate::
1637initResourceDelta(const ScheduleDAGMI *DAG,
1638 const TargetSchedModel *SchedModel) {
1639 if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
1640 return;
1641
1642 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1643 for (TargetSchedModel::ProcResIter
1644 PI = SchedModel->getWriteProcResBegin(SC),
1645 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1646 if (PI->ProcResourceIdx == Policy.ReduceResIdx)
1647 ResDelta.CritResources += PI->Cycles;
1648 if (PI->ProcResourceIdx == Policy.DemandResIdx)
1649 ResDelta.DemandedResources += PI->Cycles;
1650 }
1651}
1652
1653/// Return true if this heuristic determines order.
1654static bool tryLess(unsigned TryVal, unsigned CandVal,
1655 ConvergingScheduler::SchedCandidate &TryCand,
1656 ConvergingScheduler::SchedCandidate &Cand,
1657 ConvergingScheduler::CandReason Reason) {
1658 if (TryVal < CandVal) {
1659 TryCand.Reason = Reason;
1660 return true;
1661 }
1662 if (TryVal > CandVal) {
1663 if (Cand.Reason > Reason)
1664 Cand.Reason = Reason;
1665 return true;
1666 }
1667 return false;
1668}
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001669
Andrew Trick3b87f622012-11-07 07:05:09 +00001670static bool tryGreater(unsigned TryVal, unsigned CandVal,
1671 ConvergingScheduler::SchedCandidate &TryCand,
1672 ConvergingScheduler::SchedCandidate &Cand,
1673 ConvergingScheduler::CandReason Reason) {
1674 if (TryVal > CandVal) {
1675 TryCand.Reason = Reason;
1676 return true;
1677 }
1678 if (TryVal < CandVal) {
1679 if (Cand.Reason > Reason)
1680 Cand.Reason = Reason;
1681 return true;
1682 }
1683 return false;
1684}
1685
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001686static unsigned getWeakLeft(const SUnit *SU, bool isTop) {
1687 return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
1688}
1689
Andrew Trick3b87f622012-11-07 07:05:09 +00001690/// Apply a set of heursitics to a new candidate. Heuristics are currently
1691/// hierarchical. This may be more efficient than a graduated cost model because
1692/// we don't need to evaluate all aspects of the model for each node in the
1693/// queue. But it's really done to make the heuristics easier to debug and
1694/// statistically analyze.
1695///
1696/// \param Cand provides the policy and current best candidate.
1697/// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
1698/// \param Zone describes the scheduled zone that we are extending.
1699/// \param RPTracker describes reg pressure within the scheduled zone.
1700/// \param TempTracker is a scratch pressure tracker to reuse in queries.
1701void ConvergingScheduler::tryCandidate(SchedCandidate &Cand,
1702 SchedCandidate &TryCand,
1703 SchedBoundary &Zone,
1704 const RegPressureTracker &RPTracker,
1705 RegPressureTracker &TempTracker) {
1706
1707 // Always initialize TryCand's RPDelta.
1708 TempTracker.getMaxPressureDelta(TryCand.SU->getInstr(), TryCand.RPDelta,
1709 DAG->getRegionCriticalPSets(),
1710 DAG->getRegPressure().MaxSetPressure);
1711
1712 // Initialize the candidate if needed.
1713 if (!Cand.isValid()) {
1714 TryCand.Reason = NodeOrder;
1715 return;
1716 }
1717 // Avoid exceeding the target's limit.
1718 if (tryLess(TryCand.RPDelta.Excess.UnitIncrease,
1719 Cand.RPDelta.Excess.UnitIncrease, TryCand, Cand, SingleExcess))
1720 return;
1721 if (Cand.Reason == SingleExcess)
1722 Cand.Reason = MultiPressure;
1723
1724 // Avoid increasing the max critical pressure in the scheduled region.
1725 if (tryLess(TryCand.RPDelta.CriticalMax.UnitIncrease,
1726 Cand.RPDelta.CriticalMax.UnitIncrease,
1727 TryCand, Cand, SingleCritical))
1728 return;
1729 if (Cand.Reason == SingleCritical)
1730 Cand.Reason = MultiPressure;
1731
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001732 // Keep clustered nodes together to encourage downstream peephole
1733 // optimizations which may reduce resource requirements.
1734 //
1735 // This is a best effort to set things up for a post-RA pass. Optimizations
1736 // like generating loads of multiple registers should ideally be done within
1737 // the scheduler pass by combining the loads during DAG postprocessing.
1738 const SUnit *NextClusterSU =
1739 Zone.isTop() ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
1740 if (tryGreater(TryCand.SU == NextClusterSU, Cand.SU == NextClusterSU,
1741 TryCand, Cand, Cluster))
1742 return;
1743 // Currently, weak edges are for clustering, so we hard-code that reason.
1744 // However, deferring the current TryCand will not change Cand's reason.
1745 CandReason OrigReason = Cand.Reason;
1746 if (tryLess(getWeakLeft(TryCand.SU, Zone.isTop()),
1747 getWeakLeft(Cand.SU, Zone.isTop()),
1748 TryCand, Cand, Cluster)) {
1749 Cand.Reason = OrigReason;
1750 return;
1751 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001752 // Avoid critical resource consumption and balance the schedule.
1753 TryCand.initResourceDelta(DAG, SchedModel);
1754 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
1755 TryCand, Cand, ResourceReduce))
1756 return;
1757 if (tryGreater(TryCand.ResDelta.DemandedResources,
1758 Cand.ResDelta.DemandedResources,
1759 TryCand, Cand, ResourceDemand))
1760 return;
1761
1762 // Avoid serializing long latency dependence chains.
1763 if (Cand.Policy.ReduceLatency) {
1764 if (Zone.isTop()) {
1765 if (Cand.SU->getDepth() * SchedModel->getLatencyFactor()
1766 > Zone.ExpectedCount) {
1767 if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
1768 TryCand, Cand, TopDepthReduce))
1769 return;
1770 }
1771 if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
1772 TryCand, Cand, TopPathReduce))
1773 return;
1774 }
1775 else {
1776 if (Cand.SU->getHeight() * SchedModel->getLatencyFactor()
1777 > Zone.ExpectedCount) {
1778 if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
1779 TryCand, Cand, BotHeightReduce))
1780 return;
1781 }
1782 if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
1783 TryCand, Cand, BotPathReduce))
1784 return;
1785 }
1786 }
1787
1788 // Avoid increasing the max pressure of the entire region.
1789 if (tryLess(TryCand.RPDelta.CurrentMax.UnitIncrease,
1790 Cand.RPDelta.CurrentMax.UnitIncrease, TryCand, Cand, SingleMax))
1791 return;
1792 if (Cand.Reason == SingleMax)
1793 Cand.Reason = MultiPressure;
1794
1795 // Prefer immediate defs/users of the last scheduled instruction. This is a
1796 // nice pressure avoidance strategy that also conserves the processor's
1797 // register renaming resources and keeps the machine code readable.
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001798 if (tryGreater(Zone.NextSUs.count(TryCand.SU), Zone.NextSUs.count(Cand.SU),
1799 TryCand, Cand, NextDefUse))
Andrew Trick3b87f622012-11-07 07:05:09 +00001800 return;
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001801
Andrew Trick3b87f622012-11-07 07:05:09 +00001802 // Fall through to original instruction order.
1803 if ((Zone.isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
1804 || (!Zone.isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
1805 TryCand.Reason = NodeOrder;
1806 }
1807}
Andrew Trick28ebc892012-05-10 21:06:19 +00001808
Andrew Trick5429a6b2012-05-17 22:37:09 +00001809/// pickNodeFromQueue helper that returns true if the LHS reg pressure effect is
1810/// more desirable than RHS from scheduling standpoint.
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001811static bool compareRPDelta(const RegPressureDelta &LHS,
1812 const RegPressureDelta &RHS) {
1813 // Compare each component of pressure in decreasing order of importance
1814 // without checking if any are valid. Invalid PressureElements are assumed to
1815 // have UnitIncrease==0, so are neutral.
Andrew Trickc8fe4ec2012-05-24 22:11:01 +00001816
1817 // Avoid increasing the max critical pressure in the scheduled region.
Andrew Trick3b87f622012-11-07 07:05:09 +00001818 if (LHS.Excess.UnitIncrease != RHS.Excess.UnitIncrease) {
1819 DEBUG(dbgs() << "RP excess top - bot: "
1820 << (LHS.Excess.UnitIncrease - RHS.Excess.UnitIncrease) << '\n');
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001821 return LHS.Excess.UnitIncrease < RHS.Excess.UnitIncrease;
Andrew Trick3b87f622012-11-07 07:05:09 +00001822 }
Andrew Trickc8fe4ec2012-05-24 22:11:01 +00001823 // Avoid increasing the max critical pressure in the scheduled region.
Andrew Trick3b87f622012-11-07 07:05:09 +00001824 if (LHS.CriticalMax.UnitIncrease != RHS.CriticalMax.UnitIncrease) {
1825 DEBUG(dbgs() << "RP critical top - bot: "
1826 << (LHS.CriticalMax.UnitIncrease - RHS.CriticalMax.UnitIncrease)
1827 << '\n');
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001828 return LHS.CriticalMax.UnitIncrease < RHS.CriticalMax.UnitIncrease;
Andrew Trick3b87f622012-11-07 07:05:09 +00001829 }
Andrew Trickc8fe4ec2012-05-24 22:11:01 +00001830 // Avoid increasing the max pressure of the entire region.
Andrew Trick3b87f622012-11-07 07:05:09 +00001831 if (LHS.CurrentMax.UnitIncrease != RHS.CurrentMax.UnitIncrease) {
1832 DEBUG(dbgs() << "RP current top - bot: "
1833 << (LHS.CurrentMax.UnitIncrease - RHS.CurrentMax.UnitIncrease)
1834 << '\n');
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001835 return LHS.CurrentMax.UnitIncrease < RHS.CurrentMax.UnitIncrease;
Andrew Trick3b87f622012-11-07 07:05:09 +00001836 }
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001837 return false;
1838}
1839
Andrew Trick3b87f622012-11-07 07:05:09 +00001840#ifndef NDEBUG
1841const char *ConvergingScheduler::getReasonStr(
1842 ConvergingScheduler::CandReason Reason) {
1843 switch (Reason) {
1844 case NoCand: return "NOCAND ";
1845 case SingleExcess: return "REG-EXCESS";
1846 case SingleCritical: return "REG-CRIT ";
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001847 case Cluster: return "CLUSTER ";
Andrew Trick3b87f622012-11-07 07:05:09 +00001848 case SingleMax: return "REG-MAX ";
1849 case MultiPressure: return "REG-MULTI ";
1850 case ResourceReduce: return "RES-REDUCE";
1851 case ResourceDemand: return "RES-DEMAND";
1852 case TopDepthReduce: return "TOP-DEPTH ";
1853 case TopPathReduce: return "TOP-PATH ";
1854 case BotHeightReduce:return "BOT-HEIGHT";
1855 case BotPathReduce: return "BOT-PATH ";
1856 case NextDefUse: return "DEF-USE ";
1857 case NodeOrder: return "ORDER ";
1858 };
Benjamin Kramerb7546872012-11-09 15:45:22 +00001859 llvm_unreachable("Unknown reason!");
Andrew Trick3b87f622012-11-07 07:05:09 +00001860}
1861
1862void ConvergingScheduler::traceCandidate(const SchedCandidate &Cand,
1863 const SchedBoundary &Zone) {
1864 const char *Label = getReasonStr(Cand.Reason);
1865 PressureElement P;
1866 unsigned ResIdx = 0;
1867 unsigned Latency = 0;
1868 switch (Cand.Reason) {
1869 default:
1870 break;
1871 case SingleExcess:
1872 P = Cand.RPDelta.Excess;
1873 break;
1874 case SingleCritical:
1875 P = Cand.RPDelta.CriticalMax;
1876 break;
1877 case SingleMax:
1878 P = Cand.RPDelta.CurrentMax;
1879 break;
1880 case ResourceReduce:
1881 ResIdx = Cand.Policy.ReduceResIdx;
1882 break;
1883 case ResourceDemand:
1884 ResIdx = Cand.Policy.DemandResIdx;
1885 break;
1886 case TopDepthReduce:
1887 Latency = Cand.SU->getDepth();
1888 break;
1889 case TopPathReduce:
1890 Latency = Cand.SU->getHeight();
1891 break;
1892 case BotHeightReduce:
1893 Latency = Cand.SU->getHeight();
1894 break;
1895 case BotPathReduce:
1896 Latency = Cand.SU->getDepth();
1897 break;
1898 }
1899 dbgs() << Label << " " << Zone.Available.getName() << " ";
1900 if (P.isValid())
1901 dbgs() << TRI->getRegPressureSetName(P.PSetID) << ":" << P.UnitIncrease
1902 << " ";
1903 else
1904 dbgs() << " ";
1905 if (ResIdx)
1906 dbgs() << SchedModel->getProcResource(ResIdx)->Name << " ";
1907 else
1908 dbgs() << " ";
1909 if (Latency)
1910 dbgs() << Latency << " cycles ";
1911 else
1912 dbgs() << " ";
1913 Cand.SU->dump(DAG);
1914}
1915#endif
1916
Andrew Trick7196a8f2012-05-10 21:06:16 +00001917/// Pick the best candidate from the top queue.
1918///
1919/// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
1920/// DAG building. To adjust for the current scheduling location we need to
1921/// maintain the number of vreg uses remaining to be top-scheduled.
Andrew Trick3b87f622012-11-07 07:05:09 +00001922void ConvergingScheduler::pickNodeFromQueue(SchedBoundary &Zone,
1923 const RegPressureTracker &RPTracker,
1924 SchedCandidate &Cand) {
1925 ReadyQueue &Q = Zone.Available;
1926
Andrew Trickf3234242012-05-24 22:11:12 +00001927 DEBUG(Q.dump());
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001928
Andrew Trick7196a8f2012-05-10 21:06:16 +00001929 // getMaxPressureDelta temporarily modifies the tracker.
1930 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
1931
Andrew Trick8c2d9212012-05-24 22:11:03 +00001932 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
Andrew Trick7196a8f2012-05-10 21:06:16 +00001933
Andrew Trick3b87f622012-11-07 07:05:09 +00001934 SchedCandidate TryCand(Cand.Policy);
1935 TryCand.SU = *I;
1936 tryCandidate(Cand, TryCand, Zone, RPTracker, TempTracker);
1937 if (TryCand.Reason != NoCand) {
1938 // Initialize resource delta if needed in case future heuristics query it.
1939 if (TryCand.ResDelta == SchedResourceDelta())
1940 TryCand.initResourceDelta(DAG, SchedModel);
1941 Cand.setBest(TryCand);
1942 DEBUG(traceCandidate(Cand, Zone));
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001943 }
Andrew Trick7196a8f2012-05-10 21:06:16 +00001944 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001945}
1946
1947static void tracePick(const ConvergingScheduler::SchedCandidate &Cand,
1948 bool IsTop) {
1949 DEBUG(dbgs() << "Pick " << (IsTop ? "top" : "bot")
1950 << " SU(" << Cand.SU->NodeNum << ") "
1951 << ConvergingScheduler::getReasonStr(Cand.Reason) << '\n');
Andrew Trick7196a8f2012-05-10 21:06:16 +00001952}
1953
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001954/// Pick the best candidate node from either the top or bottom queue.
Andrew Trick3b87f622012-11-07 07:05:09 +00001955SUnit *ConvergingScheduler::pickNodeBidirectional(bool &IsTopNode) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001956 // Schedule as far as possible in the direction of no choice. This is most
1957 // efficient, but also provides the best heuristics for CriticalPSets.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001958 if (SUnit *SU = Bot.pickOnlyChoice()) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001959 IsTopNode = false;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001960 return SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001961 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001962 if (SUnit *SU = Top.pickOnlyChoice()) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001963 IsTopNode = true;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001964 return SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001965 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001966 CandPolicy NoPolicy;
1967 SchedCandidate BotCand(NoPolicy);
1968 SchedCandidate TopCand(NoPolicy);
1969 checkResourceLimits(TopCand, BotCand);
1970
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001971 // Prefer bottom scheduling when heuristics are silent.
Andrew Trick3b87f622012-11-07 07:05:09 +00001972 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
1973 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001974
1975 // If either Q has a single candidate that provides the least increase in
1976 // Excess pressure, we can immediately schedule from that Q.
1977 //
1978 // RegionCriticalPSets summarizes the pressure within the scheduled region and
1979 // affects picking from either Q. If scheduling in one direction must
1980 // increase pressure for one of the excess PSets, then schedule in that
1981 // direction first to provide more freedom in the other direction.
Andrew Trick3b87f622012-11-07 07:05:09 +00001982 if (BotCand.Reason == SingleExcess || BotCand.Reason == SingleCritical) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001983 IsTopNode = false;
Andrew Trick3b87f622012-11-07 07:05:09 +00001984 tracePick(BotCand, IsTopNode);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001985 return BotCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001986 }
1987 // Check if the top Q has a better candidate.
Andrew Trick3b87f622012-11-07 07:05:09 +00001988 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
1989 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001990
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001991 // If either Q has a single candidate that minimizes pressure above the
1992 // original region's pressure pick it.
Andrew Trick3b87f622012-11-07 07:05:09 +00001993 if (TopCand.Reason <= SingleMax || BotCand.Reason <= SingleMax) {
1994 if (TopCand.Reason < BotCand.Reason) {
1995 IsTopNode = true;
1996 tracePick(TopCand, IsTopNode);
1997 return TopCand.SU;
1998 }
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001999 IsTopNode = false;
Andrew Trick3b87f622012-11-07 07:05:09 +00002000 tracePick(BotCand, IsTopNode);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002001 return BotCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002002 }
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002003 // Check for a salient pressure difference and pick the best from either side.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002004 if (compareRPDelta(TopCand.RPDelta, BotCand.RPDelta)) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002005 IsTopNode = true;
Andrew Trick3b87f622012-11-07 07:05:09 +00002006 tracePick(TopCand, IsTopNode);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002007 return TopCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002008 }
Andrew Trick3b87f622012-11-07 07:05:09 +00002009 // Otherwise prefer the bottom candidate, in node order if all else failed.
2010 if (TopCand.Reason < BotCand.Reason) {
2011 IsTopNode = true;
2012 tracePick(TopCand, IsTopNode);
2013 return TopCand.SU;
2014 }
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002015 IsTopNode = false;
Andrew Trick3b87f622012-11-07 07:05:09 +00002016 tracePick(BotCand, IsTopNode);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002017 return BotCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002018}
2019
2020/// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
Andrew Trick7196a8f2012-05-10 21:06:16 +00002021SUnit *ConvergingScheduler::pickNode(bool &IsTopNode) {
2022 if (DAG->top() == DAG->bottom()) {
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002023 assert(Top.Available.empty() && Top.Pending.empty() &&
2024 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
Andrew Trick7196a8f2012-05-10 21:06:16 +00002025 return NULL;
2026 }
Andrew Trick7196a8f2012-05-10 21:06:16 +00002027 SUnit *SU;
Andrew Trick30c6ec22012-10-08 18:53:53 +00002028 do {
2029 if (ForceTopDown) {
2030 SU = Top.pickOnlyChoice();
2031 if (!SU) {
Andrew Trick3b87f622012-11-07 07:05:09 +00002032 CandPolicy NoPolicy;
2033 SchedCandidate TopCand(NoPolicy);
2034 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
2035 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick30c6ec22012-10-08 18:53:53 +00002036 SU = TopCand.SU;
2037 }
2038 IsTopNode = true;
Andrew Trick8ddd9d52012-05-24 23:11:17 +00002039 }
Andrew Trick30c6ec22012-10-08 18:53:53 +00002040 else if (ForceBottomUp) {
2041 SU = Bot.pickOnlyChoice();
2042 if (!SU) {
Andrew Trick3b87f622012-11-07 07:05:09 +00002043 CandPolicy NoPolicy;
2044 SchedCandidate BotCand(NoPolicy);
2045 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
2046 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick30c6ec22012-10-08 18:53:53 +00002047 SU = BotCand.SU;
2048 }
2049 IsTopNode = false;
Andrew Trick8ddd9d52012-05-24 23:11:17 +00002050 }
Andrew Trick30c6ec22012-10-08 18:53:53 +00002051 else {
Andrew Trick3b87f622012-11-07 07:05:09 +00002052 SU = pickNodeBidirectional(IsTopNode);
Andrew Trick30c6ec22012-10-08 18:53:53 +00002053 }
2054 } while (SU->isScheduled);
2055
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002056 if (SU->isTopReady())
2057 Top.removeReady(SU);
2058 if (SU->isBottomReady())
2059 Bot.removeReady(SU);
Andrew Trickc7a098f2012-05-25 02:02:39 +00002060
2061 DEBUG(dbgs() << "*** " << (IsTopNode ? "Top" : "Bottom")
2062 << " Scheduling Instruction in cycle "
2063 << (IsTopNode ? Top.CurrCycle : Bot.CurrCycle) << '\n';
2064 SU->dump(DAG));
Andrew Trick7196a8f2012-05-10 21:06:16 +00002065 return SU;
2066}
2067
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002068/// Update the scheduler's state after scheduling a node. This is the same node
2069/// that was just returned by pickNode(). However, ScheduleDAGMI needs to update
Andrew Trickb7e02892012-06-05 21:11:27 +00002070/// it's state based on the current cycle before MachineSchedStrategy does.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002071void ConvergingScheduler::schedNode(SUnit *SU, bool IsTopNode) {
Andrew Trickb7e02892012-06-05 21:11:27 +00002072 if (IsTopNode) {
2073 SU->TopReadyCycle = Top.CurrCycle;
Andrew Trick7f8c74c2012-06-29 03:23:22 +00002074 Top.bumpNode(SU);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002075 }
Andrew Trickb7e02892012-06-05 21:11:27 +00002076 else {
2077 SU->BotReadyCycle = Bot.CurrCycle;
Andrew Trick7f8c74c2012-06-29 03:23:22 +00002078 Bot.bumpNode(SU);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002079 }
2080}
2081
Andrew Trick17d35e52012-03-14 04:00:41 +00002082/// Create the standard converging machine scheduler. This will be used as the
2083/// default scheduler if the target does not set a default.
2084static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C) {
Benjamin Kramer689e0b42012-03-14 11:26:37 +00002085 assert((!ForceTopDown || !ForceBottomUp) &&
Andrew Trick17d35e52012-03-14 04:00:41 +00002086 "-misched-topdown incompatible with -misched-bottomup");
Andrew Trick9b5caaa2012-11-12 19:40:10 +00002087 ScheduleDAGMI *DAG = new ScheduleDAGMI(C, new ConvergingScheduler());
2088 // Register DAG post-processors.
2089 if (EnableLoadCluster)
2090 DAG->addMutation(new LoadClusterMutation(DAG->TII, DAG->TRI));
Andrew Trick6996fd02012-11-12 19:52:20 +00002091 if (EnableMacroFusion)
2092 DAG->addMutation(new MacroFusion(DAG->TII));
Andrew Trick9b5caaa2012-11-12 19:40:10 +00002093 return DAG;
Andrew Trick42b7a712012-01-17 06:55:03 +00002094}
2095static MachineSchedRegistry
Andrew Trick17d35e52012-03-14 04:00:41 +00002096ConvergingSchedRegistry("converge", "Standard converging scheduler.",
2097 createConvergingSched);
Andrew Trick42b7a712012-01-17 06:55:03 +00002098
2099//===----------------------------------------------------------------------===//
Andrew Trick1e94e982012-10-15 18:02:27 +00002100// ILP Scheduler. Currently for experimental analysis of heuristics.
2101//===----------------------------------------------------------------------===//
2102
2103namespace {
2104/// \brief Order nodes by the ILP metric.
2105struct ILPOrder {
Andrew Trick178f7d02013-01-25 04:01:04 +00002106 const SchedDFSResult *DFSResult;
2107 const BitVector *ScheduledTrees;
Andrew Trick1e94e982012-10-15 18:02:27 +00002108 bool MaximizeILP;
2109
Andrew Trick178f7d02013-01-25 04:01:04 +00002110 ILPOrder(bool MaxILP): DFSResult(0), ScheduledTrees(0), MaximizeILP(MaxILP) {}
Andrew Trick1e94e982012-10-15 18:02:27 +00002111
2112 /// \brief Apply a less-than relation on node priority.
Andrew Trick8b1496c2012-11-28 05:13:28 +00002113 ///
2114 /// (Return true if A comes after B in the Q.)
Andrew Trick1e94e982012-10-15 18:02:27 +00002115 bool operator()(const SUnit *A, const SUnit *B) const {
Andrew Trick8b1496c2012-11-28 05:13:28 +00002116 unsigned SchedTreeA = DFSResult->getSubtreeID(A);
2117 unsigned SchedTreeB = DFSResult->getSubtreeID(B);
2118 if (SchedTreeA != SchedTreeB) {
2119 // Unscheduled trees have lower priority.
2120 if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
2121 return ScheduledTrees->test(SchedTreeB);
2122
2123 // Trees with shallower connections have have lower priority.
2124 if (DFSResult->getSubtreeLevel(SchedTreeA)
2125 != DFSResult->getSubtreeLevel(SchedTreeB)) {
2126 return DFSResult->getSubtreeLevel(SchedTreeA)
2127 < DFSResult->getSubtreeLevel(SchedTreeB);
2128 }
2129 }
Andrew Trick1e94e982012-10-15 18:02:27 +00002130 if (MaximizeILP)
Andrew Trick8b1496c2012-11-28 05:13:28 +00002131 return DFSResult->getILP(A) < DFSResult->getILP(B);
Andrew Trick1e94e982012-10-15 18:02:27 +00002132 else
Andrew Trick8b1496c2012-11-28 05:13:28 +00002133 return DFSResult->getILP(A) > DFSResult->getILP(B);
Andrew Trick1e94e982012-10-15 18:02:27 +00002134 }
2135};
2136
2137/// \brief Schedule based on the ILP metric.
2138class ILPScheduler : public MachineSchedStrategy {
Andrew Trick8b1496c2012-11-28 05:13:28 +00002139 /// In case all subtrees are eventually connected to a common root through
2140 /// data dependence (e.g. reduction), place an upper limit on their size.
2141 ///
2142 /// FIXME: A subtree limit is generally good, but in the situation commented
2143 /// above, where multiple similar subtrees feed a common root, we should
2144 /// only split at a point where the resulting subtrees will be balanced.
2145 /// (a motivating test case must be found).
2146 static const unsigned SubtreeLimit = 16;
2147
Andrew Trick178f7d02013-01-25 04:01:04 +00002148 ScheduleDAGMI *DAG;
Andrew Trick1e94e982012-10-15 18:02:27 +00002149 ILPOrder Cmp;
2150
2151 std::vector<SUnit*> ReadyQ;
2152public:
Andrew Trick178f7d02013-01-25 04:01:04 +00002153 ILPScheduler(bool MaximizeILP): DAG(0), Cmp(MaximizeILP) {}
Andrew Trick1e94e982012-10-15 18:02:27 +00002154
Andrew Trick178f7d02013-01-25 04:01:04 +00002155 virtual void initialize(ScheduleDAGMI *dag) {
2156 DAG = dag;
Andrew Trick4e1fb182013-01-25 06:33:57 +00002157 DAG->computeDFSResult();
Andrew Trick178f7d02013-01-25 04:01:04 +00002158 Cmp.DFSResult = DAG->getDFSResult();
2159 Cmp.ScheduledTrees = &DAG->getScheduledTrees();
Andrew Trick1e94e982012-10-15 18:02:27 +00002160 ReadyQ.clear();
Andrew Trick1e94e982012-10-15 18:02:27 +00002161 }
2162
2163 virtual void registerRoots() {
Benjamin Kramer5175fd92012-11-29 14:36:26 +00002164 // Restore the heap in ReadyQ with the updated DFS results.
2165 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
Andrew Trick1e94e982012-10-15 18:02:27 +00002166 }
2167
2168 /// Implement MachineSchedStrategy interface.
2169 /// -----------------------------------------
2170
Andrew Trick8b1496c2012-11-28 05:13:28 +00002171 /// Callback to select the highest priority node from the ready Q.
Andrew Trick1e94e982012-10-15 18:02:27 +00002172 virtual SUnit *pickNode(bool &IsTopNode) {
2173 if (ReadyQ.empty()) return NULL;
2174 pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2175 SUnit *SU = ReadyQ.back();
2176 ReadyQ.pop_back();
2177 IsTopNode = false;
Andrew Trick8b1496c2012-11-28 05:13:28 +00002178 DEBUG(dbgs() << "*** Scheduling " << "SU(" << SU->NodeNum << "): "
2179 << *SU->getInstr()
Andrew Trick178f7d02013-01-25 04:01:04 +00002180 << " ILP: " << DAG->getDFSResult()->getILP(SU)
2181 << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU) << " @"
2182 << DAG->getDFSResult()->getSubtreeLevel(
2183 DAG->getDFSResult()->getSubtreeID(SU)) << '\n');
Andrew Trick1e94e982012-10-15 18:02:27 +00002184 return SU;
2185 }
2186
Andrew Trick178f7d02013-01-25 04:01:04 +00002187 /// \brief Scheduler callback to notify that a new subtree is scheduled.
2188 virtual void scheduleTree(unsigned SubtreeID) {
2189 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2190 }
2191
Andrew Trick8b1496c2012-11-28 05:13:28 +00002192 /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
2193 /// DFSResults, and resort the priority Q.
2194 virtual void schedNode(SUnit *SU, bool IsTopNode) {
2195 assert(!IsTopNode && "SchedDFSResult needs bottom-up");
Andrew Trick8b1496c2012-11-28 05:13:28 +00002196 }
Andrew Trick1e94e982012-10-15 18:02:27 +00002197
2198 virtual void releaseTopNode(SUnit *) { /*only called for top roots*/ }
2199
2200 virtual void releaseBottomNode(SUnit *SU) {
2201 ReadyQ.push_back(SU);
2202 std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2203 }
2204};
2205} // namespace
2206
2207static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
2208 return new ScheduleDAGMI(C, new ILPScheduler(true));
2209}
2210static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
2211 return new ScheduleDAGMI(C, new ILPScheduler(false));
2212}
2213static MachineSchedRegistry ILPMaxRegistry(
2214 "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
2215static MachineSchedRegistry ILPMinRegistry(
2216 "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
2217
2218//===----------------------------------------------------------------------===//
Andrew Trick5edf2f02012-01-14 02:17:06 +00002219// Machine Instruction Shuffler for Correctness Testing
2220//===----------------------------------------------------------------------===//
2221
Andrew Trick96f678f2012-01-13 06:30:30 +00002222#ifndef NDEBUG
2223namespace {
Andrew Trick17d35e52012-03-14 04:00:41 +00002224/// Apply a less-than relation on the node order, which corresponds to the
2225/// instruction order prior to scheduling. IsReverse implements greater-than.
2226template<bool IsReverse>
2227struct SUnitOrder {
Andrew Trickc6cf11b2012-01-17 06:55:07 +00002228 bool operator()(SUnit *A, SUnit *B) const {
Andrew Trick17d35e52012-03-14 04:00:41 +00002229 if (IsReverse)
2230 return A->NodeNum > B->NodeNum;
2231 else
2232 return A->NodeNum < B->NodeNum;
Andrew Trickc6cf11b2012-01-17 06:55:07 +00002233 }
2234};
2235
Andrew Trick96f678f2012-01-13 06:30:30 +00002236/// Reorder instructions as much as possible.
Andrew Trick17d35e52012-03-14 04:00:41 +00002237class InstructionShuffler : public MachineSchedStrategy {
2238 bool IsAlternating;
2239 bool IsTopDown;
2240
2241 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
2242 // gives nodes with a higher number higher priority causing the latest
2243 // instructions to be scheduled first.
2244 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
2245 TopQ;
2246 // When scheduling bottom-up, use greater-than as the queue priority.
2247 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
2248 BottomQ;
Andrew Trick96f678f2012-01-13 06:30:30 +00002249public:
Andrew Trick17d35e52012-03-14 04:00:41 +00002250 InstructionShuffler(bool alternate, bool topdown)
2251 : IsAlternating(alternate), IsTopDown(topdown) {}
Andrew Trick96f678f2012-01-13 06:30:30 +00002252
Andrew Trick17d35e52012-03-14 04:00:41 +00002253 virtual void initialize(ScheduleDAGMI *) {
2254 TopQ.clear();
2255 BottomQ.clear();
2256 }
Andrew Trickc6cf11b2012-01-17 06:55:07 +00002257
Andrew Trick17d35e52012-03-14 04:00:41 +00002258 /// Implement MachineSchedStrategy interface.
2259 /// -----------------------------------------
2260
2261 virtual SUnit *pickNode(bool &IsTopNode) {
2262 SUnit *SU;
2263 if (IsTopDown) {
2264 do {
2265 if (TopQ.empty()) return NULL;
2266 SU = TopQ.top();
2267 TopQ.pop();
2268 } while (SU->isScheduled);
2269 IsTopNode = true;
2270 }
2271 else {
2272 do {
2273 if (BottomQ.empty()) return NULL;
2274 SU = BottomQ.top();
2275 BottomQ.pop();
2276 } while (SU->isScheduled);
2277 IsTopNode = false;
2278 }
2279 if (IsAlternating)
2280 IsTopDown = !IsTopDown;
Andrew Trickc6cf11b2012-01-17 06:55:07 +00002281 return SU;
2282 }
2283
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002284 virtual void schedNode(SUnit *SU, bool IsTopNode) {}
2285
Andrew Trick17d35e52012-03-14 04:00:41 +00002286 virtual void releaseTopNode(SUnit *SU) {
2287 TopQ.push(SU);
2288 }
2289 virtual void releaseBottomNode(SUnit *SU) {
2290 BottomQ.push(SU);
Andrew Trick96f678f2012-01-13 06:30:30 +00002291 }
2292};
2293} // namespace
2294
Andrew Trickc174eaf2012-03-08 01:41:12 +00002295static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
Andrew Trick17d35e52012-03-14 04:00:41 +00002296 bool Alternate = !ForceTopDown && !ForceBottomUp;
2297 bool TopDown = !ForceBottomUp;
Benjamin Kramer689e0b42012-03-14 11:26:37 +00002298 assert((TopDown || !ForceTopDown) &&
Andrew Trick17d35e52012-03-14 04:00:41 +00002299 "-misched-topdown incompatible with -misched-bottomup");
2300 return new ScheduleDAGMI(C, new InstructionShuffler(Alternate, TopDown));
Andrew Trick96f678f2012-01-13 06:30:30 +00002301}
Andrew Trick17d35e52012-03-14 04:00:41 +00002302static MachineSchedRegistry ShufflerRegistry(
2303 "shuffle", "Shuffle machine instructions alternating directions",
2304 createInstructionShuffler);
Andrew Trick96f678f2012-01-13 06:30:30 +00002305#endif // !NDEBUG
Andrew Trick30849792013-01-25 07:45:29 +00002306
2307//===----------------------------------------------------------------------===//
2308// GraphWriter support for ScheduleDAGMI.
2309//===----------------------------------------------------------------------===//
2310
2311#ifndef NDEBUG
2312namespace llvm {
2313
2314template<> struct GraphTraits<
2315 ScheduleDAGMI*> : public GraphTraits<ScheduleDAG*> {};
2316
2317template<>
2318struct DOTGraphTraits<ScheduleDAGMI*> : public DefaultDOTGraphTraits {
2319
2320 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
2321
2322 static std::string getGraphName(const ScheduleDAG *G) {
2323 return G->MF.getName();
2324 }
2325
2326 static bool renderGraphFromBottomUp() {
2327 return true;
2328 }
2329
2330 static bool isNodeHidden(const SUnit *Node) {
2331 return (Node->NumPreds > 10 || Node->NumSuccs > 10);
2332 }
2333
2334 static bool hasNodeAddressLabel(const SUnit *Node,
2335 const ScheduleDAG *Graph) {
2336 return false;
2337 }
2338
2339 /// If you want to override the dot attributes printed for a particular
2340 /// edge, override this method.
2341 static std::string getEdgeAttributes(const SUnit *Node,
2342 SUnitIterator EI,
2343 const ScheduleDAG *Graph) {
2344 if (EI.isArtificialDep())
2345 return "color=cyan,style=dashed";
2346 if (EI.isCtrlDep())
2347 return "color=blue,style=dashed";
2348 return "";
2349 }
2350
2351 static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) {
2352 std::string Str;
2353 raw_string_ostream SS(Str);
2354 SS << "SU(" << SU->NodeNum << ')';
2355 return SS.str();
2356 }
2357 static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G) {
2358 return G->getGraphNodeLabel(SU);
2359 }
2360
2361 static std::string getNodeAttributes(const SUnit *N,
2362 const ScheduleDAG *Graph) {
2363 std::string Str("shape=Mrecord");
2364 const SchedDFSResult *DFS =
2365 static_cast<const ScheduleDAGMI*>(Graph)->getDFSResult();
2366 if (DFS) {
2367 Str += ",style=filled,fillcolor=\"#";
2368 Str += DOT::getColorString(DFS->getSubtreeID(N));
2369 Str += '"';
2370 }
2371 return Str;
2372 }
2373};
2374} // namespace llvm
2375#endif // NDEBUG
2376
2377/// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
2378/// rendered using 'dot'.
2379///
2380void ScheduleDAGMI::viewGraph(const Twine &Name, const Twine &Title) {
2381#ifndef NDEBUG
2382 ViewGraph(this, Name, false, Title);
2383#else
2384 errs() << "ScheduleDAGMI::viewGraph is only available in debug builds on "
2385 << "systems with Graphviz or gv!\n";
2386#endif // NDEBUG
2387}
2388
2389/// Out-of-line implementation with no arguments is handy for gdb.
2390void ScheduleDAGMI::viewGraph() {
2391 viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName());
2392}