blob: b9198e8fc6c3c477202eb8bf12d20709df584796 [file] [log] [blame]
Andrew Trick5429a6b2012-05-17 22:37:09 +00001//===- MachineScheduler.cpp - Machine Instruction Scheduler ---------------===//
Andrew Trick96f678f2012-01-13 06:30:30 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// MachineScheduler schedules machine instructions after phi elimination. It
11// preserves LiveIntervals so it can be invoked before register allocation.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "misched"
16
Andrew Trickc174eaf2012-03-08 01:41:12 +000017#include "llvm/CodeGen/MachineScheduler.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000018#include "llvm/ADT/OwningPtr.h"
19#include "llvm/ADT/PriorityQueue.h"
20#include "llvm/Analysis/AliasAnalysis.h"
21#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000022#include "llvm/CodeGen/Passes.h"
Andrew Trick15252602012-06-06 20:29:31 +000023#include "llvm/CodeGen/RegisterClassInfo.h"
Andrew Trick53e98a22012-11-28 05:13:24 +000024#include "llvm/CodeGen/ScheduleDFS.h"
Andrew Trick0a39d4e2012-05-24 22:11:09 +000025#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000026#include "llvm/Support/CommandLine.h"
27#include "llvm/Support/Debug.h"
28#include "llvm/Support/ErrorHandling.h"
29#include "llvm/Support/raw_ostream.h"
Andrew Trickc6cf11b2012-01-17 06:55:07 +000030#include <queue>
31
Andrew Trick96f678f2012-01-13 06:30:30 +000032using namespace llvm;
33
Andrew Trick78e5efe2012-09-11 00:39:15 +000034namespace llvm {
35cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
36 cl::desc("Force top-down list scheduling"));
37cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
38 cl::desc("Force bottom-up list scheduling"));
39}
Andrew Trick17d35e52012-03-14 04:00:41 +000040
Andrew Trick0df7f882012-03-07 00:18:25 +000041#ifndef NDEBUG
42static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
43 cl::desc("Pop up a window to show MISched dags after they are processed"));
Lang Hames23f1cbb2012-03-19 18:38:38 +000044
45static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
46 cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
Andrew Trick0df7f882012-03-07 00:18:25 +000047#else
48static bool ViewMISchedDAGs = false;
49#endif // NDEBUG
50
Andrew Trick9b5caaa2012-11-12 19:40:10 +000051// Experimental heuristics
52static cl::opt<bool> EnableLoadCluster("misched-cluster", cl::Hidden,
Andrew Trickad1cc1d2012-11-13 08:47:29 +000053 cl::desc("Enable load clustering."), cl::init(true));
Andrew Trick9b5caaa2012-11-12 19:40:10 +000054
Andrew Trick6996fd02012-11-12 19:52:20 +000055// Experimental heuristics
56static cl::opt<bool> EnableMacroFusion("misched-fusion", cl::Hidden,
Andrew Trickad1cc1d2012-11-13 08:47:29 +000057 cl::desc("Enable scheduling for macro fusion."), cl::init(true));
Andrew Trick6996fd02012-11-12 19:52:20 +000058
Andrew Trick5edf2f02012-01-14 02:17:06 +000059//===----------------------------------------------------------------------===//
60// Machine Instruction Scheduling Pass and Registry
61//===----------------------------------------------------------------------===//
62
Andrew Trick86b7e2a2012-04-24 20:36:19 +000063MachineSchedContext::MachineSchedContext():
64 MF(0), MLI(0), MDT(0), PassConfig(0), AA(0), LIS(0) {
65 RegClassInfo = new RegisterClassInfo();
66}
67
68MachineSchedContext::~MachineSchedContext() {
69 delete RegClassInfo;
70}
71
Andrew Trick96f678f2012-01-13 06:30:30 +000072namespace {
Andrew Trick42b7a712012-01-17 06:55:03 +000073/// MachineScheduler runs after coalescing and before register allocation.
Andrew Trickc174eaf2012-03-08 01:41:12 +000074class MachineScheduler : public MachineSchedContext,
75 public MachineFunctionPass {
Andrew Trick96f678f2012-01-13 06:30:30 +000076public:
Andrew Trick42b7a712012-01-17 06:55:03 +000077 MachineScheduler();
Andrew Trick96f678f2012-01-13 06:30:30 +000078
79 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
80
81 virtual void releaseMemory() {}
82
83 virtual bool runOnMachineFunction(MachineFunction&);
84
85 virtual void print(raw_ostream &O, const Module* = 0) const;
86
87 static char ID; // Class identification, replacement for typeinfo
88};
89} // namespace
90
Andrew Trick42b7a712012-01-17 06:55:03 +000091char MachineScheduler::ID = 0;
Andrew Trick96f678f2012-01-13 06:30:30 +000092
Andrew Trick42b7a712012-01-17 06:55:03 +000093char &llvm::MachineSchedulerID = MachineScheduler::ID;
Andrew Trick96f678f2012-01-13 06:30:30 +000094
Andrew Trick42b7a712012-01-17 06:55:03 +000095INITIALIZE_PASS_BEGIN(MachineScheduler, "misched",
Andrew Trick96f678f2012-01-13 06:30:30 +000096 "Machine Instruction Scheduler", false, false)
97INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
98INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
99INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
Andrew Trick42b7a712012-01-17 06:55:03 +0000100INITIALIZE_PASS_END(MachineScheduler, "misched",
Andrew Trick96f678f2012-01-13 06:30:30 +0000101 "Machine Instruction Scheduler", false, false)
102
Andrew Trick42b7a712012-01-17 06:55:03 +0000103MachineScheduler::MachineScheduler()
Andrew Trickc174eaf2012-03-08 01:41:12 +0000104: MachineFunctionPass(ID) {
Andrew Trick42b7a712012-01-17 06:55:03 +0000105 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Andrew Trick96f678f2012-01-13 06:30:30 +0000106}
107
Andrew Trick42b7a712012-01-17 06:55:03 +0000108void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
Andrew Trick96f678f2012-01-13 06:30:30 +0000109 AU.setPreservesCFG();
110 AU.addRequiredID(MachineDominatorsID);
111 AU.addRequired<MachineLoopInfo>();
112 AU.addRequired<AliasAnalysis>();
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000113 AU.addRequired<TargetPassConfig>();
Andrew Trick96f678f2012-01-13 06:30:30 +0000114 AU.addRequired<SlotIndexes>();
115 AU.addPreserved<SlotIndexes>();
116 AU.addRequired<LiveIntervals>();
117 AU.addPreserved<LiveIntervals>();
Andrew Trick96f678f2012-01-13 06:30:30 +0000118 MachineFunctionPass::getAnalysisUsage(AU);
119}
120
Andrew Trick96f678f2012-01-13 06:30:30 +0000121MachinePassRegistry MachineSchedRegistry::Registry;
122
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000123/// A dummy default scheduler factory indicates whether the scheduler
124/// is overridden on the command line.
125static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
126 return 0;
127}
Andrew Trick96f678f2012-01-13 06:30:30 +0000128
129/// MachineSchedOpt allows command line selection of the scheduler.
130static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
131 RegisterPassParser<MachineSchedRegistry> >
132MachineSchedOpt("misched",
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000133 cl::init(&useDefaultMachineSched), cl::Hidden,
Andrew Trick96f678f2012-01-13 06:30:30 +0000134 cl::desc("Machine instruction scheduler to use"));
135
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000136static MachineSchedRegistry
Andrew Trick17d35e52012-03-14 04:00:41 +0000137DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000138 useDefaultMachineSched);
139
Andrew Trick17d35e52012-03-14 04:00:41 +0000140/// Forward declare the standard machine scheduler. This will be used as the
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000141/// default scheduler if the target does not set a default.
Andrew Trick17d35e52012-03-14 04:00:41 +0000142static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C);
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000143
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000144
145/// Decrement this iterator until reaching the top or a non-debug instr.
146static MachineBasicBlock::iterator
147priorNonDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator Beg) {
148 assert(I != Beg && "reached the top of the region, cannot decrement");
149 while (--I != Beg) {
150 if (!I->isDebugValue())
151 break;
152 }
153 return I;
154}
155
156/// If this iterator is a debug value, increment until reaching the End or a
157/// non-debug instruction.
158static MachineBasicBlock::iterator
159nextIfDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator End) {
Andrew Trick811d92682012-05-17 18:35:03 +0000160 for(; I != End; ++I) {
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000161 if (!I->isDebugValue())
162 break;
163 }
164 return I;
165}
166
Andrew Trickcb058d52012-03-14 04:00:38 +0000167/// Top-level MachineScheduler pass driver.
168///
169/// Visit blocks in function order. Divide each block into scheduling regions
Andrew Trick17d35e52012-03-14 04:00:41 +0000170/// and visit them bottom-up. Visiting regions bottom-up is not required, but is
171/// consistent with the DAG builder, which traverses the interior of the
172/// scheduling regions bottom-up.
Andrew Trickcb058d52012-03-14 04:00:38 +0000173///
174/// This design avoids exposing scheduling boundaries to the DAG builder,
Andrew Trick17d35e52012-03-14 04:00:41 +0000175/// simplifying the DAG builder's support for "special" target instructions.
176/// At the same time the design allows target schedulers to operate across
Andrew Trickcb058d52012-03-14 04:00:38 +0000177/// scheduling boundaries, for example to bundle the boudary instructions
178/// without reordering them. This creates complexity, because the target
179/// scheduler must update the RegionBegin and RegionEnd positions cached by
180/// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
181/// design would be to split blocks at scheduling boundaries, but LLVM has a
182/// general bias against block splitting purely for implementation simplicity.
Andrew Trick42b7a712012-01-17 06:55:03 +0000183bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
Andrew Trick89c324b2012-05-10 21:06:21 +0000184 DEBUG(dbgs() << "Before MISsched:\n"; mf.print(dbgs()));
185
Andrew Trick96f678f2012-01-13 06:30:30 +0000186 // Initialize the context of the pass.
187 MF = &mf;
188 MLI = &getAnalysis<MachineLoopInfo>();
189 MDT = &getAnalysis<MachineDominatorTree>();
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000190 PassConfig = &getAnalysis<TargetPassConfig>();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000191 AA = &getAnalysis<AliasAnalysis>();
192
Lang Hames907cc8f2012-01-27 22:36:19 +0000193 LIS = &getAnalysis<LiveIntervals>();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000194 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
Andrew Trick96f678f2012-01-13 06:30:30 +0000195
Andrew Trick86b7e2a2012-04-24 20:36:19 +0000196 RegClassInfo->runOnMachineFunction(*MF);
Andrew Trick006e1ab2012-04-24 17:56:43 +0000197
Andrew Trick96f678f2012-01-13 06:30:30 +0000198 // Select the scheduler, or set the default.
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000199 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
200 if (Ctor == useDefaultMachineSched) {
201 // Get the default scheduler set by the target.
202 Ctor = MachineSchedRegistry::getDefault();
203 if (!Ctor) {
Andrew Trick17d35e52012-03-14 04:00:41 +0000204 Ctor = createConvergingSched;
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000205 MachineSchedRegistry::setDefault(Ctor);
206 }
Andrew Trick96f678f2012-01-13 06:30:30 +0000207 }
208 // Instantiate the selected scheduler.
209 OwningPtr<ScheduleDAGInstrs> Scheduler(Ctor(this));
210
211 // Visit all machine basic blocks.
Andrew Trick006e1ab2012-04-24 17:56:43 +0000212 //
213 // TODO: Visit blocks in global postorder or postorder within the bottom-up
214 // loop tree. Then we can optionally compute global RegPressure.
Andrew Trick96f678f2012-01-13 06:30:30 +0000215 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
216 MBB != MBBEnd; ++MBB) {
217
Andrew Trick1fabd9f2012-03-09 08:02:51 +0000218 Scheduler->startBlock(MBB);
219
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000220 // Break the block into scheduling regions [I, RegionEnd), and schedule each
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +0000221 // region as soon as it is discovered. RegionEnd points the scheduling
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000222 // boundary at the bottom of the region. The DAG does not include RegionEnd,
223 // but the region does (i.e. the next RegionEnd is above the previous
224 // RegionBegin). If the current block has no terminator then RegionEnd ==
225 // MBB->end() for the bottom region.
226 //
227 // The Scheduler may insert instructions during either schedule() or
228 // exitRegion(), even for empty regions. So the local iterators 'I' and
229 // 'RegionEnd' are invalid across these calls.
Andrew Trick22764532012-11-06 07:10:34 +0000230 unsigned RemainingInstrs = MBB->size();
Andrew Trick7799eb42012-03-09 03:46:39 +0000231 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000232 RegionEnd != MBB->begin(); RegionEnd = Scheduler->begin()) {
Andrew Trick006e1ab2012-04-24 17:56:43 +0000233
Andrew Trick1fabd9f2012-03-09 08:02:51 +0000234 // Avoid decrementing RegionEnd for blocks with no terminator.
235 if (RegionEnd != MBB->end()
236 || TII->isSchedulingBoundary(llvm::prior(RegionEnd), MBB, *MF)) {
237 --RegionEnd;
238 // Count the boundary instruction.
Andrew Trick22764532012-11-06 07:10:34 +0000239 --RemainingInstrs;
Andrew Trick1fabd9f2012-03-09 08:02:51 +0000240 }
241
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000242 // The next region starts above the previous region. Look backward in the
243 // instruction stream until we find the nearest boundary.
244 MachineBasicBlock::iterator I = RegionEnd;
Andrew Trick22764532012-11-06 07:10:34 +0000245 for(;I != MBB->begin(); --I, --RemainingInstrs) {
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000246 if (TII->isSchedulingBoundary(llvm::prior(I), MBB, *MF))
247 break;
248 }
Andrew Trick47c14452012-03-07 05:21:52 +0000249 // Notify the scheduler of the region, even if we may skip scheduling
250 // it. Perhaps it still needs to be bundled.
Andrew Trick22764532012-11-06 07:10:34 +0000251 Scheduler->enterRegion(MBB, I, RegionEnd, RemainingInstrs);
Andrew Trick47c14452012-03-07 05:21:52 +0000252
253 // Skip empty scheduling regions (0 or 1 schedulable instructions).
254 if (I == RegionEnd || I == llvm::prior(RegionEnd)) {
Andrew Trick47c14452012-03-07 05:21:52 +0000255 // Close the current region. Bundle the terminator if needed.
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000256 // This invalidates 'RegionEnd' and 'I'.
Andrew Trick47c14452012-03-07 05:21:52 +0000257 Scheduler->exitRegion();
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000258 continue;
Andrew Trick3c58ba82012-01-14 02:17:18 +0000259 }
Andrew Trickbb0a2422012-05-24 22:11:14 +0000260 DEBUG(dbgs() << "********** MI Scheduling **********\n");
Craig Topper96601ca2012-08-22 06:07:19 +0000261 DEBUG(dbgs() << MF->getName()
Andrew Trick291411c2012-02-08 02:17:21 +0000262 << ":BB#" << MBB->getNumber() << "\n From: " << *I << " To: ";
263 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
264 else dbgs() << "End";
Andrew Trick22764532012-11-06 07:10:34 +0000265 dbgs() << " Remaining: " << RemainingInstrs << "\n");
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000266
Andrew Trickd24da972012-03-09 03:46:42 +0000267 // Schedule a region: possibly reorder instructions.
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000268 // This invalidates 'RegionEnd' and 'I'.
Andrew Trick953be892012-03-07 23:00:49 +0000269 Scheduler->schedule();
Andrew Trickd24da972012-03-09 03:46:42 +0000270
271 // Close the current region.
Andrew Trick47c14452012-03-07 05:21:52 +0000272 Scheduler->exitRegion();
273
274 // Scheduling has invalidated the current iterator 'I'. Ask the
275 // scheduler for the top of it's scheduled region.
276 RegionEnd = Scheduler->begin();
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000277 }
Andrew Trick22764532012-11-06 07:10:34 +0000278 assert(RemainingInstrs == 0 && "Instruction count mismatch!");
Andrew Trick953be892012-03-07 23:00:49 +0000279 Scheduler->finishBlock();
Andrew Trick96f678f2012-01-13 06:30:30 +0000280 }
Andrew Trick830da402012-04-01 07:24:23 +0000281 Scheduler->finalizeSchedule();
Andrew Trickaad37f12012-03-21 04:12:12 +0000282 DEBUG(LIS->print(dbgs()));
Andrew Trick96f678f2012-01-13 06:30:30 +0000283 return true;
284}
285
Andrew Trick42b7a712012-01-17 06:55:03 +0000286void MachineScheduler::print(raw_ostream &O, const Module* m) const {
Andrew Trick96f678f2012-01-13 06:30:30 +0000287 // unimplemented
288}
289
Manman Renb720be62012-09-11 22:23:19 +0000290#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Andrew Trick78e5efe2012-09-11 00:39:15 +0000291void ReadyQueue::dump() {
292 dbgs() << Name << ": ";
293 for (unsigned i = 0, e = Queue.size(); i < e; ++i)
294 dbgs() << Queue[i]->NodeNum << " ";
295 dbgs() << "\n";
296}
297#endif
Andrew Trick17d35e52012-03-14 04:00:41 +0000298
299//===----------------------------------------------------------------------===//
300// ScheduleDAGMI - Base class for MachineInstr scheduling with LiveIntervals
301// preservation.
302//===----------------------------------------------------------------------===//
303
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000304bool ScheduleDAGMI::addEdge(SUnit *SuccSU, const SDep &PredDep) {
Andrew Trick6996fd02012-11-12 19:52:20 +0000305 if (SuccSU != &ExitSU) {
306 // Do not use WillCreateCycle, it assumes SD scheduling.
307 // If Pred is reachable from Succ, then the edge creates a cycle.
308 if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
309 return false;
310 Topo.AddPred(SuccSU, PredDep.getSUnit());
311 }
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000312 SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
313 // Return true regardless of whether a new edge needed to be inserted.
314 return true;
315}
316
Andrew Trickc174eaf2012-03-08 01:41:12 +0000317/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
318/// NumPredsLeft reaches zero, release the successor node.
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000319///
320/// FIXME: Adjust SuccSU height based on MinLatency.
Andrew Trick17d35e52012-03-14 04:00:41 +0000321void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
Andrew Trickc174eaf2012-03-08 01:41:12 +0000322 SUnit *SuccSU = SuccEdge->getSUnit();
323
Andrew Trickae692f22012-11-12 19:28:57 +0000324 if (SuccEdge->isWeak()) {
325 --SuccSU->WeakPredsLeft;
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000326 if (SuccEdge->isCluster())
327 NextClusterSucc = SuccSU;
Andrew Trickae692f22012-11-12 19:28:57 +0000328 return;
329 }
Andrew Trickc174eaf2012-03-08 01:41:12 +0000330#ifndef NDEBUG
331 if (SuccSU->NumPredsLeft == 0) {
332 dbgs() << "*** Scheduling failed! ***\n";
333 SuccSU->dump(this);
334 dbgs() << " has been released too many times!\n";
335 llvm_unreachable(0);
336 }
337#endif
338 --SuccSU->NumPredsLeft;
339 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
Andrew Trick17d35e52012-03-14 04:00:41 +0000340 SchedImpl->releaseTopNode(SuccSU);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000341}
342
343/// releaseSuccessors - Call releaseSucc on each of SU's successors.
Andrew Trick17d35e52012-03-14 04:00:41 +0000344void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
Andrew Trickc174eaf2012-03-08 01:41:12 +0000345 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
346 I != E; ++I) {
347 releaseSucc(SU, &*I);
348 }
349}
350
Andrew Trick17d35e52012-03-14 04:00:41 +0000351/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
352/// NumSuccsLeft reaches zero, release the predecessor node.
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000353///
354/// FIXME: Adjust PredSU height based on MinLatency.
Andrew Trick17d35e52012-03-14 04:00:41 +0000355void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
356 SUnit *PredSU = PredEdge->getSUnit();
357
Andrew Trickae692f22012-11-12 19:28:57 +0000358 if (PredEdge->isWeak()) {
359 --PredSU->WeakSuccsLeft;
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000360 if (PredEdge->isCluster())
361 NextClusterPred = PredSU;
Andrew Trickae692f22012-11-12 19:28:57 +0000362 return;
363 }
Andrew Trick17d35e52012-03-14 04:00:41 +0000364#ifndef NDEBUG
365 if (PredSU->NumSuccsLeft == 0) {
366 dbgs() << "*** Scheduling failed! ***\n";
367 PredSU->dump(this);
368 dbgs() << " has been released too many times!\n";
369 llvm_unreachable(0);
370 }
371#endif
372 --PredSU->NumSuccsLeft;
373 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
374 SchedImpl->releaseBottomNode(PredSU);
375}
376
377/// releasePredecessors - Call releasePred on each of SU's predecessors.
378void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
379 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
380 I != E; ++I) {
381 releasePred(SU, &*I);
382 }
383}
384
385void ScheduleDAGMI::moveInstruction(MachineInstr *MI,
386 MachineBasicBlock::iterator InsertPos) {
Andrew Trick811d92682012-05-17 18:35:03 +0000387 // Advance RegionBegin if the first instruction moves down.
Andrew Trick1ce062f2012-03-21 04:12:10 +0000388 if (&*RegionBegin == MI)
Andrew Trick811d92682012-05-17 18:35:03 +0000389 ++RegionBegin;
390
391 // Update the instruction stream.
Andrew Trick17d35e52012-03-14 04:00:41 +0000392 BB->splice(InsertPos, BB, MI);
Andrew Trick811d92682012-05-17 18:35:03 +0000393
394 // Update LiveIntervals
Andrew Trick27c28ce2012-10-16 00:22:51 +0000395 LIS->handleMove(MI, /*UpdateFlags=*/true);
Andrew Trick811d92682012-05-17 18:35:03 +0000396
397 // Recede RegionBegin if an instruction moves above the first.
Andrew Trick17d35e52012-03-14 04:00:41 +0000398 if (RegionBegin == InsertPos)
399 RegionBegin = MI;
400}
401
Andrew Trick0b0d8992012-03-21 04:12:07 +0000402bool ScheduleDAGMI::checkSchedLimit() {
403#ifndef NDEBUG
404 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
405 CurrentTop = CurrentBottom;
406 return false;
407 }
408 ++NumInstrsScheduled;
409#endif
410 return true;
411}
412
Andrew Trick006e1ab2012-04-24 17:56:43 +0000413/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
414/// crossing a scheduling boundary. [begin, end) includes all instructions in
415/// the region, including the boundary itself and single-instruction regions
416/// that don't get scheduled.
417void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
418 MachineBasicBlock::iterator begin,
419 MachineBasicBlock::iterator end,
420 unsigned endcount)
421{
422 ScheduleDAGInstrs::enterRegion(bb, begin, end, endcount);
Andrew Trick7f8ab782012-05-10 21:06:10 +0000423
424 // For convenience remember the end of the liveness region.
425 LiveRegionEnd =
426 (RegionEnd == bb->end()) ? RegionEnd : llvm::next(RegionEnd);
427}
428
429// Setup the register pressure trackers for the top scheduled top and bottom
430// scheduled regions.
431void ScheduleDAGMI::initRegPressure() {
432 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin);
433 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
434
435 // Close the RPTracker to finalize live ins.
436 RPTracker.closeRegion();
437
Andrew Trickbb0a2422012-05-24 22:11:14 +0000438 DEBUG(RPTracker.getPressure().dump(TRI));
439
Andrew Trick7f8ab782012-05-10 21:06:10 +0000440 // Initialize the live ins and live outs.
441 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
442 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
443
444 // Close one end of the tracker so we can call
445 // getMaxUpward/DownwardPressureDelta before advancing across any
446 // instructions. This converts currently live regs into live ins/outs.
447 TopRPTracker.closeTop();
448 BotRPTracker.closeBottom();
449
450 // Account for liveness generated by the region boundary.
451 if (LiveRegionEnd != RegionEnd)
452 BotRPTracker.recede();
453
454 assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000455
456 // Cache the list of excess pressure sets in this region. This will also track
457 // the max pressure in the scheduled code for these sets.
458 RegionCriticalPSets.clear();
459 std::vector<unsigned> RegionPressure = RPTracker.getPressure().MaxSetPressure;
460 for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
461 unsigned Limit = TRI->getRegPressureSetLimit(i);
Andrew Trick78e5efe2012-09-11 00:39:15 +0000462 DEBUG(dbgs() << TRI->getRegPressureSetName(i)
463 << "Limit " << Limit
464 << " Actual " << RegionPressure[i] << "\n");
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000465 if (RegionPressure[i] > Limit)
466 RegionCriticalPSets.push_back(PressureElement(i, 0));
467 }
468 DEBUG(dbgs() << "Excess PSets: ";
469 for (unsigned i = 0, e = RegionCriticalPSets.size(); i != e; ++i)
470 dbgs() << TRI->getRegPressureSetName(
471 RegionCriticalPSets[i].PSetID) << " ";
472 dbgs() << "\n");
473}
474
475// FIXME: When the pressure tracker deals in pressure differences then we won't
476// iterate over all RegionCriticalPSets[i].
477void ScheduleDAGMI::
478updateScheduledPressure(std::vector<unsigned> NewMaxPressure) {
479 for (unsigned i = 0, e = RegionCriticalPSets.size(); i < e; ++i) {
480 unsigned ID = RegionCriticalPSets[i].PSetID;
481 int &MaxUnits = RegionCriticalPSets[i].UnitIncrease;
482 if ((int)NewMaxPressure[ID] > MaxUnits)
483 MaxUnits = NewMaxPressure[ID];
484 }
Andrew Trick006e1ab2012-04-24 17:56:43 +0000485}
486
Andrew Trick17d35e52012-03-14 04:00:41 +0000487/// schedule - Called back from MachineScheduler::runOnMachineFunction
Andrew Trick006e1ab2012-04-24 17:56:43 +0000488/// after setting up the current scheduling region. [RegionBegin, RegionEnd)
489/// only includes instructions that have DAG nodes, not scheduling boundaries.
Andrew Trick78e5efe2012-09-11 00:39:15 +0000490///
491/// This is a skeletal driver, with all the functionality pushed into helpers,
492/// so that it can be easilly extended by experimental schedulers. Generally,
493/// implementing MachineSchedStrategy should be sufficient to implement a new
494/// scheduling algorithm. However, if a scheduler further subclasses
495/// ScheduleDAGMI then it will want to override this virtual method in order to
496/// update any specialized state.
Andrew Trick17d35e52012-03-14 04:00:41 +0000497void ScheduleDAGMI::schedule() {
Andrew Trick78e5efe2012-09-11 00:39:15 +0000498 buildDAGWithRegPressure();
499
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000500 Topo.InitDAGTopologicalSorting();
501
Andrew Trickd039b382012-09-14 17:22:42 +0000502 postprocessDAG();
503
Andrew Trick78e5efe2012-09-11 00:39:15 +0000504 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
505 SUnits[su].dumpAll(this));
506
507 if (ViewMISchedDAGs) viewGraph();
508
509 initQueues();
510
511 bool IsTopNode = false;
512 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
Andrew Trick30c6ec22012-10-08 18:53:53 +0000513 assert(!SU->isScheduled && "Node already scheduled");
Andrew Trick78e5efe2012-09-11 00:39:15 +0000514 if (!checkSchedLimit())
515 break;
516
517 scheduleMI(SU, IsTopNode);
518
519 updateQueues(SU, IsTopNode);
520 }
521 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
522
523 placeDebugValues();
Andrew Trick3b87f622012-11-07 07:05:09 +0000524
525 DEBUG({
Andrew Trickb4221042012-11-28 03:42:47 +0000526 unsigned BBNum = begin()->getParent()->getNumber();
Andrew Trick3b87f622012-11-07 07:05:09 +0000527 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
528 dumpSchedule();
529 dbgs() << '\n';
530 });
Andrew Trick78e5efe2012-09-11 00:39:15 +0000531}
532
533/// Build the DAG and setup three register pressure trackers.
534void ScheduleDAGMI::buildDAGWithRegPressure() {
Andrew Trick7f8ab782012-05-10 21:06:10 +0000535 // Initialize the register pressure tracker used by buildSchedGraph.
536 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
Andrew Trick006e1ab2012-04-24 17:56:43 +0000537
Andrew Trick7f8ab782012-05-10 21:06:10 +0000538 // Account for liveness generate by the region boundary.
539 if (LiveRegionEnd != RegionEnd)
540 RPTracker.recede();
541
542 // Build the DAG, and compute current register pressure.
Andrew Trick006e1ab2012-04-24 17:56:43 +0000543 buildSchedGraph(AA, &RPTracker);
Andrew Trick78e5efe2012-09-11 00:39:15 +0000544 if (ViewMISchedDAGs) viewGraph();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000545
Andrew Trick7f8ab782012-05-10 21:06:10 +0000546 // Initialize top/bottom trackers after computing region pressure.
547 initRegPressure();
Andrew Trick78e5efe2012-09-11 00:39:15 +0000548}
Andrew Trick7f8ab782012-05-10 21:06:10 +0000549
Andrew Trickd039b382012-09-14 17:22:42 +0000550/// Apply each ScheduleDAGMutation step in order.
551void ScheduleDAGMI::postprocessDAG() {
552 for (unsigned i = 0, e = Mutations.size(); i < e; ++i) {
553 Mutations[i]->apply(this);
554 }
555}
556
Andrew Trick1e94e982012-10-15 18:02:27 +0000557// Release all DAG roots for scheduling.
Andrew Trickae692f22012-11-12 19:28:57 +0000558//
559// Nodes with unreleased weak edges can still be roots.
Andrew Trick1e94e982012-10-15 18:02:27 +0000560void ScheduleDAGMI::releaseRoots() {
561 SmallVector<SUnit*, 16> BotRoots;
562
563 for (std::vector<SUnit>::iterator
564 I = SUnits.begin(), E = SUnits.end(); I != E; ++I) {
Andrew Trickae692f22012-11-12 19:28:57 +0000565 SUnit *SU = &(*I);
Andrew Trickdb417062013-01-24 02:09:57 +0000566
567 // Order predecessors so DFSResult follows the critical path.
568 SU->biasCriticalPath();
569
Andrew Trick1e94e982012-10-15 18:02:27 +0000570 // A SUnit is ready to top schedule if it has no predecessors.
Andrew Trickae692f22012-11-12 19:28:57 +0000571 if (!I->NumPredsLeft && SU != &EntrySU)
572 SchedImpl->releaseTopNode(SU);
Andrew Trick1e94e982012-10-15 18:02:27 +0000573 // A SUnit is ready to bottom schedule if it has no successors.
Andrew Trickae692f22012-11-12 19:28:57 +0000574 if (!I->NumSuccsLeft && SU != &ExitSU)
575 BotRoots.push_back(SU);
Andrew Trick1e94e982012-10-15 18:02:27 +0000576 }
577 // Release bottom roots in reverse order so the higher priority nodes appear
578 // first. This is more natural and slightly more efficient.
579 for (SmallVectorImpl<SUnit*>::const_reverse_iterator
580 I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I)
581 SchedImpl->releaseBottomNode(*I);
582}
583
Andrew Trick78e5efe2012-09-11 00:39:15 +0000584/// Identify DAG roots and setup scheduler queues.
585void ScheduleDAGMI::initQueues() {
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000586 NextClusterSucc = NULL;
587 NextClusterPred = NULL;
Andrew Trick1e94e982012-10-15 18:02:27 +0000588
Andrew Trick78e5efe2012-09-11 00:39:15 +0000589 // Initialize the strategy before modifying the DAG.
Andrew Trick17d35e52012-03-14 04:00:41 +0000590 SchedImpl->initialize(this);
591
Andrew Trickae692f22012-11-12 19:28:57 +0000592 // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
593 releaseRoots();
594
Andrew Trickc174eaf2012-03-08 01:41:12 +0000595 releaseSuccessors(&EntrySU);
Andrew Trick17d35e52012-03-14 04:00:41 +0000596 releasePredecessors(&ExitSU);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000597
Andrew Trick1e94e982012-10-15 18:02:27 +0000598 SchedImpl->registerRoots();
599
Andrew Trick657b75b2012-12-01 01:22:49 +0000600 // Advance past initial DebugValues.
601 assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000602 CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
Andrew Trick657b75b2012-12-01 01:22:49 +0000603 TopRPTracker.setPos(CurrentTop);
604
Andrew Trick17d35e52012-03-14 04:00:41 +0000605 CurrentBottom = RegionEnd;
Andrew Trick78e5efe2012-09-11 00:39:15 +0000606}
Andrew Trickc174eaf2012-03-08 01:41:12 +0000607
Andrew Trick78e5efe2012-09-11 00:39:15 +0000608/// Move an instruction and update register pressure.
609void ScheduleDAGMI::scheduleMI(SUnit *SU, bool IsTopNode) {
610 // Move the instruction to its new location in the instruction stream.
611 MachineInstr *MI = SU->getInstr();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000612
Andrew Trick78e5efe2012-09-11 00:39:15 +0000613 if (IsTopNode) {
614 assert(SU->isTopReady() && "node still has unscheduled dependencies");
615 if (&*CurrentTop == MI)
616 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
Andrew Trick17d35e52012-03-14 04:00:41 +0000617 else {
Andrew Trick78e5efe2012-09-11 00:39:15 +0000618 moveInstruction(MI, CurrentTop);
619 TopRPTracker.setPos(MI);
Andrew Trick17d35e52012-03-14 04:00:41 +0000620 }
Andrew Trick000b2502012-04-24 18:04:37 +0000621
Andrew Trick78e5efe2012-09-11 00:39:15 +0000622 // Update top scheduled pressure.
623 TopRPTracker.advance();
624 assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
625 updateScheduledPressure(TopRPTracker.getPressure().MaxSetPressure);
626 }
627 else {
628 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
629 MachineBasicBlock::iterator priorII =
630 priorNonDebug(CurrentBottom, CurrentTop);
631 if (&*priorII == MI)
632 CurrentBottom = priorII;
633 else {
634 if (&*CurrentTop == MI) {
635 CurrentTop = nextIfDebug(++CurrentTop, priorII);
636 TopRPTracker.setPos(CurrentTop);
637 }
638 moveInstruction(MI, CurrentBottom);
639 CurrentBottom = MI;
640 }
641 // Update bottom scheduled pressure.
642 BotRPTracker.recede();
643 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
644 updateScheduledPressure(BotRPTracker.getPressure().MaxSetPressure);
645 }
646}
647
648/// Update scheduler queues after scheduling an instruction.
649void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
650 // Release dependent instructions for scheduling.
651 if (IsTopNode)
652 releaseSuccessors(SU);
653 else
654 releasePredecessors(SU);
655
656 SU->isScheduled = true;
657
658 // Notify the scheduling strategy after updating the DAG.
659 SchedImpl->schedNode(SU, IsTopNode);
Andrew Trick000b2502012-04-24 18:04:37 +0000660}
661
662/// Reinsert any remaining debug_values, just like the PostRA scheduler.
663void ScheduleDAGMI::placeDebugValues() {
664 // If first instruction was a DBG_VALUE then put it back.
665 if (FirstDbgValue) {
666 BB->splice(RegionBegin, BB, FirstDbgValue);
667 RegionBegin = FirstDbgValue;
668 }
669
670 for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
671 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
672 std::pair<MachineInstr *, MachineInstr *> P = *prior(DI);
673 MachineInstr *DbgValue = P.first;
674 MachineBasicBlock::iterator OrigPrevMI = P.second;
Andrew Trick67bdd422012-12-01 01:22:38 +0000675 if (&*RegionBegin == DbgValue)
676 ++RegionBegin;
Andrew Trick000b2502012-04-24 18:04:37 +0000677 BB->splice(++OrigPrevMI, BB, DbgValue);
678 if (OrigPrevMI == llvm::prior(RegionEnd))
679 RegionEnd = DbgValue;
680 }
681 DbgValues.clear();
682 FirstDbgValue = NULL;
Andrew Trickc174eaf2012-03-08 01:41:12 +0000683}
684
Andrew Trick3b87f622012-11-07 07:05:09 +0000685#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
686void ScheduleDAGMI::dumpSchedule() const {
687 for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
688 if (SUnit *SU = getSUnit(&(*MI)))
689 SU->dump(this);
690 else
691 dbgs() << "Missing SUnit\n";
692 }
693}
694#endif
695
Andrew Trick6996fd02012-11-12 19:52:20 +0000696//===----------------------------------------------------------------------===//
697// LoadClusterMutation - DAG post-processing to cluster loads.
698//===----------------------------------------------------------------------===//
699
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000700namespace {
701/// \brief Post-process the DAG to create cluster edges between neighboring
702/// loads.
703class LoadClusterMutation : public ScheduleDAGMutation {
704 struct LoadInfo {
705 SUnit *SU;
706 unsigned BaseReg;
707 unsigned Offset;
708 LoadInfo(SUnit *su, unsigned reg, unsigned ofs)
709 : SU(su), BaseReg(reg), Offset(ofs) {}
710 };
711 static bool LoadInfoLess(const LoadClusterMutation::LoadInfo &LHS,
712 const LoadClusterMutation::LoadInfo &RHS);
713
714 const TargetInstrInfo *TII;
715 const TargetRegisterInfo *TRI;
716public:
717 LoadClusterMutation(const TargetInstrInfo *tii,
718 const TargetRegisterInfo *tri)
719 : TII(tii), TRI(tri) {}
720
721 virtual void apply(ScheduleDAGMI *DAG);
722protected:
723 void clusterNeighboringLoads(ArrayRef<SUnit*> Loads, ScheduleDAGMI *DAG);
724};
725} // anonymous
726
727bool LoadClusterMutation::LoadInfoLess(
728 const LoadClusterMutation::LoadInfo &LHS,
729 const LoadClusterMutation::LoadInfo &RHS) {
730 if (LHS.BaseReg != RHS.BaseReg)
731 return LHS.BaseReg < RHS.BaseReg;
732 return LHS.Offset < RHS.Offset;
733}
734
735void LoadClusterMutation::clusterNeighboringLoads(ArrayRef<SUnit*> Loads,
736 ScheduleDAGMI *DAG) {
737 SmallVector<LoadClusterMutation::LoadInfo,32> LoadRecords;
738 for (unsigned Idx = 0, End = Loads.size(); Idx != End; ++Idx) {
739 SUnit *SU = Loads[Idx];
740 unsigned BaseReg;
741 unsigned Offset;
742 if (TII->getLdStBaseRegImmOfs(SU->getInstr(), BaseReg, Offset, TRI))
743 LoadRecords.push_back(LoadInfo(SU, BaseReg, Offset));
744 }
745 if (LoadRecords.size() < 2)
746 return;
747 std::sort(LoadRecords.begin(), LoadRecords.end(), LoadInfoLess);
748 unsigned ClusterLength = 1;
749 for (unsigned Idx = 0, End = LoadRecords.size(); Idx < (End - 1); ++Idx) {
750 if (LoadRecords[Idx].BaseReg != LoadRecords[Idx+1].BaseReg) {
751 ClusterLength = 1;
752 continue;
753 }
754
755 SUnit *SUa = LoadRecords[Idx].SU;
756 SUnit *SUb = LoadRecords[Idx+1].SU;
Andrew Tricka7d2d562012-11-12 21:28:10 +0000757 if (TII->shouldClusterLoads(SUa->getInstr(), SUb->getInstr(), ClusterLength)
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000758 && DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
759
760 DEBUG(dbgs() << "Cluster loads SU(" << SUa->NodeNum << ") - SU("
761 << SUb->NodeNum << ")\n");
762 // Copy successor edges from SUa to SUb. Interleaving computation
763 // dependent on SUa can prevent load combining due to register reuse.
764 // Predecessor edges do not need to be copied from SUb to SUa since nearby
765 // loads should have effectively the same inputs.
766 for (SUnit::const_succ_iterator
767 SI = SUa->Succs.begin(), SE = SUa->Succs.end(); SI != SE; ++SI) {
768 if (SI->getSUnit() == SUb)
769 continue;
770 DEBUG(dbgs() << " Copy Succ SU(" << SI->getSUnit()->NodeNum << ")\n");
771 DAG->addEdge(SI->getSUnit(), SDep(SUb, SDep::Artificial));
772 }
773 ++ClusterLength;
774 }
775 else
776 ClusterLength = 1;
777 }
778}
779
780/// \brief Callback from DAG postProcessing to create cluster edges for loads.
781void LoadClusterMutation::apply(ScheduleDAGMI *DAG) {
782 // Map DAG NodeNum to store chain ID.
783 DenseMap<unsigned, unsigned> StoreChainIDs;
784 // Map each store chain to a set of dependent loads.
785 SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
786 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
787 SUnit *SU = &DAG->SUnits[Idx];
788 if (!SU->getInstr()->mayLoad())
789 continue;
790 unsigned ChainPredID = DAG->SUnits.size();
791 for (SUnit::const_pred_iterator
792 PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
793 if (PI->isCtrl()) {
794 ChainPredID = PI->getSUnit()->NodeNum;
795 break;
796 }
797 }
798 // Check if this chain-like pred has been seen
799 // before. ChainPredID==MaxNodeID for loads at the top of the schedule.
800 unsigned NumChains = StoreChainDependents.size();
801 std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
802 StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
803 if (Result.second)
804 StoreChainDependents.resize(NumChains + 1);
805 StoreChainDependents[Result.first->second].push_back(SU);
806 }
807 // Iterate over the store chains.
808 for (unsigned Idx = 0, End = StoreChainDependents.size(); Idx != End; ++Idx)
809 clusterNeighboringLoads(StoreChainDependents[Idx], DAG);
810}
811
Andrew Trickc174eaf2012-03-08 01:41:12 +0000812//===----------------------------------------------------------------------===//
Andrew Trick6996fd02012-11-12 19:52:20 +0000813// MacroFusion - DAG post-processing to encourage fusion of macro ops.
814//===----------------------------------------------------------------------===//
815
816namespace {
817/// \brief Post-process the DAG to create cluster edges between instructions
818/// that may be fused by the processor into a single operation.
819class MacroFusion : public ScheduleDAGMutation {
820 const TargetInstrInfo *TII;
821public:
822 MacroFusion(const TargetInstrInfo *tii): TII(tii) {}
823
824 virtual void apply(ScheduleDAGMI *DAG);
825};
826} // anonymous
827
828/// \brief Callback from DAG postProcessing to create cluster edges to encourage
829/// fused operations.
830void MacroFusion::apply(ScheduleDAGMI *DAG) {
831 // For now, assume targets can only fuse with the branch.
832 MachineInstr *Branch = DAG->ExitSU.getInstr();
833 if (!Branch)
834 return;
835
836 for (unsigned Idx = DAG->SUnits.size(); Idx > 0;) {
837 SUnit *SU = &DAG->SUnits[--Idx];
838 if (!TII->shouldScheduleAdjacent(SU->getInstr(), Branch))
839 continue;
840
841 // Create a single weak edge from SU to ExitSU. The only effect is to cause
842 // bottom-up scheduling to heavily prioritize the clustered SU. There is no
843 // need to copy predecessor edges from ExitSU to SU, since top-down
844 // scheduling cannot prioritize ExitSU anyway. To defer top-down scheduling
845 // of SU, we could create an artificial edge from the deepest root, but it
846 // hasn't been needed yet.
847 bool Success = DAG->addEdge(&DAG->ExitSU, SDep(SU, SDep::Cluster));
848 (void)Success;
849 assert(Success && "No DAG nodes should be reachable from ExitSU");
850
851 DEBUG(dbgs() << "Macro Fuse SU(" << SU->NodeNum << ")\n");
852 break;
853 }
854}
855
856//===----------------------------------------------------------------------===//
Andrew Trick17d35e52012-03-14 04:00:41 +0000857// ConvergingScheduler - Implementation of the standard MachineSchedStrategy.
Andrew Trick42b7a712012-01-17 06:55:03 +0000858//===----------------------------------------------------------------------===//
859
860namespace {
Andrew Trick17d35e52012-03-14 04:00:41 +0000861/// ConvergingScheduler shrinks the unscheduled zone using heuristics to balance
862/// the schedule.
863class ConvergingScheduler : public MachineSchedStrategy {
Andrew Trick3b87f622012-11-07 07:05:09 +0000864public:
865 /// Represent the type of SchedCandidate found within a single queue.
866 /// pickNodeBidirectional depends on these listed by decreasing priority.
867 enum CandReason {
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000868 NoCand, SingleExcess, SingleCritical, Cluster,
869 ResourceReduce, ResourceDemand, BotHeightReduce, BotPathReduce,
870 TopDepthReduce, TopPathReduce, SingleMax, MultiPressure, NextDefUse,
871 NodeOrder};
Andrew Trick3b87f622012-11-07 07:05:09 +0000872
873#ifndef NDEBUG
874 static const char *getReasonStr(ConvergingScheduler::CandReason Reason);
875#endif
876
877 /// Policy for scheduling the next instruction in the candidate's zone.
878 struct CandPolicy {
879 bool ReduceLatency;
880 unsigned ReduceResIdx;
881 unsigned DemandResIdx;
882
883 CandPolicy(): ReduceLatency(false), ReduceResIdx(0), DemandResIdx(0) {}
884 };
885
886 /// Status of an instruction's critical resource consumption.
887 struct SchedResourceDelta {
888 // Count critical resources in the scheduled region required by SU.
889 unsigned CritResources;
890
891 // Count critical resources from another region consumed by SU.
892 unsigned DemandedResources;
893
894 SchedResourceDelta(): CritResources(0), DemandedResources(0) {}
895
896 bool operator==(const SchedResourceDelta &RHS) const {
897 return CritResources == RHS.CritResources
898 && DemandedResources == RHS.DemandedResources;
899 }
900 bool operator!=(const SchedResourceDelta &RHS) const {
901 return !operator==(RHS);
902 }
903 };
Andrew Trick7196a8f2012-05-10 21:06:16 +0000904
905 /// Store the state used by ConvergingScheduler heuristics, required for the
906 /// lifetime of one invocation of pickNode().
907 struct SchedCandidate {
Andrew Trick3b87f622012-11-07 07:05:09 +0000908 CandPolicy Policy;
909
Andrew Trick7196a8f2012-05-10 21:06:16 +0000910 // The best SUnit candidate.
911 SUnit *SU;
912
Andrew Trick3b87f622012-11-07 07:05:09 +0000913 // The reason for this candidate.
914 CandReason Reason;
915
Andrew Trick7196a8f2012-05-10 21:06:16 +0000916 // Register pressure values for the best candidate.
917 RegPressureDelta RPDelta;
918
Andrew Trick3b87f622012-11-07 07:05:09 +0000919 // Critical resource consumption of the best candidate.
920 SchedResourceDelta ResDelta;
921
922 SchedCandidate(const CandPolicy &policy)
923 : Policy(policy), SU(NULL), Reason(NoCand) {}
924
925 bool isValid() const { return SU; }
926
927 // Copy the status of another candidate without changing policy.
928 void setBest(SchedCandidate &Best) {
929 assert(Best.Reason != NoCand && "uninitialized Sched candidate");
930 SU = Best.SU;
931 Reason = Best.Reason;
932 RPDelta = Best.RPDelta;
933 ResDelta = Best.ResDelta;
934 }
935
936 void initResourceDelta(const ScheduleDAGMI *DAG,
937 const TargetSchedModel *SchedModel);
Andrew Trick7196a8f2012-05-10 21:06:16 +0000938 };
Andrew Trick3b87f622012-11-07 07:05:09 +0000939
940 /// Summarize the unscheduled region.
941 struct SchedRemainder {
942 // Critical path through the DAG in expected latency.
943 unsigned CriticalPath;
944
945 // Unscheduled resources
946 SmallVector<unsigned, 16> RemainingCounts;
947 // Critical resource for the unscheduled zone.
948 unsigned CritResIdx;
949 // Number of micro-ops left to schedule.
950 unsigned RemainingMicroOps;
Andrew Trick3b87f622012-11-07 07:05:09 +0000951
Andrew Trick3b87f622012-11-07 07:05:09 +0000952 void reset() {
953 CriticalPath = 0;
954 RemainingCounts.clear();
955 CritResIdx = 0;
956 RemainingMicroOps = 0;
Andrew Trick3b87f622012-11-07 07:05:09 +0000957 }
958
959 SchedRemainder() { reset(); }
960
961 void init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel);
Andrew Trick44fd0bc2012-12-18 20:52:56 +0000962
963 unsigned getMaxRemainingCount(const TargetSchedModel *SchedModel) const {
964 if (!SchedModel->hasInstrSchedModel())
965 return 0;
966
967 return std::max(
968 RemainingMicroOps * SchedModel->getMicroOpFactor(),
969 RemainingCounts[CritResIdx]);
970 }
Andrew Trick3b87f622012-11-07 07:05:09 +0000971 };
Andrew Trick7196a8f2012-05-10 21:06:16 +0000972
Andrew Trickf3234242012-05-24 22:11:12 +0000973 /// Each Scheduling boundary is associated with ready queues. It tracks the
Andrew Trick3b87f622012-11-07 07:05:09 +0000974 /// current cycle in the direction of movement, and maintains the state
Andrew Trickf3234242012-05-24 22:11:12 +0000975 /// of "hazards" and other interlocks at the current cycle.
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000976 struct SchedBoundary {
Andrew Trick7f8c74c2012-06-29 03:23:22 +0000977 ScheduleDAGMI *DAG;
Andrew Trick412cd2f2012-10-10 05:43:09 +0000978 const TargetSchedModel *SchedModel;
Andrew Trick3b87f622012-11-07 07:05:09 +0000979 SchedRemainder *Rem;
Andrew Trick7f8c74c2012-06-29 03:23:22 +0000980
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000981 ReadyQueue Available;
982 ReadyQueue Pending;
983 bool CheckPending;
984
Andrew Trick3b87f622012-11-07 07:05:09 +0000985 // For heuristics, keep a list of the nodes that immediately depend on the
986 // most recently scheduled node.
987 SmallPtrSet<const SUnit*, 8> NextSUs;
988
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000989 ScheduleHazardRecognizer *HazardRec;
990
991 unsigned CurrCycle;
992 unsigned IssueCount;
993
994 /// MinReadyCycle - Cycle of the soonest available instruction.
995 unsigned MinReadyCycle;
996
Andrew Trick3b87f622012-11-07 07:05:09 +0000997 // The expected latency of the critical path in this scheduled zone.
998 unsigned ExpectedLatency;
999
1000 // Resources used in the scheduled zone beyond this boundary.
1001 SmallVector<unsigned, 16> ResourceCounts;
1002
1003 // Cache the critical resources ID in this scheduled zone.
1004 unsigned CritResIdx;
1005
1006 // Is the scheduled region resource limited vs. latency limited.
1007 bool IsResourceLimited;
1008
1009 unsigned ExpectedCount;
1010
Andrew Trick3b87f622012-11-07 07:05:09 +00001011#ifndef NDEBUG
Andrew Trickb7e02892012-06-05 21:11:27 +00001012 // Remember the greatest min operand latency.
1013 unsigned MaxMinLatency;
Andrew Trick3b87f622012-11-07 07:05:09 +00001014#endif
1015
1016 void reset() {
1017 Available.clear();
1018 Pending.clear();
1019 CheckPending = false;
1020 NextSUs.clear();
1021 HazardRec = 0;
1022 CurrCycle = 0;
1023 IssueCount = 0;
1024 MinReadyCycle = UINT_MAX;
1025 ExpectedLatency = 0;
1026 ResourceCounts.resize(1);
1027 assert(!ResourceCounts[0] && "nonzero count for bad resource");
1028 CritResIdx = 0;
1029 IsResourceLimited = false;
1030 ExpectedCount = 0;
Andrew Trick3b87f622012-11-07 07:05:09 +00001031#ifndef NDEBUG
1032 MaxMinLatency = 0;
1033#endif
1034 // Reserve a zero-count for invalid CritResIdx.
1035 ResourceCounts.resize(1);
1036 }
Andrew Trickb7e02892012-06-05 21:11:27 +00001037
Andrew Trickf3234242012-05-24 22:11:12 +00001038 /// Pending queues extend the ready queues with the same ID and the
1039 /// PendingFlag set.
1040 SchedBoundary(unsigned ID, const Twine &Name):
Andrew Trick3b87f622012-11-07 07:05:09 +00001041 DAG(0), SchedModel(0), Rem(0), Available(ID, Name+".A"),
1042 Pending(ID << ConvergingScheduler::LogMaxQID, Name+".P") {
1043 reset();
1044 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001045
1046 ~SchedBoundary() { delete HazardRec; }
1047
Andrew Trick3b87f622012-11-07 07:05:09 +00001048 void init(ScheduleDAGMI *dag, const TargetSchedModel *smodel,
1049 SchedRemainder *rem);
Andrew Trick412cd2f2012-10-10 05:43:09 +00001050
Andrew Trickf3234242012-05-24 22:11:12 +00001051 bool isTop() const {
1052 return Available.getID() == ConvergingScheduler::TopQID;
1053 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001054
Andrew Trick3b87f622012-11-07 07:05:09 +00001055 unsigned getUnscheduledLatency(SUnit *SU) const {
1056 if (isTop())
1057 return SU->getHeight();
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001058 return SU->getDepth() + SU->Latency;
Andrew Trick3b87f622012-11-07 07:05:09 +00001059 }
1060
1061 unsigned getCriticalCount() const {
1062 return ResourceCounts[CritResIdx];
1063 }
1064
Andrew Trick5559ffa2012-06-29 03:23:24 +00001065 bool checkHazard(SUnit *SU);
1066
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001067 void setLatencyPolicy(CandPolicy &Policy);
Andrew Trick3b87f622012-11-07 07:05:09 +00001068
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001069 void releaseNode(SUnit *SU, unsigned ReadyCycle);
1070
1071 void bumpCycle();
1072
Andrew Trick3b87f622012-11-07 07:05:09 +00001073 void countResource(unsigned PIdx, unsigned Cycles);
1074
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001075 void bumpNode(SUnit *SU);
Andrew Trickb7e02892012-06-05 21:11:27 +00001076
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001077 void releasePending();
1078
1079 void removeReady(SUnit *SU);
1080
1081 SUnit *pickOnlyChoice();
1082 };
1083
Andrew Trick3b87f622012-11-07 07:05:09 +00001084private:
Andrew Trick17d35e52012-03-14 04:00:41 +00001085 ScheduleDAGMI *DAG;
Andrew Trick412cd2f2012-10-10 05:43:09 +00001086 const TargetSchedModel *SchedModel;
Andrew Trick7196a8f2012-05-10 21:06:16 +00001087 const TargetRegisterInfo *TRI;
Andrew Trick42b7a712012-01-17 06:55:03 +00001088
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001089 // State of the top and bottom scheduled instruction boundaries.
Andrew Trick3b87f622012-11-07 07:05:09 +00001090 SchedRemainder Rem;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001091 SchedBoundary Top;
1092 SchedBoundary Bot;
Andrew Trick17d35e52012-03-14 04:00:41 +00001093
1094public:
Andrew Trickf3234242012-05-24 22:11:12 +00001095 /// SUnit::NodeQueueId: 0 (none), 1 (top), 2 (bot), 3 (both)
Andrew Trick7196a8f2012-05-10 21:06:16 +00001096 enum {
1097 TopQID = 1,
Andrew Trickf3234242012-05-24 22:11:12 +00001098 BotQID = 2,
1099 LogMaxQID = 2
Andrew Trick7196a8f2012-05-10 21:06:16 +00001100 };
1101
Andrew Trickf3234242012-05-24 22:11:12 +00001102 ConvergingScheduler():
Andrew Trick412cd2f2012-10-10 05:43:09 +00001103 DAG(0), SchedModel(0), TRI(0), Top(TopQID, "TopQ"), Bot(BotQID, "BotQ") {}
Andrew Trickd38f87e2012-05-10 21:06:12 +00001104
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001105 virtual void initialize(ScheduleDAGMI *dag);
Andrew Trick17d35e52012-03-14 04:00:41 +00001106
Andrew Trick7196a8f2012-05-10 21:06:16 +00001107 virtual SUnit *pickNode(bool &IsTopNode);
Andrew Trick17d35e52012-03-14 04:00:41 +00001108
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001109 virtual void schedNode(SUnit *SU, bool IsTopNode);
1110
1111 virtual void releaseTopNode(SUnit *SU);
1112
1113 virtual void releaseBottomNode(SUnit *SU);
1114
Andrew Trick3b87f622012-11-07 07:05:09 +00001115 virtual void registerRoots();
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001116
Andrew Trick3b87f622012-11-07 07:05:09 +00001117protected:
1118 void balanceZones(
1119 ConvergingScheduler::SchedBoundary &CriticalZone,
1120 ConvergingScheduler::SchedCandidate &CriticalCand,
1121 ConvergingScheduler::SchedBoundary &OppositeZone,
1122 ConvergingScheduler::SchedCandidate &OppositeCand);
1123
1124 void checkResourceLimits(ConvergingScheduler::SchedCandidate &TopCand,
1125 ConvergingScheduler::SchedCandidate &BotCand);
1126
1127 void tryCandidate(SchedCandidate &Cand,
1128 SchedCandidate &TryCand,
1129 SchedBoundary &Zone,
1130 const RegPressureTracker &RPTracker,
1131 RegPressureTracker &TempTracker);
1132
1133 SUnit *pickNodeBidirectional(bool &IsTopNode);
1134
1135 void pickNodeFromQueue(SchedBoundary &Zone,
1136 const RegPressureTracker &RPTracker,
1137 SchedCandidate &Candidate);
1138
Andrew Trick28ebc892012-05-10 21:06:19 +00001139#ifndef NDEBUG
Andrew Trick3b87f622012-11-07 07:05:09 +00001140 void traceCandidate(const SchedCandidate &Cand, const SchedBoundary &Zone);
Andrew Trick28ebc892012-05-10 21:06:19 +00001141#endif
Andrew Trick42b7a712012-01-17 06:55:03 +00001142};
1143} // namespace
1144
Andrew Trick3b87f622012-11-07 07:05:09 +00001145void ConvergingScheduler::SchedRemainder::
1146init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
1147 reset();
1148 if (!SchedModel->hasInstrSchedModel())
1149 return;
1150 RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
1151 for (std::vector<SUnit>::iterator
1152 I = DAG->SUnits.begin(), E = DAG->SUnits.end(); I != E; ++I) {
1153 const MCSchedClassDesc *SC = DAG->getSchedClass(&*I);
1154 RemainingMicroOps += SchedModel->getNumMicroOps(I->getInstr(), SC);
1155 for (TargetSchedModel::ProcResIter
1156 PI = SchedModel->getWriteProcResBegin(SC),
1157 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1158 unsigned PIdx = PI->ProcResourceIdx;
1159 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1160 RemainingCounts[PIdx] += (Factor * PI->Cycles);
1161 }
1162 }
Andrew Trick071966f2012-12-18 20:52:49 +00001163 for (unsigned PIdx = 0, PEnd = SchedModel->getNumProcResourceKinds();
1164 PIdx != PEnd; ++PIdx) {
1165 if ((int)(RemainingCounts[PIdx] - RemainingCounts[CritResIdx])
1166 >= (int)SchedModel->getLatencyFactor()) {
1167 CritResIdx = PIdx;
1168 }
1169 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001170}
1171
1172void ConvergingScheduler::SchedBoundary::
1173init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
1174 reset();
1175 DAG = dag;
1176 SchedModel = smodel;
1177 Rem = rem;
1178 if (SchedModel->hasInstrSchedModel())
1179 ResourceCounts.resize(SchedModel->getNumProcResourceKinds());
1180}
1181
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001182void ConvergingScheduler::initialize(ScheduleDAGMI *dag) {
1183 DAG = dag;
Andrew Trick412cd2f2012-10-10 05:43:09 +00001184 SchedModel = DAG->getSchedModel();
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001185 TRI = DAG->TRI;
Andrew Trick3b87f622012-11-07 07:05:09 +00001186 Rem.init(DAG, SchedModel);
1187 Top.init(DAG, SchedModel, &Rem);
1188 Bot.init(DAG, SchedModel, &Rem);
1189
1190 // Initialize resource counts.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001191
Andrew Trick412cd2f2012-10-10 05:43:09 +00001192 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
1193 // are disabled, then these HazardRecs will be disabled.
1194 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001195 const TargetMachine &TM = DAG->MF.getTarget();
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001196 Top.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
1197 Bot.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
1198
1199 assert((!ForceTopDown || !ForceBottomUp) &&
1200 "-misched-topdown incompatible with -misched-bottomup");
1201}
1202
1203void ConvergingScheduler::releaseTopNode(SUnit *SU) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001204 if (SU->isScheduled)
1205 return;
1206
Andrew Trickd4539602012-12-18 20:52:52 +00001207 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
Andrew Trickb7e02892012-06-05 21:11:27 +00001208 I != E; ++I) {
1209 unsigned PredReadyCycle = I->getSUnit()->TopReadyCycle;
Andrew Trickffd25262012-08-23 00:39:43 +00001210 unsigned MinLatency = I->getMinLatency();
Andrew Trickb7e02892012-06-05 21:11:27 +00001211#ifndef NDEBUG
Andrew Trickffd25262012-08-23 00:39:43 +00001212 Top.MaxMinLatency = std::max(MinLatency, Top.MaxMinLatency);
Andrew Trickb7e02892012-06-05 21:11:27 +00001213#endif
Andrew Trickffd25262012-08-23 00:39:43 +00001214 if (SU->TopReadyCycle < PredReadyCycle + MinLatency)
1215 SU->TopReadyCycle = PredReadyCycle + MinLatency;
Andrew Trickb7e02892012-06-05 21:11:27 +00001216 }
1217 Top.releaseNode(SU, SU->TopReadyCycle);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001218}
1219
1220void ConvergingScheduler::releaseBottomNode(SUnit *SU) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001221 if (SU->isScheduled)
1222 return;
1223
1224 assert(SU->getInstr() && "Scheduled SUnit must have instr");
1225
1226 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1227 I != E; ++I) {
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001228 if (I->isWeak())
1229 continue;
Andrew Trickb7e02892012-06-05 21:11:27 +00001230 unsigned SuccReadyCycle = I->getSUnit()->BotReadyCycle;
Andrew Trickffd25262012-08-23 00:39:43 +00001231 unsigned MinLatency = I->getMinLatency();
Andrew Trickb7e02892012-06-05 21:11:27 +00001232#ifndef NDEBUG
Andrew Trickffd25262012-08-23 00:39:43 +00001233 Bot.MaxMinLatency = std::max(MinLatency, Bot.MaxMinLatency);
Andrew Trickb7e02892012-06-05 21:11:27 +00001234#endif
Andrew Trickffd25262012-08-23 00:39:43 +00001235 if (SU->BotReadyCycle < SuccReadyCycle + MinLatency)
1236 SU->BotReadyCycle = SuccReadyCycle + MinLatency;
Andrew Trickb7e02892012-06-05 21:11:27 +00001237 }
1238 Bot.releaseNode(SU, SU->BotReadyCycle);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001239}
1240
Andrew Trick3b87f622012-11-07 07:05:09 +00001241void ConvergingScheduler::registerRoots() {
1242 Rem.CriticalPath = DAG->ExitSU.getDepth();
1243 // Some roots may not feed into ExitSU. Check all of them in case.
1244 for (std::vector<SUnit*>::const_iterator
1245 I = Bot.Available.begin(), E = Bot.Available.end(); I != E; ++I) {
1246 if ((*I)->getDepth() > Rem.CriticalPath)
1247 Rem.CriticalPath = (*I)->getDepth();
1248 }
1249 DEBUG(dbgs() << "Critical Path: " << Rem.CriticalPath << '\n');
1250}
1251
Andrew Trick5559ffa2012-06-29 03:23:24 +00001252/// Does this SU have a hazard within the current instruction group.
1253///
1254/// The scheduler supports two modes of hazard recognition. The first is the
1255/// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
1256/// supports highly complicated in-order reservation tables
1257/// (ScoreboardHazardRecognizer) and arbitraty target-specific logic.
1258///
1259/// The second is a streamlined mechanism that checks for hazards based on
1260/// simple counters that the scheduler itself maintains. It explicitly checks
1261/// for instruction dispatch limitations, including the number of micro-ops that
1262/// can dispatch per cycle.
1263///
1264/// TODO: Also check whether the SU must start a new group.
1265bool ConvergingScheduler::SchedBoundary::checkHazard(SUnit *SU) {
1266 if (HazardRec->isEnabled())
1267 return HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard;
1268
Andrew Trick412cd2f2012-10-10 05:43:09 +00001269 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
Andrew Trick3b87f622012-11-07 07:05:09 +00001270 if ((IssueCount > 0) && (IssueCount + uops > SchedModel->getIssueWidth())) {
1271 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") uops="
1272 << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
Andrew Trick5559ffa2012-06-29 03:23:24 +00001273 return true;
Andrew Trick3b87f622012-11-07 07:05:09 +00001274 }
Andrew Trick5559ffa2012-06-29 03:23:24 +00001275 return false;
1276}
1277
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001278/// Compute the remaining latency to determine whether ILP should be increased.
1279void ConvergingScheduler::SchedBoundary::setLatencyPolicy(CandPolicy &Policy) {
1280 // FIXME: compile time. In all, we visit four queues here one we should only
1281 // need to visit the one that was last popped if we cache the result.
1282 unsigned RemLatency = 0;
1283 for (ReadyQueue::iterator I = Available.begin(), E = Available.end();
1284 I != E; ++I) {
1285 unsigned L = getUnscheduledLatency(*I);
1286 if (L > RemLatency)
1287 RemLatency = L;
1288 }
1289 for (ReadyQueue::iterator I = Pending.begin(), E = Pending.end();
1290 I != E; ++I) {
1291 unsigned L = getUnscheduledLatency(*I);
1292 if (L > RemLatency)
1293 RemLatency = L;
1294 }
Andrew Trick47579cf2013-01-09 03:36:49 +00001295 unsigned CriticalPathLimit = Rem->CriticalPath + SchedModel->getILPWindow();
1296 if (RemLatency + ExpectedLatency >= CriticalPathLimit
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001297 && RemLatency > Rem->getMaxRemainingCount(SchedModel)) {
1298 Policy.ReduceLatency = true;
1299 DEBUG(dbgs() << "Increase ILP: " << Available.getName() << '\n');
Andrew Trick3b87f622012-11-07 07:05:09 +00001300 }
1301}
1302
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001303void ConvergingScheduler::SchedBoundary::releaseNode(SUnit *SU,
1304 unsigned ReadyCycle) {
Andrew Trick3b87f622012-11-07 07:05:09 +00001305
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001306 if (ReadyCycle < MinReadyCycle)
1307 MinReadyCycle = ReadyCycle;
1308
1309 // Check for interlocks first. For the purpose of other heuristics, an
1310 // instruction that cannot issue appears as if it's not in the ReadyQueue.
Andrew Trick5559ffa2012-06-29 03:23:24 +00001311 if (ReadyCycle > CurrCycle || checkHazard(SU))
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001312 Pending.push(SU);
1313 else
1314 Available.push(SU);
Andrew Trick3b87f622012-11-07 07:05:09 +00001315
1316 // Record this node as an immediate dependent of the scheduled node.
1317 NextSUs.insert(SU);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001318}
1319
1320/// Move the boundary of scheduled code by one cycle.
1321void ConvergingScheduler::SchedBoundary::bumpCycle() {
Andrew Trick412cd2f2012-10-10 05:43:09 +00001322 unsigned Width = SchedModel->getIssueWidth();
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001323 IssueCount = (IssueCount <= Width) ? 0 : IssueCount - Width;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001324
Andrew Trick3b87f622012-11-07 07:05:09 +00001325 unsigned NextCycle = CurrCycle + 1;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001326 assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
Andrew Trick3b87f622012-11-07 07:05:09 +00001327 if (MinReadyCycle > NextCycle) {
1328 IssueCount = 0;
1329 NextCycle = MinReadyCycle;
1330 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001331
1332 if (!HazardRec->isEnabled()) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001333 // Bypass HazardRec virtual calls.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001334 CurrCycle = NextCycle;
1335 }
1336 else {
Andrew Trickb7e02892012-06-05 21:11:27 +00001337 // Bypass getHazardType calls in case of long latency.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001338 for (; CurrCycle != NextCycle; ++CurrCycle) {
1339 if (isTop())
1340 HazardRec->AdvanceCycle();
1341 else
1342 HazardRec->RecedeCycle();
1343 }
1344 }
1345 CheckPending = true;
Andrew Trick3b87f622012-11-07 07:05:09 +00001346 IsResourceLimited = getCriticalCount() > std::max(ExpectedLatency, CurrCycle);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001347
Andrew Trick3b87f622012-11-07 07:05:09 +00001348 DEBUG(dbgs() << " *** " << Available.getName() << " cycle "
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001349 << CurrCycle << '\n');
1350}
1351
Andrew Trick3b87f622012-11-07 07:05:09 +00001352/// Add the given processor resource to this scheduled zone.
1353void ConvergingScheduler::SchedBoundary::countResource(unsigned PIdx,
1354 unsigned Cycles) {
1355 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1356 DEBUG(dbgs() << " " << SchedModel->getProcResource(PIdx)->Name
1357 << " +(" << Cycles << "x" << Factor
1358 << ") / " << SchedModel->getLatencyFactor() << '\n');
1359
1360 unsigned Count = Factor * Cycles;
1361 ResourceCounts[PIdx] += Count;
1362 assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
1363 Rem->RemainingCounts[PIdx] -= Count;
1364
Andrew Trick3b87f622012-11-07 07:05:09 +00001365 // Check if this resource exceeds the current critical resource by a full
1366 // cycle. If so, it becomes the critical resource.
1367 if ((int)(ResourceCounts[PIdx] - ResourceCounts[CritResIdx])
1368 >= (int)SchedModel->getLatencyFactor()) {
1369 CritResIdx = PIdx;
1370 DEBUG(dbgs() << " *** Critical resource "
1371 << SchedModel->getProcResource(PIdx)->Name << " x"
1372 << ResourceCounts[PIdx] << '\n');
1373 }
1374}
1375
Andrew Trickb7e02892012-06-05 21:11:27 +00001376/// Move the boundary of scheduled code by one SUnit.
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001377void ConvergingScheduler::SchedBoundary::bumpNode(SUnit *SU) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001378 // Update the reservation table.
1379 if (HazardRec->isEnabled()) {
1380 if (!isTop() && SU->isCall) {
1381 // Calls are scheduled with their preceding instructions. For bottom-up
1382 // scheduling, clear the pipeline state before emitting.
1383 HazardRec->Reset();
1384 }
1385 HazardRec->EmitInstruction(SU);
1386 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001387 // Update resource counts and critical resource.
1388 if (SchedModel->hasInstrSchedModel()) {
1389 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1390 Rem->RemainingMicroOps -= SchedModel->getNumMicroOps(SU->getInstr(), SC);
1391 for (TargetSchedModel::ProcResIter
1392 PI = SchedModel->getWriteProcResBegin(SC),
1393 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1394 countResource(PI->ProcResourceIdx, PI->Cycles);
1395 }
1396 }
1397 if (isTop()) {
1398 if (SU->getDepth() > ExpectedLatency)
1399 ExpectedLatency = SU->getDepth();
1400 }
1401 else {
1402 if (SU->getHeight() > ExpectedLatency)
1403 ExpectedLatency = SU->getHeight();
1404 }
1405
1406 IsResourceLimited = getCriticalCount() > std::max(ExpectedLatency, CurrCycle);
1407
Andrew Trick5559ffa2012-06-29 03:23:24 +00001408 // Check the instruction group dispatch limit.
1409 // TODO: Check if this SU must end a dispatch group.
Andrew Trick412cd2f2012-10-10 05:43:09 +00001410 IssueCount += SchedModel->getNumMicroOps(SU->getInstr());
Andrew Trick3b87f622012-11-07 07:05:09 +00001411
1412 // checkHazard prevents scheduling multiple instructions per cycle that exceed
1413 // issue width. However, we commonly reach the maximum. In this case
1414 // opportunistically bump the cycle to avoid uselessly checking everything in
1415 // the readyQ. Furthermore, a single instruction may produce more than one
1416 // cycle's worth of micro-ops.
Andrew Trick412cd2f2012-10-10 05:43:09 +00001417 if (IssueCount >= SchedModel->getIssueWidth()) {
Andrew Trick3b87f622012-11-07 07:05:09 +00001418 DEBUG(dbgs() << " *** Max instrs at cycle " << CurrCycle << '\n');
Andrew Trickb7e02892012-06-05 21:11:27 +00001419 bumpCycle();
1420 }
1421}
1422
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001423/// Release pending ready nodes in to the available queue. This makes them
1424/// visible to heuristics.
1425void ConvergingScheduler::SchedBoundary::releasePending() {
1426 // If the available queue is empty, it is safe to reset MinReadyCycle.
1427 if (Available.empty())
1428 MinReadyCycle = UINT_MAX;
1429
1430 // Check to see if any of the pending instructions are ready to issue. If
1431 // so, add them to the available queue.
1432 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
1433 SUnit *SU = *(Pending.begin()+i);
Andrew Trickb7e02892012-06-05 21:11:27 +00001434 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001435
1436 if (ReadyCycle < MinReadyCycle)
1437 MinReadyCycle = ReadyCycle;
1438
1439 if (ReadyCycle > CurrCycle)
1440 continue;
1441
Andrew Trick5559ffa2012-06-29 03:23:24 +00001442 if (checkHazard(SU))
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001443 continue;
1444
1445 Available.push(SU);
1446 Pending.remove(Pending.begin()+i);
1447 --i; --e;
1448 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001449 DEBUG(if (!Pending.empty()) Pending.dump());
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001450 CheckPending = false;
1451}
1452
1453/// Remove SU from the ready set for this boundary.
1454void ConvergingScheduler::SchedBoundary::removeReady(SUnit *SU) {
1455 if (Available.isInQueue(SU))
1456 Available.remove(Available.find(SU));
1457 else {
1458 assert(Pending.isInQueue(SU) && "bad ready count");
1459 Pending.remove(Pending.find(SU));
1460 }
1461}
1462
1463/// If this queue only has one ready candidate, return it. As a side effect,
Andrew Trick3b87f622012-11-07 07:05:09 +00001464/// defer any nodes that now hit a hazard, and advance the cycle until at least
1465/// one node is ready. If multiple instructions are ready, return NULL.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001466SUnit *ConvergingScheduler::SchedBoundary::pickOnlyChoice() {
1467 if (CheckPending)
1468 releasePending();
1469
Andrew Trick3b87f622012-11-07 07:05:09 +00001470 if (IssueCount > 0) {
1471 // Defer any ready instrs that now have a hazard.
1472 for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
1473 if (checkHazard(*I)) {
1474 Pending.push(*I);
1475 I = Available.remove(I);
1476 continue;
1477 }
1478 ++I;
1479 }
1480 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001481 for (unsigned i = 0; Available.empty(); ++i) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001482 assert(i <= (HazardRec->getMaxLookAhead() + MaxMinLatency) &&
1483 "permanent hazard"); (void)i;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001484 bumpCycle();
1485 releasePending();
1486 }
1487 if (Available.size() == 1)
1488 return *Available.begin();
1489 return NULL;
1490}
1491
Andrew Trick3b87f622012-11-07 07:05:09 +00001492/// Record the candidate policy for opposite zones with different critical
1493/// resources.
1494///
1495/// If the CriticalZone is latency limited, don't force a policy for the
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001496/// candidates here. Instead, setLatencyPolicy sets ReduceLatency if needed.
Andrew Trick3b87f622012-11-07 07:05:09 +00001497void ConvergingScheduler::balanceZones(
1498 ConvergingScheduler::SchedBoundary &CriticalZone,
1499 ConvergingScheduler::SchedCandidate &CriticalCand,
1500 ConvergingScheduler::SchedBoundary &OppositeZone,
1501 ConvergingScheduler::SchedCandidate &OppositeCand) {
1502
1503 if (!CriticalZone.IsResourceLimited)
1504 return;
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001505 assert(SchedModel->hasInstrSchedModel() && "required schedmodel");
Andrew Trick3b87f622012-11-07 07:05:09 +00001506
1507 SchedRemainder *Rem = CriticalZone.Rem;
1508
1509 // If the critical zone is overconsuming a resource relative to the
1510 // remainder, try to reduce it.
1511 unsigned RemainingCritCount =
1512 Rem->RemainingCounts[CriticalZone.CritResIdx];
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001513 if ((int)(Rem->getMaxRemainingCount(SchedModel) - RemainingCritCount)
Andrew Trick3b87f622012-11-07 07:05:09 +00001514 > (int)SchedModel->getLatencyFactor()) {
1515 CriticalCand.Policy.ReduceResIdx = CriticalZone.CritResIdx;
1516 DEBUG(dbgs() << "Balance " << CriticalZone.Available.getName() << " reduce "
1517 << SchedModel->getProcResource(CriticalZone.CritResIdx)->Name
1518 << '\n');
1519 }
1520 // If the other zone is underconsuming a resource relative to the full zone,
1521 // try to increase it.
1522 unsigned OppositeCount =
1523 OppositeZone.ResourceCounts[CriticalZone.CritResIdx];
1524 if ((int)(OppositeZone.ExpectedCount - OppositeCount)
1525 > (int)SchedModel->getLatencyFactor()) {
1526 OppositeCand.Policy.DemandResIdx = CriticalZone.CritResIdx;
1527 DEBUG(dbgs() << "Balance " << OppositeZone.Available.getName() << " demand "
1528 << SchedModel->getProcResource(OppositeZone.CritResIdx)->Name
1529 << '\n');
1530 }
Andrew Trick28ebc892012-05-10 21:06:19 +00001531}
Andrew Trick3b87f622012-11-07 07:05:09 +00001532
1533/// Determine if the scheduled zones exceed resource limits or critical path and
1534/// set each candidate's ReduceHeight policy accordingly.
1535void ConvergingScheduler::checkResourceLimits(
1536 ConvergingScheduler::SchedCandidate &TopCand,
1537 ConvergingScheduler::SchedCandidate &BotCand) {
1538
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001539 // Set ReduceLatency to true if needed.
Andrew Trickeed4e012013-01-11 17:51:16 +00001540 Bot.setLatencyPolicy(BotCand.Policy);
1541 Top.setLatencyPolicy(TopCand.Policy);
Andrew Trick3b87f622012-11-07 07:05:09 +00001542
1543 // Handle resource-limited regions.
1544 if (Top.IsResourceLimited && Bot.IsResourceLimited
1545 && Top.CritResIdx == Bot.CritResIdx) {
1546 // If the scheduled critical resource in both zones is no longer the
1547 // critical remaining resource, attempt to reduce resource height both ways.
1548 if (Top.CritResIdx != Rem.CritResIdx) {
1549 TopCand.Policy.ReduceResIdx = Top.CritResIdx;
1550 BotCand.Policy.ReduceResIdx = Bot.CritResIdx;
1551 DEBUG(dbgs() << "Reduce scheduled "
1552 << SchedModel->getProcResource(Top.CritResIdx)->Name << '\n');
1553 }
1554 return;
1555 }
1556 // Handle latency-limited regions.
1557 if (!Top.IsResourceLimited && !Bot.IsResourceLimited) {
1558 // If the total scheduled expected latency exceeds the region's critical
1559 // path then reduce latency both ways.
1560 //
1561 // Just because a zone is not resource limited does not mean it is latency
1562 // limited. Unbuffered resource, such as max micro-ops may cause CurrCycle
1563 // to exceed expected latency.
1564 if ((Top.ExpectedLatency + Bot.ExpectedLatency >= Rem.CriticalPath)
1565 && (Rem.CriticalPath > Top.CurrCycle + Bot.CurrCycle)) {
1566 TopCand.Policy.ReduceLatency = true;
1567 BotCand.Policy.ReduceLatency = true;
1568 DEBUG(dbgs() << "Reduce scheduled latency " << Top.ExpectedLatency
1569 << " + " << Bot.ExpectedLatency << '\n');
1570 }
1571 return;
1572 }
1573 // The critical resource is different in each zone, so request balancing.
1574
1575 // Compute the cost of each zone.
Andrew Trick3b87f622012-11-07 07:05:09 +00001576 Top.ExpectedCount = std::max(Top.ExpectedLatency, Top.CurrCycle);
1577 Top.ExpectedCount = std::max(
1578 Top.getCriticalCount(),
1579 Top.ExpectedCount * SchedModel->getLatencyFactor());
1580 Bot.ExpectedCount = std::max(Bot.ExpectedLatency, Bot.CurrCycle);
1581 Bot.ExpectedCount = std::max(
1582 Bot.getCriticalCount(),
1583 Bot.ExpectedCount * SchedModel->getLatencyFactor());
1584
1585 balanceZones(Top, TopCand, Bot, BotCand);
1586 balanceZones(Bot, BotCand, Top, TopCand);
1587}
1588
1589void ConvergingScheduler::SchedCandidate::
1590initResourceDelta(const ScheduleDAGMI *DAG,
1591 const TargetSchedModel *SchedModel) {
1592 if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
1593 return;
1594
1595 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1596 for (TargetSchedModel::ProcResIter
1597 PI = SchedModel->getWriteProcResBegin(SC),
1598 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1599 if (PI->ProcResourceIdx == Policy.ReduceResIdx)
1600 ResDelta.CritResources += PI->Cycles;
1601 if (PI->ProcResourceIdx == Policy.DemandResIdx)
1602 ResDelta.DemandedResources += PI->Cycles;
1603 }
1604}
1605
1606/// Return true if this heuristic determines order.
1607static bool tryLess(unsigned TryVal, unsigned CandVal,
1608 ConvergingScheduler::SchedCandidate &TryCand,
1609 ConvergingScheduler::SchedCandidate &Cand,
1610 ConvergingScheduler::CandReason Reason) {
1611 if (TryVal < CandVal) {
1612 TryCand.Reason = Reason;
1613 return true;
1614 }
1615 if (TryVal > CandVal) {
1616 if (Cand.Reason > Reason)
1617 Cand.Reason = Reason;
1618 return true;
1619 }
1620 return false;
1621}
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001622
Andrew Trick3b87f622012-11-07 07:05:09 +00001623static bool tryGreater(unsigned TryVal, unsigned CandVal,
1624 ConvergingScheduler::SchedCandidate &TryCand,
1625 ConvergingScheduler::SchedCandidate &Cand,
1626 ConvergingScheduler::CandReason Reason) {
1627 if (TryVal > CandVal) {
1628 TryCand.Reason = Reason;
1629 return true;
1630 }
1631 if (TryVal < CandVal) {
1632 if (Cand.Reason > Reason)
1633 Cand.Reason = Reason;
1634 return true;
1635 }
1636 return false;
1637}
1638
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001639static unsigned getWeakLeft(const SUnit *SU, bool isTop) {
1640 return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
1641}
1642
Andrew Trick3b87f622012-11-07 07:05:09 +00001643/// Apply a set of heursitics to a new candidate. Heuristics are currently
1644/// hierarchical. This may be more efficient than a graduated cost model because
1645/// we don't need to evaluate all aspects of the model for each node in the
1646/// queue. But it's really done to make the heuristics easier to debug and
1647/// statistically analyze.
1648///
1649/// \param Cand provides the policy and current best candidate.
1650/// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
1651/// \param Zone describes the scheduled zone that we are extending.
1652/// \param RPTracker describes reg pressure within the scheduled zone.
1653/// \param TempTracker is a scratch pressure tracker to reuse in queries.
1654void ConvergingScheduler::tryCandidate(SchedCandidate &Cand,
1655 SchedCandidate &TryCand,
1656 SchedBoundary &Zone,
1657 const RegPressureTracker &RPTracker,
1658 RegPressureTracker &TempTracker) {
1659
1660 // Always initialize TryCand's RPDelta.
1661 TempTracker.getMaxPressureDelta(TryCand.SU->getInstr(), TryCand.RPDelta,
1662 DAG->getRegionCriticalPSets(),
1663 DAG->getRegPressure().MaxSetPressure);
1664
1665 // Initialize the candidate if needed.
1666 if (!Cand.isValid()) {
1667 TryCand.Reason = NodeOrder;
1668 return;
1669 }
1670 // Avoid exceeding the target's limit.
1671 if (tryLess(TryCand.RPDelta.Excess.UnitIncrease,
1672 Cand.RPDelta.Excess.UnitIncrease, TryCand, Cand, SingleExcess))
1673 return;
1674 if (Cand.Reason == SingleExcess)
1675 Cand.Reason = MultiPressure;
1676
1677 // Avoid increasing the max critical pressure in the scheduled region.
1678 if (tryLess(TryCand.RPDelta.CriticalMax.UnitIncrease,
1679 Cand.RPDelta.CriticalMax.UnitIncrease,
1680 TryCand, Cand, SingleCritical))
1681 return;
1682 if (Cand.Reason == SingleCritical)
1683 Cand.Reason = MultiPressure;
1684
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001685 // Keep clustered nodes together to encourage downstream peephole
1686 // optimizations which may reduce resource requirements.
1687 //
1688 // This is a best effort to set things up for a post-RA pass. Optimizations
1689 // like generating loads of multiple registers should ideally be done within
1690 // the scheduler pass by combining the loads during DAG postprocessing.
1691 const SUnit *NextClusterSU =
1692 Zone.isTop() ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
1693 if (tryGreater(TryCand.SU == NextClusterSU, Cand.SU == NextClusterSU,
1694 TryCand, Cand, Cluster))
1695 return;
1696 // Currently, weak edges are for clustering, so we hard-code that reason.
1697 // However, deferring the current TryCand will not change Cand's reason.
1698 CandReason OrigReason = Cand.Reason;
1699 if (tryLess(getWeakLeft(TryCand.SU, Zone.isTop()),
1700 getWeakLeft(Cand.SU, Zone.isTop()),
1701 TryCand, Cand, Cluster)) {
1702 Cand.Reason = OrigReason;
1703 return;
1704 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001705 // Avoid critical resource consumption and balance the schedule.
1706 TryCand.initResourceDelta(DAG, SchedModel);
1707 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
1708 TryCand, Cand, ResourceReduce))
1709 return;
1710 if (tryGreater(TryCand.ResDelta.DemandedResources,
1711 Cand.ResDelta.DemandedResources,
1712 TryCand, Cand, ResourceDemand))
1713 return;
1714
1715 // Avoid serializing long latency dependence chains.
1716 if (Cand.Policy.ReduceLatency) {
1717 if (Zone.isTop()) {
1718 if (Cand.SU->getDepth() * SchedModel->getLatencyFactor()
1719 > Zone.ExpectedCount) {
1720 if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
1721 TryCand, Cand, TopDepthReduce))
1722 return;
1723 }
1724 if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
1725 TryCand, Cand, TopPathReduce))
1726 return;
1727 }
1728 else {
1729 if (Cand.SU->getHeight() * SchedModel->getLatencyFactor()
1730 > Zone.ExpectedCount) {
1731 if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
1732 TryCand, Cand, BotHeightReduce))
1733 return;
1734 }
1735 if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
1736 TryCand, Cand, BotPathReduce))
1737 return;
1738 }
1739 }
1740
1741 // Avoid increasing the max pressure of the entire region.
1742 if (tryLess(TryCand.RPDelta.CurrentMax.UnitIncrease,
1743 Cand.RPDelta.CurrentMax.UnitIncrease, TryCand, Cand, SingleMax))
1744 return;
1745 if (Cand.Reason == SingleMax)
1746 Cand.Reason = MultiPressure;
1747
1748 // Prefer immediate defs/users of the last scheduled instruction. This is a
1749 // nice pressure avoidance strategy that also conserves the processor's
1750 // register renaming resources and keeps the machine code readable.
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001751 if (tryGreater(Zone.NextSUs.count(TryCand.SU), Zone.NextSUs.count(Cand.SU),
1752 TryCand, Cand, NextDefUse))
Andrew Trick3b87f622012-11-07 07:05:09 +00001753 return;
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001754
Andrew Trick3b87f622012-11-07 07:05:09 +00001755 // Fall through to original instruction order.
1756 if ((Zone.isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
1757 || (!Zone.isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
1758 TryCand.Reason = NodeOrder;
1759 }
1760}
Andrew Trick28ebc892012-05-10 21:06:19 +00001761
Andrew Trick5429a6b2012-05-17 22:37:09 +00001762/// pickNodeFromQueue helper that returns true if the LHS reg pressure effect is
1763/// more desirable than RHS from scheduling standpoint.
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001764static bool compareRPDelta(const RegPressureDelta &LHS,
1765 const RegPressureDelta &RHS) {
1766 // Compare each component of pressure in decreasing order of importance
1767 // without checking if any are valid. Invalid PressureElements are assumed to
1768 // have UnitIncrease==0, so are neutral.
Andrew Trickc8fe4ec2012-05-24 22:11:01 +00001769
1770 // Avoid increasing the max critical pressure in the scheduled region.
Andrew Trick3b87f622012-11-07 07:05:09 +00001771 if (LHS.Excess.UnitIncrease != RHS.Excess.UnitIncrease) {
1772 DEBUG(dbgs() << "RP excess top - bot: "
1773 << (LHS.Excess.UnitIncrease - RHS.Excess.UnitIncrease) << '\n');
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001774 return LHS.Excess.UnitIncrease < RHS.Excess.UnitIncrease;
Andrew Trick3b87f622012-11-07 07:05:09 +00001775 }
Andrew Trickc8fe4ec2012-05-24 22:11:01 +00001776 // Avoid increasing the max critical pressure in the scheduled region.
Andrew Trick3b87f622012-11-07 07:05:09 +00001777 if (LHS.CriticalMax.UnitIncrease != RHS.CriticalMax.UnitIncrease) {
1778 DEBUG(dbgs() << "RP critical top - bot: "
1779 << (LHS.CriticalMax.UnitIncrease - RHS.CriticalMax.UnitIncrease)
1780 << '\n');
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001781 return LHS.CriticalMax.UnitIncrease < RHS.CriticalMax.UnitIncrease;
Andrew Trick3b87f622012-11-07 07:05:09 +00001782 }
Andrew Trickc8fe4ec2012-05-24 22:11:01 +00001783 // Avoid increasing the max pressure of the entire region.
Andrew Trick3b87f622012-11-07 07:05:09 +00001784 if (LHS.CurrentMax.UnitIncrease != RHS.CurrentMax.UnitIncrease) {
1785 DEBUG(dbgs() << "RP current top - bot: "
1786 << (LHS.CurrentMax.UnitIncrease - RHS.CurrentMax.UnitIncrease)
1787 << '\n');
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001788 return LHS.CurrentMax.UnitIncrease < RHS.CurrentMax.UnitIncrease;
Andrew Trick3b87f622012-11-07 07:05:09 +00001789 }
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001790 return false;
1791}
1792
Andrew Trick3b87f622012-11-07 07:05:09 +00001793#ifndef NDEBUG
1794const char *ConvergingScheduler::getReasonStr(
1795 ConvergingScheduler::CandReason Reason) {
1796 switch (Reason) {
1797 case NoCand: return "NOCAND ";
1798 case SingleExcess: return "REG-EXCESS";
1799 case SingleCritical: return "REG-CRIT ";
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001800 case Cluster: return "CLUSTER ";
Andrew Trick3b87f622012-11-07 07:05:09 +00001801 case SingleMax: return "REG-MAX ";
1802 case MultiPressure: return "REG-MULTI ";
1803 case ResourceReduce: return "RES-REDUCE";
1804 case ResourceDemand: return "RES-DEMAND";
1805 case TopDepthReduce: return "TOP-DEPTH ";
1806 case TopPathReduce: return "TOP-PATH ";
1807 case BotHeightReduce:return "BOT-HEIGHT";
1808 case BotPathReduce: return "BOT-PATH ";
1809 case NextDefUse: return "DEF-USE ";
1810 case NodeOrder: return "ORDER ";
1811 };
Benjamin Kramerb7546872012-11-09 15:45:22 +00001812 llvm_unreachable("Unknown reason!");
Andrew Trick3b87f622012-11-07 07:05:09 +00001813}
1814
1815void ConvergingScheduler::traceCandidate(const SchedCandidate &Cand,
1816 const SchedBoundary &Zone) {
1817 const char *Label = getReasonStr(Cand.Reason);
1818 PressureElement P;
1819 unsigned ResIdx = 0;
1820 unsigned Latency = 0;
1821 switch (Cand.Reason) {
1822 default:
1823 break;
1824 case SingleExcess:
1825 P = Cand.RPDelta.Excess;
1826 break;
1827 case SingleCritical:
1828 P = Cand.RPDelta.CriticalMax;
1829 break;
1830 case SingleMax:
1831 P = Cand.RPDelta.CurrentMax;
1832 break;
1833 case ResourceReduce:
1834 ResIdx = Cand.Policy.ReduceResIdx;
1835 break;
1836 case ResourceDemand:
1837 ResIdx = Cand.Policy.DemandResIdx;
1838 break;
1839 case TopDepthReduce:
1840 Latency = Cand.SU->getDepth();
1841 break;
1842 case TopPathReduce:
1843 Latency = Cand.SU->getHeight();
1844 break;
1845 case BotHeightReduce:
1846 Latency = Cand.SU->getHeight();
1847 break;
1848 case BotPathReduce:
1849 Latency = Cand.SU->getDepth();
1850 break;
1851 }
1852 dbgs() << Label << " " << Zone.Available.getName() << " ";
1853 if (P.isValid())
1854 dbgs() << TRI->getRegPressureSetName(P.PSetID) << ":" << P.UnitIncrease
1855 << " ";
1856 else
1857 dbgs() << " ";
1858 if (ResIdx)
1859 dbgs() << SchedModel->getProcResource(ResIdx)->Name << " ";
1860 else
1861 dbgs() << " ";
1862 if (Latency)
1863 dbgs() << Latency << " cycles ";
1864 else
1865 dbgs() << " ";
1866 Cand.SU->dump(DAG);
1867}
1868#endif
1869
Andrew Trick7196a8f2012-05-10 21:06:16 +00001870/// Pick the best candidate from the top queue.
1871///
1872/// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
1873/// DAG building. To adjust for the current scheduling location we need to
1874/// maintain the number of vreg uses remaining to be top-scheduled.
Andrew Trick3b87f622012-11-07 07:05:09 +00001875void ConvergingScheduler::pickNodeFromQueue(SchedBoundary &Zone,
1876 const RegPressureTracker &RPTracker,
1877 SchedCandidate &Cand) {
1878 ReadyQueue &Q = Zone.Available;
1879
Andrew Trickf3234242012-05-24 22:11:12 +00001880 DEBUG(Q.dump());
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001881
Andrew Trick7196a8f2012-05-10 21:06:16 +00001882 // getMaxPressureDelta temporarily modifies the tracker.
1883 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
1884
Andrew Trick8c2d9212012-05-24 22:11:03 +00001885 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
Andrew Trick7196a8f2012-05-10 21:06:16 +00001886
Andrew Trick3b87f622012-11-07 07:05:09 +00001887 SchedCandidate TryCand(Cand.Policy);
1888 TryCand.SU = *I;
1889 tryCandidate(Cand, TryCand, Zone, RPTracker, TempTracker);
1890 if (TryCand.Reason != NoCand) {
1891 // Initialize resource delta if needed in case future heuristics query it.
1892 if (TryCand.ResDelta == SchedResourceDelta())
1893 TryCand.initResourceDelta(DAG, SchedModel);
1894 Cand.setBest(TryCand);
1895 DEBUG(traceCandidate(Cand, Zone));
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001896 }
Andrew Trick7196a8f2012-05-10 21:06:16 +00001897 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001898}
1899
1900static void tracePick(const ConvergingScheduler::SchedCandidate &Cand,
1901 bool IsTop) {
1902 DEBUG(dbgs() << "Pick " << (IsTop ? "top" : "bot")
1903 << " SU(" << Cand.SU->NodeNum << ") "
1904 << ConvergingScheduler::getReasonStr(Cand.Reason) << '\n');
Andrew Trick7196a8f2012-05-10 21:06:16 +00001905}
1906
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001907/// Pick the best candidate node from either the top or bottom queue.
Andrew Trick3b87f622012-11-07 07:05:09 +00001908SUnit *ConvergingScheduler::pickNodeBidirectional(bool &IsTopNode) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001909 // Schedule as far as possible in the direction of no choice. This is most
1910 // efficient, but also provides the best heuristics for CriticalPSets.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001911 if (SUnit *SU = Bot.pickOnlyChoice()) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001912 IsTopNode = false;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001913 return SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001914 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001915 if (SUnit *SU = Top.pickOnlyChoice()) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001916 IsTopNode = true;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001917 return SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001918 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001919 CandPolicy NoPolicy;
1920 SchedCandidate BotCand(NoPolicy);
1921 SchedCandidate TopCand(NoPolicy);
1922 checkResourceLimits(TopCand, BotCand);
1923
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001924 // Prefer bottom scheduling when heuristics are silent.
Andrew Trick3b87f622012-11-07 07:05:09 +00001925 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
1926 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001927
1928 // If either Q has a single candidate that provides the least increase in
1929 // Excess pressure, we can immediately schedule from that Q.
1930 //
1931 // RegionCriticalPSets summarizes the pressure within the scheduled region and
1932 // affects picking from either Q. If scheduling in one direction must
1933 // increase pressure for one of the excess PSets, then schedule in that
1934 // direction first to provide more freedom in the other direction.
Andrew Trick3b87f622012-11-07 07:05:09 +00001935 if (BotCand.Reason == SingleExcess || BotCand.Reason == SingleCritical) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001936 IsTopNode = false;
Andrew Trick3b87f622012-11-07 07:05:09 +00001937 tracePick(BotCand, IsTopNode);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001938 return BotCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001939 }
1940 // Check if the top Q has a better candidate.
Andrew Trick3b87f622012-11-07 07:05:09 +00001941 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
1942 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001943
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001944 // If either Q has a single candidate that minimizes pressure above the
1945 // original region's pressure pick it.
Andrew Trick3b87f622012-11-07 07:05:09 +00001946 if (TopCand.Reason <= SingleMax || BotCand.Reason <= SingleMax) {
1947 if (TopCand.Reason < BotCand.Reason) {
1948 IsTopNode = true;
1949 tracePick(TopCand, IsTopNode);
1950 return TopCand.SU;
1951 }
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001952 IsTopNode = false;
Andrew Trick3b87f622012-11-07 07:05:09 +00001953 tracePick(BotCand, IsTopNode);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001954 return BotCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001955 }
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001956 // Check for a salient pressure difference and pick the best from either side.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001957 if (compareRPDelta(TopCand.RPDelta, BotCand.RPDelta)) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001958 IsTopNode = true;
Andrew Trick3b87f622012-11-07 07:05:09 +00001959 tracePick(TopCand, IsTopNode);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001960 return TopCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001961 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001962 // Otherwise prefer the bottom candidate, in node order if all else failed.
1963 if (TopCand.Reason < BotCand.Reason) {
1964 IsTopNode = true;
1965 tracePick(TopCand, IsTopNode);
1966 return TopCand.SU;
1967 }
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001968 IsTopNode = false;
Andrew Trick3b87f622012-11-07 07:05:09 +00001969 tracePick(BotCand, IsTopNode);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001970 return BotCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001971}
1972
1973/// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
Andrew Trick7196a8f2012-05-10 21:06:16 +00001974SUnit *ConvergingScheduler::pickNode(bool &IsTopNode) {
1975 if (DAG->top() == DAG->bottom()) {
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001976 assert(Top.Available.empty() && Top.Pending.empty() &&
1977 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
Andrew Trick7196a8f2012-05-10 21:06:16 +00001978 return NULL;
1979 }
Andrew Trick7196a8f2012-05-10 21:06:16 +00001980 SUnit *SU;
Andrew Trick30c6ec22012-10-08 18:53:53 +00001981 do {
1982 if (ForceTopDown) {
1983 SU = Top.pickOnlyChoice();
1984 if (!SU) {
Andrew Trick3b87f622012-11-07 07:05:09 +00001985 CandPolicy NoPolicy;
1986 SchedCandidate TopCand(NoPolicy);
1987 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
1988 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick30c6ec22012-10-08 18:53:53 +00001989 SU = TopCand.SU;
1990 }
1991 IsTopNode = true;
Andrew Trick8ddd9d52012-05-24 23:11:17 +00001992 }
Andrew Trick30c6ec22012-10-08 18:53:53 +00001993 else if (ForceBottomUp) {
1994 SU = Bot.pickOnlyChoice();
1995 if (!SU) {
Andrew Trick3b87f622012-11-07 07:05:09 +00001996 CandPolicy NoPolicy;
1997 SchedCandidate BotCand(NoPolicy);
1998 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
1999 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick30c6ec22012-10-08 18:53:53 +00002000 SU = BotCand.SU;
2001 }
2002 IsTopNode = false;
Andrew Trick8ddd9d52012-05-24 23:11:17 +00002003 }
Andrew Trick30c6ec22012-10-08 18:53:53 +00002004 else {
Andrew Trick3b87f622012-11-07 07:05:09 +00002005 SU = pickNodeBidirectional(IsTopNode);
Andrew Trick30c6ec22012-10-08 18:53:53 +00002006 }
2007 } while (SU->isScheduled);
2008
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002009 if (SU->isTopReady())
2010 Top.removeReady(SU);
2011 if (SU->isBottomReady())
2012 Bot.removeReady(SU);
Andrew Trickc7a098f2012-05-25 02:02:39 +00002013
2014 DEBUG(dbgs() << "*** " << (IsTopNode ? "Top" : "Bottom")
2015 << " Scheduling Instruction in cycle "
2016 << (IsTopNode ? Top.CurrCycle : Bot.CurrCycle) << '\n';
2017 SU->dump(DAG));
Andrew Trick7196a8f2012-05-10 21:06:16 +00002018 return SU;
2019}
2020
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002021/// Update the scheduler's state after scheduling a node. This is the same node
2022/// that was just returned by pickNode(). However, ScheduleDAGMI needs to update
Andrew Trickb7e02892012-06-05 21:11:27 +00002023/// it's state based on the current cycle before MachineSchedStrategy does.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002024void ConvergingScheduler::schedNode(SUnit *SU, bool IsTopNode) {
Andrew Trickb7e02892012-06-05 21:11:27 +00002025 if (IsTopNode) {
2026 SU->TopReadyCycle = Top.CurrCycle;
Andrew Trick7f8c74c2012-06-29 03:23:22 +00002027 Top.bumpNode(SU);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002028 }
Andrew Trickb7e02892012-06-05 21:11:27 +00002029 else {
2030 SU->BotReadyCycle = Bot.CurrCycle;
Andrew Trick7f8c74c2012-06-29 03:23:22 +00002031 Bot.bumpNode(SU);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002032 }
2033}
2034
Andrew Trick17d35e52012-03-14 04:00:41 +00002035/// Create the standard converging machine scheduler. This will be used as the
2036/// default scheduler if the target does not set a default.
2037static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C) {
Benjamin Kramer689e0b42012-03-14 11:26:37 +00002038 assert((!ForceTopDown || !ForceBottomUp) &&
Andrew Trick17d35e52012-03-14 04:00:41 +00002039 "-misched-topdown incompatible with -misched-bottomup");
Andrew Trick9b5caaa2012-11-12 19:40:10 +00002040 ScheduleDAGMI *DAG = new ScheduleDAGMI(C, new ConvergingScheduler());
2041 // Register DAG post-processors.
2042 if (EnableLoadCluster)
2043 DAG->addMutation(new LoadClusterMutation(DAG->TII, DAG->TRI));
Andrew Trick6996fd02012-11-12 19:52:20 +00002044 if (EnableMacroFusion)
2045 DAG->addMutation(new MacroFusion(DAG->TII));
Andrew Trick9b5caaa2012-11-12 19:40:10 +00002046 return DAG;
Andrew Trick42b7a712012-01-17 06:55:03 +00002047}
2048static MachineSchedRegistry
Andrew Trick17d35e52012-03-14 04:00:41 +00002049ConvergingSchedRegistry("converge", "Standard converging scheduler.",
2050 createConvergingSched);
Andrew Trick42b7a712012-01-17 06:55:03 +00002051
2052//===----------------------------------------------------------------------===//
Andrew Trick1e94e982012-10-15 18:02:27 +00002053// ILP Scheduler. Currently for experimental analysis of heuristics.
2054//===----------------------------------------------------------------------===//
2055
2056namespace {
2057/// \brief Order nodes by the ILP metric.
2058struct ILPOrder {
Andrew Trick8b1496c2012-11-28 05:13:28 +00002059 SchedDFSResult *DFSResult;
2060 BitVector *ScheduledTrees;
Andrew Trick1e94e982012-10-15 18:02:27 +00002061 bool MaximizeILP;
2062
Andrew Trick8b1496c2012-11-28 05:13:28 +00002063 ILPOrder(SchedDFSResult *dfs, BitVector *schedtrees, bool MaxILP)
2064 : DFSResult(dfs), ScheduledTrees(schedtrees), MaximizeILP(MaxILP) {}
Andrew Trick1e94e982012-10-15 18:02:27 +00002065
2066 /// \brief Apply a less-than relation on node priority.
Andrew Trick8b1496c2012-11-28 05:13:28 +00002067 ///
2068 /// (Return true if A comes after B in the Q.)
Andrew Trick1e94e982012-10-15 18:02:27 +00002069 bool operator()(const SUnit *A, const SUnit *B) const {
Andrew Trick8b1496c2012-11-28 05:13:28 +00002070 unsigned SchedTreeA = DFSResult->getSubtreeID(A);
2071 unsigned SchedTreeB = DFSResult->getSubtreeID(B);
2072 if (SchedTreeA != SchedTreeB) {
2073 // Unscheduled trees have lower priority.
2074 if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
2075 return ScheduledTrees->test(SchedTreeB);
2076
2077 // Trees with shallower connections have have lower priority.
2078 if (DFSResult->getSubtreeLevel(SchedTreeA)
2079 != DFSResult->getSubtreeLevel(SchedTreeB)) {
2080 return DFSResult->getSubtreeLevel(SchedTreeA)
2081 < DFSResult->getSubtreeLevel(SchedTreeB);
2082 }
2083 }
Andrew Trick1e94e982012-10-15 18:02:27 +00002084 if (MaximizeILP)
Andrew Trick8b1496c2012-11-28 05:13:28 +00002085 return DFSResult->getILP(A) < DFSResult->getILP(B);
Andrew Trick1e94e982012-10-15 18:02:27 +00002086 else
Andrew Trick8b1496c2012-11-28 05:13:28 +00002087 return DFSResult->getILP(A) > DFSResult->getILP(B);
Andrew Trick1e94e982012-10-15 18:02:27 +00002088 }
2089};
2090
2091/// \brief Schedule based on the ILP metric.
2092class ILPScheduler : public MachineSchedStrategy {
Andrew Trick8b1496c2012-11-28 05:13:28 +00002093 /// In case all subtrees are eventually connected to a common root through
2094 /// data dependence (e.g. reduction), place an upper limit on their size.
2095 ///
2096 /// FIXME: A subtree limit is generally good, but in the situation commented
2097 /// above, where multiple similar subtrees feed a common root, we should
2098 /// only split at a point where the resulting subtrees will be balanced.
2099 /// (a motivating test case must be found).
2100 static const unsigned SubtreeLimit = 16;
2101
2102 SchedDFSResult DFSResult;
2103 BitVector ScheduledTrees;
Andrew Trick1e94e982012-10-15 18:02:27 +00002104 ILPOrder Cmp;
2105
2106 std::vector<SUnit*> ReadyQ;
2107public:
2108 ILPScheduler(bool MaximizeILP)
Andrew Trick8b1496c2012-11-28 05:13:28 +00002109 : DFSResult(/*BottomUp=*/true, SubtreeLimit),
2110 Cmp(&DFSResult, &ScheduledTrees, MaximizeILP) {}
Andrew Trick1e94e982012-10-15 18:02:27 +00002111
2112 virtual void initialize(ScheduleDAGMI *DAG) {
2113 ReadyQ.clear();
Andrew Trick8b1496c2012-11-28 05:13:28 +00002114 DFSResult.clear();
2115 DFSResult.resize(DAG->SUnits.size());
2116 ScheduledTrees.clear();
Andrew Trick1e94e982012-10-15 18:02:27 +00002117 }
2118
2119 virtual void registerRoots() {
Andrew Trick8b1496c2012-11-28 05:13:28 +00002120 DFSResult.compute(ReadyQ);
2121 ScheduledTrees.resize(DFSResult.getNumSubtrees());
Benjamin Kramer5175fd92012-11-29 14:36:26 +00002122 // Restore the heap in ReadyQ with the updated DFS results.
2123 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
Andrew Trick1e94e982012-10-15 18:02:27 +00002124 }
2125
2126 /// Implement MachineSchedStrategy interface.
2127 /// -----------------------------------------
2128
Andrew Trick8b1496c2012-11-28 05:13:28 +00002129 /// Callback to select the highest priority node from the ready Q.
Andrew Trick1e94e982012-10-15 18:02:27 +00002130 virtual SUnit *pickNode(bool &IsTopNode) {
2131 if (ReadyQ.empty()) return NULL;
2132 pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2133 SUnit *SU = ReadyQ.back();
2134 ReadyQ.pop_back();
2135 IsTopNode = false;
Andrew Trick8b1496c2012-11-28 05:13:28 +00002136 DEBUG(dbgs() << "*** Scheduling " << "SU(" << SU->NodeNum << "): "
2137 << *SU->getInstr()
2138 << " ILP: " << DFSResult.getILP(SU)
2139 << " Tree: " << DFSResult.getSubtreeID(SU) << " @"
2140 << DFSResult.getSubtreeLevel(DFSResult.getSubtreeID(SU))<< '\n');
Andrew Trick1e94e982012-10-15 18:02:27 +00002141 return SU;
2142 }
2143
Andrew Trick8b1496c2012-11-28 05:13:28 +00002144 /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
2145 /// DFSResults, and resort the priority Q.
2146 virtual void schedNode(SUnit *SU, bool IsTopNode) {
2147 assert(!IsTopNode && "SchedDFSResult needs bottom-up");
2148 if (!ScheduledTrees.test(DFSResult.getSubtreeID(SU))) {
2149 ScheduledTrees.set(DFSResult.getSubtreeID(SU));
2150 DFSResult.scheduleTree(DFSResult.getSubtreeID(SU));
2151 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2152 }
2153 }
Andrew Trick1e94e982012-10-15 18:02:27 +00002154
2155 virtual void releaseTopNode(SUnit *) { /*only called for top roots*/ }
2156
2157 virtual void releaseBottomNode(SUnit *SU) {
2158 ReadyQ.push_back(SU);
2159 std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2160 }
2161};
2162} // namespace
2163
2164static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
2165 return new ScheduleDAGMI(C, new ILPScheduler(true));
2166}
2167static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
2168 return new ScheduleDAGMI(C, new ILPScheduler(false));
2169}
2170static MachineSchedRegistry ILPMaxRegistry(
2171 "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
2172static MachineSchedRegistry ILPMinRegistry(
2173 "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
2174
2175//===----------------------------------------------------------------------===//
Andrew Trick5edf2f02012-01-14 02:17:06 +00002176// Machine Instruction Shuffler for Correctness Testing
2177//===----------------------------------------------------------------------===//
2178
Andrew Trick96f678f2012-01-13 06:30:30 +00002179#ifndef NDEBUG
2180namespace {
Andrew Trick17d35e52012-03-14 04:00:41 +00002181/// Apply a less-than relation on the node order, which corresponds to the
2182/// instruction order prior to scheduling. IsReverse implements greater-than.
2183template<bool IsReverse>
2184struct SUnitOrder {
Andrew Trickc6cf11b2012-01-17 06:55:07 +00002185 bool operator()(SUnit *A, SUnit *B) const {
Andrew Trick17d35e52012-03-14 04:00:41 +00002186 if (IsReverse)
2187 return A->NodeNum > B->NodeNum;
2188 else
2189 return A->NodeNum < B->NodeNum;
Andrew Trickc6cf11b2012-01-17 06:55:07 +00002190 }
2191};
2192
Andrew Trick96f678f2012-01-13 06:30:30 +00002193/// Reorder instructions as much as possible.
Andrew Trick17d35e52012-03-14 04:00:41 +00002194class InstructionShuffler : public MachineSchedStrategy {
2195 bool IsAlternating;
2196 bool IsTopDown;
2197
2198 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
2199 // gives nodes with a higher number higher priority causing the latest
2200 // instructions to be scheduled first.
2201 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
2202 TopQ;
2203 // When scheduling bottom-up, use greater-than as the queue priority.
2204 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
2205 BottomQ;
Andrew Trick96f678f2012-01-13 06:30:30 +00002206public:
Andrew Trick17d35e52012-03-14 04:00:41 +00002207 InstructionShuffler(bool alternate, bool topdown)
2208 : IsAlternating(alternate), IsTopDown(topdown) {}
Andrew Trick96f678f2012-01-13 06:30:30 +00002209
Andrew Trick17d35e52012-03-14 04:00:41 +00002210 virtual void initialize(ScheduleDAGMI *) {
2211 TopQ.clear();
2212 BottomQ.clear();
2213 }
Andrew Trickc6cf11b2012-01-17 06:55:07 +00002214
Andrew Trick17d35e52012-03-14 04:00:41 +00002215 /// Implement MachineSchedStrategy interface.
2216 /// -----------------------------------------
2217
2218 virtual SUnit *pickNode(bool &IsTopNode) {
2219 SUnit *SU;
2220 if (IsTopDown) {
2221 do {
2222 if (TopQ.empty()) return NULL;
2223 SU = TopQ.top();
2224 TopQ.pop();
2225 } while (SU->isScheduled);
2226 IsTopNode = true;
2227 }
2228 else {
2229 do {
2230 if (BottomQ.empty()) return NULL;
2231 SU = BottomQ.top();
2232 BottomQ.pop();
2233 } while (SU->isScheduled);
2234 IsTopNode = false;
2235 }
2236 if (IsAlternating)
2237 IsTopDown = !IsTopDown;
Andrew Trickc6cf11b2012-01-17 06:55:07 +00002238 return SU;
2239 }
2240
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002241 virtual void schedNode(SUnit *SU, bool IsTopNode) {}
2242
Andrew Trick17d35e52012-03-14 04:00:41 +00002243 virtual void releaseTopNode(SUnit *SU) {
2244 TopQ.push(SU);
2245 }
2246 virtual void releaseBottomNode(SUnit *SU) {
2247 BottomQ.push(SU);
Andrew Trick96f678f2012-01-13 06:30:30 +00002248 }
2249};
2250} // namespace
2251
Andrew Trickc174eaf2012-03-08 01:41:12 +00002252static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
Andrew Trick17d35e52012-03-14 04:00:41 +00002253 bool Alternate = !ForceTopDown && !ForceBottomUp;
2254 bool TopDown = !ForceBottomUp;
Benjamin Kramer689e0b42012-03-14 11:26:37 +00002255 assert((TopDown || !ForceTopDown) &&
Andrew Trick17d35e52012-03-14 04:00:41 +00002256 "-misched-topdown incompatible with -misched-bottomup");
2257 return new ScheduleDAGMI(C, new InstructionShuffler(Alternate, TopDown));
Andrew Trick96f678f2012-01-13 06:30:30 +00002258}
Andrew Trick17d35e52012-03-14 04:00:41 +00002259static MachineSchedRegistry ShufflerRegistry(
2260 "shuffle", "Shuffle machine instructions alternating directions",
2261 createInstructionShuffler);
Andrew Trick96f678f2012-01-13 06:30:30 +00002262#endif // !NDEBUG