blob: 7f4e36f2365b903c20176ef55203cc1ba3f96ec6 [file] [log] [blame]
Andrew Trick5429a6b2012-05-17 22:37:09 +00001//===- MachineScheduler.cpp - Machine Instruction Scheduler ---------------===//
Andrew Trick96f678f2012-01-13 06:30:30 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// MachineScheduler schedules machine instructions after phi elimination. It
11// preserves LiveIntervals so it can be invoked before register allocation.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "misched"
16
Andrew Trickc174eaf2012-03-08 01:41:12 +000017#include "llvm/CodeGen/MachineScheduler.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000018#include "llvm/ADT/OwningPtr.h"
19#include "llvm/ADT/PriorityQueue.h"
20#include "llvm/Analysis/AliasAnalysis.h"
21#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000022#include "llvm/CodeGen/Passes.h"
Andrew Trick15252602012-06-06 20:29:31 +000023#include "llvm/CodeGen/RegisterClassInfo.h"
Andrew Trick53e98a22012-11-28 05:13:24 +000024#include "llvm/CodeGen/ScheduleDFS.h"
Andrew Trick0a39d4e2012-05-24 22:11:09 +000025#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000026#include "llvm/Support/CommandLine.h"
27#include "llvm/Support/Debug.h"
28#include "llvm/Support/ErrorHandling.h"
Andrew Trick30849792013-01-25 07:45:29 +000029#include "llvm/Support/GraphWriter.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000030#include "llvm/Support/raw_ostream.h"
Andrew Trickc6cf11b2012-01-17 06:55:07 +000031#include <queue>
32
Andrew Trick96f678f2012-01-13 06:30:30 +000033using namespace llvm;
34
Andrew Trick78e5efe2012-09-11 00:39:15 +000035namespace llvm {
36cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
37 cl::desc("Force top-down list scheduling"));
38cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
39 cl::desc("Force bottom-up list scheduling"));
40}
Andrew Trick17d35e52012-03-14 04:00:41 +000041
Andrew Trick0df7f882012-03-07 00:18:25 +000042#ifndef NDEBUG
43static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
44 cl::desc("Pop up a window to show MISched dags after they are processed"));
Lang Hames23f1cbb2012-03-19 18:38:38 +000045
46static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
47 cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
Andrew Trick0df7f882012-03-07 00:18:25 +000048#else
49static bool ViewMISchedDAGs = false;
50#endif // NDEBUG
51
Andrew Trick9b5caaa2012-11-12 19:40:10 +000052// Experimental heuristics
53static cl::opt<bool> EnableLoadCluster("misched-cluster", cl::Hidden,
Andrew Trickad1cc1d2012-11-13 08:47:29 +000054 cl::desc("Enable load clustering."), cl::init(true));
Andrew Trick9b5caaa2012-11-12 19:40:10 +000055
Andrew Trick6996fd02012-11-12 19:52:20 +000056// Experimental heuristics
57static cl::opt<bool> EnableMacroFusion("misched-fusion", cl::Hidden,
Andrew Trickad1cc1d2012-11-13 08:47:29 +000058 cl::desc("Enable scheduling for macro fusion."), cl::init(true));
Andrew Trick6996fd02012-11-12 19:52:20 +000059
Andrew Trickfff2d3a2013-03-08 05:40:34 +000060static cl::opt<bool> VerifyScheduling("verify-misched", cl::Hidden,
61 cl::desc("Verify machine instrs before and after machine scheduling"));
62
Andrew Trick178f7d02013-01-25 04:01:04 +000063// DAG subtrees must have at least this many nodes.
64static const unsigned MinSubtreeSize = 8;
65
Andrew Trick5edf2f02012-01-14 02:17:06 +000066//===----------------------------------------------------------------------===//
67// Machine Instruction Scheduling Pass and Registry
68//===----------------------------------------------------------------------===//
69
Andrew Trick86b7e2a2012-04-24 20:36:19 +000070MachineSchedContext::MachineSchedContext():
71 MF(0), MLI(0), MDT(0), PassConfig(0), AA(0), LIS(0) {
72 RegClassInfo = new RegisterClassInfo();
73}
74
75MachineSchedContext::~MachineSchedContext() {
76 delete RegClassInfo;
77}
78
Andrew Trick96f678f2012-01-13 06:30:30 +000079namespace {
Andrew Trick42b7a712012-01-17 06:55:03 +000080/// MachineScheduler runs after coalescing and before register allocation.
Andrew Trickc174eaf2012-03-08 01:41:12 +000081class MachineScheduler : public MachineSchedContext,
82 public MachineFunctionPass {
Andrew Trick96f678f2012-01-13 06:30:30 +000083public:
Andrew Trick42b7a712012-01-17 06:55:03 +000084 MachineScheduler();
Andrew Trick96f678f2012-01-13 06:30:30 +000085
86 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
87
88 virtual void releaseMemory() {}
89
90 virtual bool runOnMachineFunction(MachineFunction&);
91
92 virtual void print(raw_ostream &O, const Module* = 0) const;
93
94 static char ID; // Class identification, replacement for typeinfo
95};
96} // namespace
97
Andrew Trick42b7a712012-01-17 06:55:03 +000098char MachineScheduler::ID = 0;
Andrew Trick96f678f2012-01-13 06:30:30 +000099
Andrew Trick42b7a712012-01-17 06:55:03 +0000100char &llvm::MachineSchedulerID = MachineScheduler::ID;
Andrew Trick96f678f2012-01-13 06:30:30 +0000101
Andrew Trick42b7a712012-01-17 06:55:03 +0000102INITIALIZE_PASS_BEGIN(MachineScheduler, "misched",
Andrew Trick96f678f2012-01-13 06:30:30 +0000103 "Machine Instruction Scheduler", false, false)
104INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
105INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
106INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
Andrew Trick42b7a712012-01-17 06:55:03 +0000107INITIALIZE_PASS_END(MachineScheduler, "misched",
Andrew Trick96f678f2012-01-13 06:30:30 +0000108 "Machine Instruction Scheduler", false, false)
109
Andrew Trick42b7a712012-01-17 06:55:03 +0000110MachineScheduler::MachineScheduler()
Andrew Trickc174eaf2012-03-08 01:41:12 +0000111: MachineFunctionPass(ID) {
Andrew Trick42b7a712012-01-17 06:55:03 +0000112 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Andrew Trick96f678f2012-01-13 06:30:30 +0000113}
114
Andrew Trick42b7a712012-01-17 06:55:03 +0000115void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
Andrew Trick96f678f2012-01-13 06:30:30 +0000116 AU.setPreservesCFG();
117 AU.addRequiredID(MachineDominatorsID);
118 AU.addRequired<MachineLoopInfo>();
119 AU.addRequired<AliasAnalysis>();
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000120 AU.addRequired<TargetPassConfig>();
Andrew Trick96f678f2012-01-13 06:30:30 +0000121 AU.addRequired<SlotIndexes>();
122 AU.addPreserved<SlotIndexes>();
123 AU.addRequired<LiveIntervals>();
124 AU.addPreserved<LiveIntervals>();
Andrew Trick96f678f2012-01-13 06:30:30 +0000125 MachineFunctionPass::getAnalysisUsage(AU);
126}
127
Andrew Trick96f678f2012-01-13 06:30:30 +0000128MachinePassRegistry MachineSchedRegistry::Registry;
129
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000130/// A dummy default scheduler factory indicates whether the scheduler
131/// is overridden on the command line.
132static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
133 return 0;
134}
Andrew Trick96f678f2012-01-13 06:30:30 +0000135
136/// MachineSchedOpt allows command line selection of the scheduler.
137static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
138 RegisterPassParser<MachineSchedRegistry> >
139MachineSchedOpt("misched",
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000140 cl::init(&useDefaultMachineSched), cl::Hidden,
Andrew Trick96f678f2012-01-13 06:30:30 +0000141 cl::desc("Machine instruction scheduler to use"));
142
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000143static MachineSchedRegistry
Andrew Trick17d35e52012-03-14 04:00:41 +0000144DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000145 useDefaultMachineSched);
146
Andrew Trick17d35e52012-03-14 04:00:41 +0000147/// Forward declare the standard machine scheduler. This will be used as the
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000148/// default scheduler if the target does not set a default.
Andrew Trick17d35e52012-03-14 04:00:41 +0000149static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C);
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000150
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000151
152/// Decrement this iterator until reaching the top or a non-debug instr.
153static MachineBasicBlock::iterator
154priorNonDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator Beg) {
155 assert(I != Beg && "reached the top of the region, cannot decrement");
156 while (--I != Beg) {
157 if (!I->isDebugValue())
158 break;
159 }
160 return I;
161}
162
163/// If this iterator is a debug value, increment until reaching the End or a
164/// non-debug instruction.
165static MachineBasicBlock::iterator
166nextIfDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator End) {
Andrew Trick811d92682012-05-17 18:35:03 +0000167 for(; I != End; ++I) {
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000168 if (!I->isDebugValue())
169 break;
170 }
171 return I;
172}
173
Andrew Trickcb058d52012-03-14 04:00:38 +0000174/// Top-level MachineScheduler pass driver.
175///
176/// Visit blocks in function order. Divide each block into scheduling regions
Andrew Trick17d35e52012-03-14 04:00:41 +0000177/// and visit them bottom-up. Visiting regions bottom-up is not required, but is
178/// consistent with the DAG builder, which traverses the interior of the
179/// scheduling regions bottom-up.
Andrew Trickcb058d52012-03-14 04:00:38 +0000180///
181/// This design avoids exposing scheduling boundaries to the DAG builder,
Andrew Trick17d35e52012-03-14 04:00:41 +0000182/// simplifying the DAG builder's support for "special" target instructions.
183/// At the same time the design allows target schedulers to operate across
Andrew Trickcb058d52012-03-14 04:00:38 +0000184/// scheduling boundaries, for example to bundle the boudary instructions
185/// without reordering them. This creates complexity, because the target
186/// scheduler must update the RegionBegin and RegionEnd positions cached by
187/// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
188/// design would be to split blocks at scheduling boundaries, but LLVM has a
189/// general bias against block splitting purely for implementation simplicity.
Andrew Trick42b7a712012-01-17 06:55:03 +0000190bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
Andrew Trick89c324b2012-05-10 21:06:21 +0000191 DEBUG(dbgs() << "Before MISsched:\n"; mf.print(dbgs()));
192
Andrew Trick96f678f2012-01-13 06:30:30 +0000193 // Initialize the context of the pass.
194 MF = &mf;
195 MLI = &getAnalysis<MachineLoopInfo>();
196 MDT = &getAnalysis<MachineDominatorTree>();
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000197 PassConfig = &getAnalysis<TargetPassConfig>();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000198 AA = &getAnalysis<AliasAnalysis>();
199
Lang Hames907cc8f2012-01-27 22:36:19 +0000200 LIS = &getAnalysis<LiveIntervals>();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000201 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
Andrew Trick96f678f2012-01-13 06:30:30 +0000202
Andrew Trickfff2d3a2013-03-08 05:40:34 +0000203 if (VerifyScheduling) {
204 DEBUG(LIS->print(dbgs()));
205 MF->verify(this, "Before machine scheduling.");
206 }
Andrew Trick86b7e2a2012-04-24 20:36:19 +0000207 RegClassInfo->runOnMachineFunction(*MF);
Andrew Trick006e1ab2012-04-24 17:56:43 +0000208
Andrew Trick96f678f2012-01-13 06:30:30 +0000209 // Select the scheduler, or set the default.
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000210 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
211 if (Ctor == useDefaultMachineSched) {
212 // Get the default scheduler set by the target.
213 Ctor = MachineSchedRegistry::getDefault();
214 if (!Ctor) {
Andrew Trick17d35e52012-03-14 04:00:41 +0000215 Ctor = createConvergingSched;
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000216 MachineSchedRegistry::setDefault(Ctor);
217 }
Andrew Trick96f678f2012-01-13 06:30:30 +0000218 }
219 // Instantiate the selected scheduler.
220 OwningPtr<ScheduleDAGInstrs> Scheduler(Ctor(this));
221
222 // Visit all machine basic blocks.
Andrew Trick006e1ab2012-04-24 17:56:43 +0000223 //
224 // TODO: Visit blocks in global postorder or postorder within the bottom-up
225 // loop tree. Then we can optionally compute global RegPressure.
Andrew Trick96f678f2012-01-13 06:30:30 +0000226 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
227 MBB != MBBEnd; ++MBB) {
228
Andrew Trick1fabd9f2012-03-09 08:02:51 +0000229 Scheduler->startBlock(MBB);
230
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000231 // Break the block into scheduling regions [I, RegionEnd), and schedule each
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +0000232 // region as soon as it is discovered. RegionEnd points the scheduling
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000233 // boundary at the bottom of the region. The DAG does not include RegionEnd,
234 // but the region does (i.e. the next RegionEnd is above the previous
235 // RegionBegin). If the current block has no terminator then RegionEnd ==
236 // MBB->end() for the bottom region.
237 //
238 // The Scheduler may insert instructions during either schedule() or
239 // exitRegion(), even for empty regions. So the local iterators 'I' and
240 // 'RegionEnd' are invalid across these calls.
Andrew Trick22764532012-11-06 07:10:34 +0000241 unsigned RemainingInstrs = MBB->size();
Andrew Trick7799eb42012-03-09 03:46:39 +0000242 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000243 RegionEnd != MBB->begin(); RegionEnd = Scheduler->begin()) {
Andrew Trick006e1ab2012-04-24 17:56:43 +0000244
Andrew Trick1fabd9f2012-03-09 08:02:51 +0000245 // Avoid decrementing RegionEnd for blocks with no terminator.
246 if (RegionEnd != MBB->end()
247 || TII->isSchedulingBoundary(llvm::prior(RegionEnd), MBB, *MF)) {
248 --RegionEnd;
249 // Count the boundary instruction.
Andrew Trick22764532012-11-06 07:10:34 +0000250 --RemainingInstrs;
Andrew Trick1fabd9f2012-03-09 08:02:51 +0000251 }
252
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000253 // The next region starts above the previous region. Look backward in the
254 // instruction stream until we find the nearest boundary.
255 MachineBasicBlock::iterator I = RegionEnd;
Andrew Trick22764532012-11-06 07:10:34 +0000256 for(;I != MBB->begin(); --I, --RemainingInstrs) {
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000257 if (TII->isSchedulingBoundary(llvm::prior(I), MBB, *MF))
258 break;
259 }
Andrew Trick47c14452012-03-07 05:21:52 +0000260 // Notify the scheduler of the region, even if we may skip scheduling
261 // it. Perhaps it still needs to be bundled.
Andrew Trick22764532012-11-06 07:10:34 +0000262 Scheduler->enterRegion(MBB, I, RegionEnd, RemainingInstrs);
Andrew Trick47c14452012-03-07 05:21:52 +0000263
264 // Skip empty scheduling regions (0 or 1 schedulable instructions).
265 if (I == RegionEnd || I == llvm::prior(RegionEnd)) {
Andrew Trick47c14452012-03-07 05:21:52 +0000266 // Close the current region. Bundle the terminator if needed.
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000267 // This invalidates 'RegionEnd' and 'I'.
Andrew Trick47c14452012-03-07 05:21:52 +0000268 Scheduler->exitRegion();
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000269 continue;
Andrew Trick3c58ba82012-01-14 02:17:18 +0000270 }
Andrew Trickbb0a2422012-05-24 22:11:14 +0000271 DEBUG(dbgs() << "********** MI Scheduling **********\n");
Craig Topper96601ca2012-08-22 06:07:19 +0000272 DEBUG(dbgs() << MF->getName()
Andrew Trickc8554232013-01-25 07:45:31 +0000273 << ":BB#" << MBB->getNumber() << " " << MBB->getName()
274 << "\n From: " << *I << " To: ";
Andrew Trick291411c2012-02-08 02:17:21 +0000275 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
276 else dbgs() << "End";
Andrew Trick22764532012-11-06 07:10:34 +0000277 dbgs() << " Remaining: " << RemainingInstrs << "\n");
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000278
Andrew Trickd24da972012-03-09 03:46:42 +0000279 // Schedule a region: possibly reorder instructions.
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000280 // This invalidates 'RegionEnd' and 'I'.
Andrew Trick953be892012-03-07 23:00:49 +0000281 Scheduler->schedule();
Andrew Trickd24da972012-03-09 03:46:42 +0000282
283 // Close the current region.
Andrew Trick47c14452012-03-07 05:21:52 +0000284 Scheduler->exitRegion();
285
286 // Scheduling has invalidated the current iterator 'I'. Ask the
287 // scheduler for the top of it's scheduled region.
288 RegionEnd = Scheduler->begin();
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000289 }
Andrew Trick22764532012-11-06 07:10:34 +0000290 assert(RemainingInstrs == 0 && "Instruction count mismatch!");
Andrew Trick953be892012-03-07 23:00:49 +0000291 Scheduler->finishBlock();
Andrew Trick96f678f2012-01-13 06:30:30 +0000292 }
Andrew Trick830da402012-04-01 07:24:23 +0000293 Scheduler->finalizeSchedule();
Andrew Trickaad37f12012-03-21 04:12:12 +0000294 DEBUG(LIS->print(dbgs()));
Andrew Trickfff2d3a2013-03-08 05:40:34 +0000295 if (VerifyScheduling)
296 MF->verify(this, "After machine scheduling.");
Andrew Trick96f678f2012-01-13 06:30:30 +0000297 return true;
298}
299
Andrew Trick42b7a712012-01-17 06:55:03 +0000300void MachineScheduler::print(raw_ostream &O, const Module* m) const {
Andrew Trick96f678f2012-01-13 06:30:30 +0000301 // unimplemented
302}
303
Manman Renb720be62012-09-11 22:23:19 +0000304#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Andrew Trick78e5efe2012-09-11 00:39:15 +0000305void ReadyQueue::dump() {
306 dbgs() << Name << ": ";
307 for (unsigned i = 0, e = Queue.size(); i < e; ++i)
308 dbgs() << Queue[i]->NodeNum << " ";
309 dbgs() << "\n";
310}
311#endif
Andrew Trick17d35e52012-03-14 04:00:41 +0000312
313//===----------------------------------------------------------------------===//
314// ScheduleDAGMI - Base class for MachineInstr scheduling with LiveIntervals
315// preservation.
316//===----------------------------------------------------------------------===//
317
Andrew Trick178f7d02013-01-25 04:01:04 +0000318ScheduleDAGMI::~ScheduleDAGMI() {
319 delete DFSResult;
320 DeleteContainerPointers(Mutations);
321 delete SchedImpl;
322}
323
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000324bool ScheduleDAGMI::addEdge(SUnit *SuccSU, const SDep &PredDep) {
Andrew Trick6996fd02012-11-12 19:52:20 +0000325 if (SuccSU != &ExitSU) {
326 // Do not use WillCreateCycle, it assumes SD scheduling.
327 // If Pred is reachable from Succ, then the edge creates a cycle.
328 if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
329 return false;
330 Topo.AddPred(SuccSU, PredDep.getSUnit());
331 }
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000332 SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
333 // Return true regardless of whether a new edge needed to be inserted.
334 return true;
335}
336
Andrew Trickc174eaf2012-03-08 01:41:12 +0000337/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
338/// NumPredsLeft reaches zero, release the successor node.
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000339///
340/// FIXME: Adjust SuccSU height based on MinLatency.
Andrew Trick17d35e52012-03-14 04:00:41 +0000341void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
Andrew Trickc174eaf2012-03-08 01:41:12 +0000342 SUnit *SuccSU = SuccEdge->getSUnit();
343
Andrew Trickae692f22012-11-12 19:28:57 +0000344 if (SuccEdge->isWeak()) {
345 --SuccSU->WeakPredsLeft;
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000346 if (SuccEdge->isCluster())
347 NextClusterSucc = SuccSU;
Andrew Trickae692f22012-11-12 19:28:57 +0000348 return;
349 }
Andrew Trickc174eaf2012-03-08 01:41:12 +0000350#ifndef NDEBUG
351 if (SuccSU->NumPredsLeft == 0) {
352 dbgs() << "*** Scheduling failed! ***\n";
353 SuccSU->dump(this);
354 dbgs() << " has been released too many times!\n";
355 llvm_unreachable(0);
356 }
357#endif
358 --SuccSU->NumPredsLeft;
359 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
Andrew Trick17d35e52012-03-14 04:00:41 +0000360 SchedImpl->releaseTopNode(SuccSU);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000361}
362
363/// releaseSuccessors - Call releaseSucc on each of SU's successors.
Andrew Trick17d35e52012-03-14 04:00:41 +0000364void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
Andrew Trickc174eaf2012-03-08 01:41:12 +0000365 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
366 I != E; ++I) {
367 releaseSucc(SU, &*I);
368 }
369}
370
Andrew Trick17d35e52012-03-14 04:00:41 +0000371/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
372/// NumSuccsLeft reaches zero, release the predecessor node.
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000373///
374/// FIXME: Adjust PredSU height based on MinLatency.
Andrew Trick17d35e52012-03-14 04:00:41 +0000375void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
376 SUnit *PredSU = PredEdge->getSUnit();
377
Andrew Trickae692f22012-11-12 19:28:57 +0000378 if (PredEdge->isWeak()) {
379 --PredSU->WeakSuccsLeft;
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000380 if (PredEdge->isCluster())
381 NextClusterPred = PredSU;
Andrew Trickae692f22012-11-12 19:28:57 +0000382 return;
383 }
Andrew Trick17d35e52012-03-14 04:00:41 +0000384#ifndef NDEBUG
385 if (PredSU->NumSuccsLeft == 0) {
386 dbgs() << "*** Scheduling failed! ***\n";
387 PredSU->dump(this);
388 dbgs() << " has been released too many times!\n";
389 llvm_unreachable(0);
390 }
391#endif
392 --PredSU->NumSuccsLeft;
393 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
394 SchedImpl->releaseBottomNode(PredSU);
395}
396
397/// releasePredecessors - Call releasePred on each of SU's predecessors.
398void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
399 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
400 I != E; ++I) {
401 releasePred(SU, &*I);
402 }
403}
404
405void ScheduleDAGMI::moveInstruction(MachineInstr *MI,
406 MachineBasicBlock::iterator InsertPos) {
Andrew Trick811d92682012-05-17 18:35:03 +0000407 // Advance RegionBegin if the first instruction moves down.
Andrew Trick1ce062f2012-03-21 04:12:10 +0000408 if (&*RegionBegin == MI)
Andrew Trick811d92682012-05-17 18:35:03 +0000409 ++RegionBegin;
410
411 // Update the instruction stream.
Andrew Trick17d35e52012-03-14 04:00:41 +0000412 BB->splice(InsertPos, BB, MI);
Andrew Trick811d92682012-05-17 18:35:03 +0000413
414 // Update LiveIntervals
Andrew Trick27c28ce2012-10-16 00:22:51 +0000415 LIS->handleMove(MI, /*UpdateFlags=*/true);
Andrew Trick811d92682012-05-17 18:35:03 +0000416
417 // Recede RegionBegin if an instruction moves above the first.
Andrew Trick17d35e52012-03-14 04:00:41 +0000418 if (RegionBegin == InsertPos)
419 RegionBegin = MI;
420}
421
Andrew Trick0b0d8992012-03-21 04:12:07 +0000422bool ScheduleDAGMI::checkSchedLimit() {
423#ifndef NDEBUG
424 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
425 CurrentTop = CurrentBottom;
426 return false;
427 }
428 ++NumInstrsScheduled;
429#endif
430 return true;
431}
432
Andrew Trick006e1ab2012-04-24 17:56:43 +0000433/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
434/// crossing a scheduling boundary. [begin, end) includes all instructions in
435/// the region, including the boundary itself and single-instruction regions
436/// that don't get scheduled.
437void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
438 MachineBasicBlock::iterator begin,
439 MachineBasicBlock::iterator end,
440 unsigned endcount)
441{
442 ScheduleDAGInstrs::enterRegion(bb, begin, end, endcount);
Andrew Trick7f8ab782012-05-10 21:06:10 +0000443
444 // For convenience remember the end of the liveness region.
445 LiveRegionEnd =
446 (RegionEnd == bb->end()) ? RegionEnd : llvm::next(RegionEnd);
447}
448
449// Setup the register pressure trackers for the top scheduled top and bottom
450// scheduled regions.
451void ScheduleDAGMI::initRegPressure() {
452 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin);
453 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
454
455 // Close the RPTracker to finalize live ins.
456 RPTracker.closeRegion();
457
Andrew Trickbb0a2422012-05-24 22:11:14 +0000458 DEBUG(RPTracker.getPressure().dump(TRI));
459
Andrew Trick7f8ab782012-05-10 21:06:10 +0000460 // Initialize the live ins and live outs.
461 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
462 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
463
464 // Close one end of the tracker so we can call
465 // getMaxUpward/DownwardPressureDelta before advancing across any
466 // instructions. This converts currently live regs into live ins/outs.
467 TopRPTracker.closeTop();
468 BotRPTracker.closeBottom();
469
470 // Account for liveness generated by the region boundary.
471 if (LiveRegionEnd != RegionEnd)
472 BotRPTracker.recede();
473
474 assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000475
476 // Cache the list of excess pressure sets in this region. This will also track
477 // the max pressure in the scheduled code for these sets.
478 RegionCriticalPSets.clear();
Jakub Staszakb74564a2013-01-25 21:44:27 +0000479 const std::vector<unsigned> &RegionPressure =
480 RPTracker.getPressure().MaxSetPressure;
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000481 for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
482 unsigned Limit = TRI->getRegPressureSetLimit(i);
Andrew Trick78e5efe2012-09-11 00:39:15 +0000483 DEBUG(dbgs() << TRI->getRegPressureSetName(i)
484 << "Limit " << Limit
485 << " Actual " << RegionPressure[i] << "\n");
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000486 if (RegionPressure[i] > Limit)
487 RegionCriticalPSets.push_back(PressureElement(i, 0));
488 }
489 DEBUG(dbgs() << "Excess PSets: ";
490 for (unsigned i = 0, e = RegionCriticalPSets.size(); i != e; ++i)
491 dbgs() << TRI->getRegPressureSetName(
492 RegionCriticalPSets[i].PSetID) << " ";
493 dbgs() << "\n");
494}
495
496// FIXME: When the pressure tracker deals in pressure differences then we won't
497// iterate over all RegionCriticalPSets[i].
498void ScheduleDAGMI::
Jakub Staszakb717a502013-02-16 15:47:26 +0000499updateScheduledPressure(const std::vector<unsigned> &NewMaxPressure) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000500 for (unsigned i = 0, e = RegionCriticalPSets.size(); i < e; ++i) {
501 unsigned ID = RegionCriticalPSets[i].PSetID;
502 int &MaxUnits = RegionCriticalPSets[i].UnitIncrease;
503 if ((int)NewMaxPressure[ID] > MaxUnits)
504 MaxUnits = NewMaxPressure[ID];
505 }
Andrew Trick006e1ab2012-04-24 17:56:43 +0000506}
507
Andrew Trick17d35e52012-03-14 04:00:41 +0000508/// schedule - Called back from MachineScheduler::runOnMachineFunction
Andrew Trick006e1ab2012-04-24 17:56:43 +0000509/// after setting up the current scheduling region. [RegionBegin, RegionEnd)
510/// only includes instructions that have DAG nodes, not scheduling boundaries.
Andrew Trick78e5efe2012-09-11 00:39:15 +0000511///
512/// This is a skeletal driver, with all the functionality pushed into helpers,
513/// so that it can be easilly extended by experimental schedulers. Generally,
514/// implementing MachineSchedStrategy should be sufficient to implement a new
515/// scheduling algorithm. However, if a scheduler further subclasses
516/// ScheduleDAGMI then it will want to override this virtual method in order to
517/// update any specialized state.
Andrew Trick17d35e52012-03-14 04:00:41 +0000518void ScheduleDAGMI::schedule() {
Andrew Trick78e5efe2012-09-11 00:39:15 +0000519 buildDAGWithRegPressure();
520
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000521 Topo.InitDAGTopologicalSorting();
522
Andrew Trickd039b382012-09-14 17:22:42 +0000523 postprocessDAG();
524
Andrew Trick4e1fb182013-01-25 06:33:57 +0000525 SmallVector<SUnit*, 8> TopRoots, BotRoots;
526 findRootsAndBiasEdges(TopRoots, BotRoots);
527
528 // Initialize the strategy before modifying the DAG.
529 // This may initialize a DFSResult to be used for queue priority.
530 SchedImpl->initialize(this);
531
Andrew Trick78e5efe2012-09-11 00:39:15 +0000532 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
533 SUnits[su].dumpAll(this));
Andrew Trick4e1fb182013-01-25 06:33:57 +0000534 if (ViewMISchedDAGs) viewGraph();
Andrew Trick78e5efe2012-09-11 00:39:15 +0000535
Andrew Trick4e1fb182013-01-25 06:33:57 +0000536 // Initialize ready queues now that the DAG and priority data are finalized.
537 initQueues(TopRoots, BotRoots);
Andrew Trick78e5efe2012-09-11 00:39:15 +0000538
539 bool IsTopNode = false;
540 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
Andrew Trick30c6ec22012-10-08 18:53:53 +0000541 assert(!SU->isScheduled && "Node already scheduled");
Andrew Trick78e5efe2012-09-11 00:39:15 +0000542 if (!checkSchedLimit())
543 break;
544
545 scheduleMI(SU, IsTopNode);
546
547 updateQueues(SU, IsTopNode);
548 }
549 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
550
551 placeDebugValues();
Andrew Trick3b87f622012-11-07 07:05:09 +0000552
553 DEBUG({
Andrew Trickb4221042012-11-28 03:42:47 +0000554 unsigned BBNum = begin()->getParent()->getNumber();
Andrew Trick3b87f622012-11-07 07:05:09 +0000555 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
556 dumpSchedule();
557 dbgs() << '\n';
558 });
Andrew Trick78e5efe2012-09-11 00:39:15 +0000559}
560
561/// Build the DAG and setup three register pressure trackers.
562void ScheduleDAGMI::buildDAGWithRegPressure() {
Andrew Trick7f8ab782012-05-10 21:06:10 +0000563 // Initialize the register pressure tracker used by buildSchedGraph.
564 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
Andrew Trick006e1ab2012-04-24 17:56:43 +0000565
Andrew Trick7f8ab782012-05-10 21:06:10 +0000566 // Account for liveness generate by the region boundary.
567 if (LiveRegionEnd != RegionEnd)
568 RPTracker.recede();
569
570 // Build the DAG, and compute current register pressure.
Andrew Trick006e1ab2012-04-24 17:56:43 +0000571 buildSchedGraph(AA, &RPTracker);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000572
Andrew Trick7f8ab782012-05-10 21:06:10 +0000573 // Initialize top/bottom trackers after computing region pressure.
574 initRegPressure();
Andrew Trick78e5efe2012-09-11 00:39:15 +0000575}
Andrew Trick7f8ab782012-05-10 21:06:10 +0000576
Andrew Trickd039b382012-09-14 17:22:42 +0000577/// Apply each ScheduleDAGMutation step in order.
578void ScheduleDAGMI::postprocessDAG() {
579 for (unsigned i = 0, e = Mutations.size(); i < e; ++i) {
580 Mutations[i]->apply(this);
581 }
582}
583
Andrew Trick4e1fb182013-01-25 06:33:57 +0000584void ScheduleDAGMI::computeDFSResult() {
Andrew Trick178f7d02013-01-25 04:01:04 +0000585 if (!DFSResult)
586 DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize);
587 DFSResult->clear();
Andrew Trick178f7d02013-01-25 04:01:04 +0000588 ScheduledTrees.clear();
Andrew Trick4e1fb182013-01-25 06:33:57 +0000589 DFSResult->resize(SUnits.size());
590 DFSResult->compute(SUnits);
Andrew Trick178f7d02013-01-25 04:01:04 +0000591 ScheduledTrees.resize(DFSResult->getNumSubtrees());
592}
593
Andrew Trick4e1fb182013-01-25 06:33:57 +0000594void ScheduleDAGMI::findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
595 SmallVectorImpl<SUnit*> &BotRoots) {
Andrew Trick1e94e982012-10-15 18:02:27 +0000596 for (std::vector<SUnit>::iterator
597 I = SUnits.begin(), E = SUnits.end(); I != E; ++I) {
Andrew Trickae692f22012-11-12 19:28:57 +0000598 SUnit *SU = &(*I);
Andrew Trick4c6a2ba2013-01-29 06:26:35 +0000599 assert(!SU->isBoundaryNode() && "Boundary node should not be in SUnits");
Andrew Trickdb417062013-01-24 02:09:57 +0000600
601 // Order predecessors so DFSResult follows the critical path.
602 SU->biasCriticalPath();
603
Andrew Trick1e94e982012-10-15 18:02:27 +0000604 // A SUnit is ready to top schedule if it has no predecessors.
Andrew Trick4c6a2ba2013-01-29 06:26:35 +0000605 if (!I->NumPredsLeft)
Andrew Trick4e1fb182013-01-25 06:33:57 +0000606 TopRoots.push_back(SU);
Andrew Trick1e94e982012-10-15 18:02:27 +0000607 // A SUnit is ready to bottom schedule if it has no successors.
Andrew Trick4c6a2ba2013-01-29 06:26:35 +0000608 if (!I->NumSuccsLeft)
Andrew Trickae692f22012-11-12 19:28:57 +0000609 BotRoots.push_back(SU);
Andrew Trick1e94e982012-10-15 18:02:27 +0000610 }
Andrew Trick4c6a2ba2013-01-29 06:26:35 +0000611 ExitSU.biasCriticalPath();
Andrew Trick1e94e982012-10-15 18:02:27 +0000612}
613
Andrew Trick78e5efe2012-09-11 00:39:15 +0000614/// Identify DAG roots and setup scheduler queues.
Andrew Trick4e1fb182013-01-25 06:33:57 +0000615void ScheduleDAGMI::initQueues(ArrayRef<SUnit*> TopRoots,
616 ArrayRef<SUnit*> BotRoots) {
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000617 NextClusterSucc = NULL;
618 NextClusterPred = NULL;
Andrew Trick1e94e982012-10-15 18:02:27 +0000619
Andrew Trickae692f22012-11-12 19:28:57 +0000620 // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
Andrew Trick4e1fb182013-01-25 06:33:57 +0000621 //
622 // Nodes with unreleased weak edges can still be roots.
623 // Release top roots in forward order.
624 for (SmallVectorImpl<SUnit*>::const_iterator
625 I = TopRoots.begin(), E = TopRoots.end(); I != E; ++I) {
626 SchedImpl->releaseTopNode(*I);
627 }
628 // Release bottom roots in reverse order so the higher priority nodes appear
629 // first. This is more natural and slightly more efficient.
630 for (SmallVectorImpl<SUnit*>::const_reverse_iterator
631 I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I) {
632 SchedImpl->releaseBottomNode(*I);
633 }
Andrew Trickae692f22012-11-12 19:28:57 +0000634
Andrew Trickc174eaf2012-03-08 01:41:12 +0000635 releaseSuccessors(&EntrySU);
Andrew Trick17d35e52012-03-14 04:00:41 +0000636 releasePredecessors(&ExitSU);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000637
Andrew Trick1e94e982012-10-15 18:02:27 +0000638 SchedImpl->registerRoots();
639
Andrew Trick657b75b2012-12-01 01:22:49 +0000640 // Advance past initial DebugValues.
641 assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000642 CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
Andrew Trick657b75b2012-12-01 01:22:49 +0000643 TopRPTracker.setPos(CurrentTop);
644
Andrew Trick17d35e52012-03-14 04:00:41 +0000645 CurrentBottom = RegionEnd;
Andrew Trick78e5efe2012-09-11 00:39:15 +0000646}
Andrew Trickc174eaf2012-03-08 01:41:12 +0000647
Andrew Trick78e5efe2012-09-11 00:39:15 +0000648/// Move an instruction and update register pressure.
649void ScheduleDAGMI::scheduleMI(SUnit *SU, bool IsTopNode) {
650 // Move the instruction to its new location in the instruction stream.
651 MachineInstr *MI = SU->getInstr();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000652
Andrew Trick78e5efe2012-09-11 00:39:15 +0000653 if (IsTopNode) {
654 assert(SU->isTopReady() && "node still has unscheduled dependencies");
655 if (&*CurrentTop == MI)
656 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
Andrew Trick17d35e52012-03-14 04:00:41 +0000657 else {
Andrew Trick78e5efe2012-09-11 00:39:15 +0000658 moveInstruction(MI, CurrentTop);
659 TopRPTracker.setPos(MI);
Andrew Trick17d35e52012-03-14 04:00:41 +0000660 }
Andrew Trick000b2502012-04-24 18:04:37 +0000661
Andrew Trick78e5efe2012-09-11 00:39:15 +0000662 // Update top scheduled pressure.
663 TopRPTracker.advance();
664 assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
665 updateScheduledPressure(TopRPTracker.getPressure().MaxSetPressure);
666 }
667 else {
668 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
669 MachineBasicBlock::iterator priorII =
670 priorNonDebug(CurrentBottom, CurrentTop);
671 if (&*priorII == MI)
672 CurrentBottom = priorII;
673 else {
674 if (&*CurrentTop == MI) {
675 CurrentTop = nextIfDebug(++CurrentTop, priorII);
676 TopRPTracker.setPos(CurrentTop);
677 }
678 moveInstruction(MI, CurrentBottom);
679 CurrentBottom = MI;
680 }
681 // Update bottom scheduled pressure.
682 BotRPTracker.recede();
683 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
684 updateScheduledPressure(BotRPTracker.getPressure().MaxSetPressure);
685 }
686}
687
688/// Update scheduler queues after scheduling an instruction.
689void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
690 // Release dependent instructions for scheduling.
691 if (IsTopNode)
692 releaseSuccessors(SU);
693 else
694 releasePredecessors(SU);
695
696 SU->isScheduled = true;
697
Andrew Trick178f7d02013-01-25 04:01:04 +0000698 if (DFSResult) {
699 unsigned SubtreeID = DFSResult->getSubtreeID(SU);
700 if (!ScheduledTrees.test(SubtreeID)) {
701 ScheduledTrees.set(SubtreeID);
702 DFSResult->scheduleTree(SubtreeID);
703 SchedImpl->scheduleTree(SubtreeID);
704 }
705 }
706
Andrew Trick78e5efe2012-09-11 00:39:15 +0000707 // Notify the scheduling strategy after updating the DAG.
708 SchedImpl->schedNode(SU, IsTopNode);
Andrew Trick000b2502012-04-24 18:04:37 +0000709}
710
711/// Reinsert any remaining debug_values, just like the PostRA scheduler.
712void ScheduleDAGMI::placeDebugValues() {
713 // If first instruction was a DBG_VALUE then put it back.
714 if (FirstDbgValue) {
715 BB->splice(RegionBegin, BB, FirstDbgValue);
716 RegionBegin = FirstDbgValue;
717 }
718
719 for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
720 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
721 std::pair<MachineInstr *, MachineInstr *> P = *prior(DI);
722 MachineInstr *DbgValue = P.first;
723 MachineBasicBlock::iterator OrigPrevMI = P.second;
Andrew Trick67bdd422012-12-01 01:22:38 +0000724 if (&*RegionBegin == DbgValue)
725 ++RegionBegin;
Andrew Trick000b2502012-04-24 18:04:37 +0000726 BB->splice(++OrigPrevMI, BB, DbgValue);
727 if (OrigPrevMI == llvm::prior(RegionEnd))
728 RegionEnd = DbgValue;
729 }
730 DbgValues.clear();
731 FirstDbgValue = NULL;
Andrew Trickc174eaf2012-03-08 01:41:12 +0000732}
733
Andrew Trick3b87f622012-11-07 07:05:09 +0000734#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
735void ScheduleDAGMI::dumpSchedule() const {
736 for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
737 if (SUnit *SU = getSUnit(&(*MI)))
738 SU->dump(this);
739 else
740 dbgs() << "Missing SUnit\n";
741 }
742}
743#endif
744
Andrew Trick6996fd02012-11-12 19:52:20 +0000745//===----------------------------------------------------------------------===//
746// LoadClusterMutation - DAG post-processing to cluster loads.
747//===----------------------------------------------------------------------===//
748
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000749namespace {
750/// \brief Post-process the DAG to create cluster edges between neighboring
751/// loads.
752class LoadClusterMutation : public ScheduleDAGMutation {
753 struct LoadInfo {
754 SUnit *SU;
755 unsigned BaseReg;
756 unsigned Offset;
757 LoadInfo(SUnit *su, unsigned reg, unsigned ofs)
758 : SU(su), BaseReg(reg), Offset(ofs) {}
759 };
760 static bool LoadInfoLess(const LoadClusterMutation::LoadInfo &LHS,
761 const LoadClusterMutation::LoadInfo &RHS);
762
763 const TargetInstrInfo *TII;
764 const TargetRegisterInfo *TRI;
765public:
766 LoadClusterMutation(const TargetInstrInfo *tii,
767 const TargetRegisterInfo *tri)
768 : TII(tii), TRI(tri) {}
769
770 virtual void apply(ScheduleDAGMI *DAG);
771protected:
772 void clusterNeighboringLoads(ArrayRef<SUnit*> Loads, ScheduleDAGMI *DAG);
773};
774} // anonymous
775
776bool LoadClusterMutation::LoadInfoLess(
777 const LoadClusterMutation::LoadInfo &LHS,
778 const LoadClusterMutation::LoadInfo &RHS) {
779 if (LHS.BaseReg != RHS.BaseReg)
780 return LHS.BaseReg < RHS.BaseReg;
781 return LHS.Offset < RHS.Offset;
782}
783
784void LoadClusterMutation::clusterNeighboringLoads(ArrayRef<SUnit*> Loads,
785 ScheduleDAGMI *DAG) {
786 SmallVector<LoadClusterMutation::LoadInfo,32> LoadRecords;
787 for (unsigned Idx = 0, End = Loads.size(); Idx != End; ++Idx) {
788 SUnit *SU = Loads[Idx];
789 unsigned BaseReg;
790 unsigned Offset;
791 if (TII->getLdStBaseRegImmOfs(SU->getInstr(), BaseReg, Offset, TRI))
792 LoadRecords.push_back(LoadInfo(SU, BaseReg, Offset));
793 }
794 if (LoadRecords.size() < 2)
795 return;
796 std::sort(LoadRecords.begin(), LoadRecords.end(), LoadInfoLess);
797 unsigned ClusterLength = 1;
798 for (unsigned Idx = 0, End = LoadRecords.size(); Idx < (End - 1); ++Idx) {
799 if (LoadRecords[Idx].BaseReg != LoadRecords[Idx+1].BaseReg) {
800 ClusterLength = 1;
801 continue;
802 }
803
804 SUnit *SUa = LoadRecords[Idx].SU;
805 SUnit *SUb = LoadRecords[Idx+1].SU;
Andrew Tricka7d2d562012-11-12 21:28:10 +0000806 if (TII->shouldClusterLoads(SUa->getInstr(), SUb->getInstr(), ClusterLength)
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000807 && DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
808
809 DEBUG(dbgs() << "Cluster loads SU(" << SUa->NodeNum << ") - SU("
810 << SUb->NodeNum << ")\n");
811 // Copy successor edges from SUa to SUb. Interleaving computation
812 // dependent on SUa can prevent load combining due to register reuse.
813 // Predecessor edges do not need to be copied from SUb to SUa since nearby
814 // loads should have effectively the same inputs.
815 for (SUnit::const_succ_iterator
816 SI = SUa->Succs.begin(), SE = SUa->Succs.end(); SI != SE; ++SI) {
817 if (SI->getSUnit() == SUb)
818 continue;
819 DEBUG(dbgs() << " Copy Succ SU(" << SI->getSUnit()->NodeNum << ")\n");
820 DAG->addEdge(SI->getSUnit(), SDep(SUb, SDep::Artificial));
821 }
822 ++ClusterLength;
823 }
824 else
825 ClusterLength = 1;
826 }
827}
828
829/// \brief Callback from DAG postProcessing to create cluster edges for loads.
830void LoadClusterMutation::apply(ScheduleDAGMI *DAG) {
831 // Map DAG NodeNum to store chain ID.
832 DenseMap<unsigned, unsigned> StoreChainIDs;
833 // Map each store chain to a set of dependent loads.
834 SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
835 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
836 SUnit *SU = &DAG->SUnits[Idx];
837 if (!SU->getInstr()->mayLoad())
838 continue;
839 unsigned ChainPredID = DAG->SUnits.size();
840 for (SUnit::const_pred_iterator
841 PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
842 if (PI->isCtrl()) {
843 ChainPredID = PI->getSUnit()->NodeNum;
844 break;
845 }
846 }
847 // Check if this chain-like pred has been seen
848 // before. ChainPredID==MaxNodeID for loads at the top of the schedule.
849 unsigned NumChains = StoreChainDependents.size();
850 std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
851 StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
852 if (Result.second)
853 StoreChainDependents.resize(NumChains + 1);
854 StoreChainDependents[Result.first->second].push_back(SU);
855 }
856 // Iterate over the store chains.
857 for (unsigned Idx = 0, End = StoreChainDependents.size(); Idx != End; ++Idx)
858 clusterNeighboringLoads(StoreChainDependents[Idx], DAG);
859}
860
Andrew Trickc174eaf2012-03-08 01:41:12 +0000861//===----------------------------------------------------------------------===//
Andrew Trick6996fd02012-11-12 19:52:20 +0000862// MacroFusion - DAG post-processing to encourage fusion of macro ops.
863//===----------------------------------------------------------------------===//
864
865namespace {
866/// \brief Post-process the DAG to create cluster edges between instructions
867/// that may be fused by the processor into a single operation.
868class MacroFusion : public ScheduleDAGMutation {
869 const TargetInstrInfo *TII;
870public:
871 MacroFusion(const TargetInstrInfo *tii): TII(tii) {}
872
873 virtual void apply(ScheduleDAGMI *DAG);
874};
875} // anonymous
876
877/// \brief Callback from DAG postProcessing to create cluster edges to encourage
878/// fused operations.
879void MacroFusion::apply(ScheduleDAGMI *DAG) {
880 // For now, assume targets can only fuse with the branch.
881 MachineInstr *Branch = DAG->ExitSU.getInstr();
882 if (!Branch)
883 return;
884
885 for (unsigned Idx = DAG->SUnits.size(); Idx > 0;) {
886 SUnit *SU = &DAG->SUnits[--Idx];
887 if (!TII->shouldScheduleAdjacent(SU->getInstr(), Branch))
888 continue;
889
890 // Create a single weak edge from SU to ExitSU. The only effect is to cause
891 // bottom-up scheduling to heavily prioritize the clustered SU. There is no
892 // need to copy predecessor edges from ExitSU to SU, since top-down
893 // scheduling cannot prioritize ExitSU anyway. To defer top-down scheduling
894 // of SU, we could create an artificial edge from the deepest root, but it
895 // hasn't been needed yet.
896 bool Success = DAG->addEdge(&DAG->ExitSU, SDep(SU, SDep::Cluster));
897 (void)Success;
898 assert(Success && "No DAG nodes should be reachable from ExitSU");
899
900 DEBUG(dbgs() << "Macro Fuse SU(" << SU->NodeNum << ")\n");
901 break;
902 }
903}
904
905//===----------------------------------------------------------------------===//
Andrew Trick17d35e52012-03-14 04:00:41 +0000906// ConvergingScheduler - Implementation of the standard MachineSchedStrategy.
Andrew Trick42b7a712012-01-17 06:55:03 +0000907//===----------------------------------------------------------------------===//
908
909namespace {
Andrew Trick17d35e52012-03-14 04:00:41 +0000910/// ConvergingScheduler shrinks the unscheduled zone using heuristics to balance
911/// the schedule.
912class ConvergingScheduler : public MachineSchedStrategy {
Andrew Trick3b87f622012-11-07 07:05:09 +0000913public:
914 /// Represent the type of SchedCandidate found within a single queue.
915 /// pickNodeBidirectional depends on these listed by decreasing priority.
916 enum CandReason {
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000917 NoCand, SingleExcess, SingleCritical, Cluster,
918 ResourceReduce, ResourceDemand, BotHeightReduce, BotPathReduce,
919 TopDepthReduce, TopPathReduce, SingleMax, MultiPressure, NextDefUse,
920 NodeOrder};
Andrew Trick3b87f622012-11-07 07:05:09 +0000921
922#ifndef NDEBUG
923 static const char *getReasonStr(ConvergingScheduler::CandReason Reason);
924#endif
925
926 /// Policy for scheduling the next instruction in the candidate's zone.
927 struct CandPolicy {
928 bool ReduceLatency;
929 unsigned ReduceResIdx;
930 unsigned DemandResIdx;
931
932 CandPolicy(): ReduceLatency(false), ReduceResIdx(0), DemandResIdx(0) {}
933 };
934
935 /// Status of an instruction's critical resource consumption.
936 struct SchedResourceDelta {
937 // Count critical resources in the scheduled region required by SU.
938 unsigned CritResources;
939
940 // Count critical resources from another region consumed by SU.
941 unsigned DemandedResources;
942
943 SchedResourceDelta(): CritResources(0), DemandedResources(0) {}
944
945 bool operator==(const SchedResourceDelta &RHS) const {
946 return CritResources == RHS.CritResources
947 && DemandedResources == RHS.DemandedResources;
948 }
949 bool operator!=(const SchedResourceDelta &RHS) const {
950 return !operator==(RHS);
951 }
952 };
Andrew Trick7196a8f2012-05-10 21:06:16 +0000953
954 /// Store the state used by ConvergingScheduler heuristics, required for the
955 /// lifetime of one invocation of pickNode().
956 struct SchedCandidate {
Andrew Trick3b87f622012-11-07 07:05:09 +0000957 CandPolicy Policy;
958
Andrew Trick7196a8f2012-05-10 21:06:16 +0000959 // The best SUnit candidate.
960 SUnit *SU;
961
Andrew Trick3b87f622012-11-07 07:05:09 +0000962 // The reason for this candidate.
963 CandReason Reason;
964
Andrew Trick7196a8f2012-05-10 21:06:16 +0000965 // Register pressure values for the best candidate.
966 RegPressureDelta RPDelta;
967
Andrew Trick3b87f622012-11-07 07:05:09 +0000968 // Critical resource consumption of the best candidate.
969 SchedResourceDelta ResDelta;
970
971 SchedCandidate(const CandPolicy &policy)
972 : Policy(policy), SU(NULL), Reason(NoCand) {}
973
974 bool isValid() const { return SU; }
975
976 // Copy the status of another candidate without changing policy.
977 void setBest(SchedCandidate &Best) {
978 assert(Best.Reason != NoCand && "uninitialized Sched candidate");
979 SU = Best.SU;
980 Reason = Best.Reason;
981 RPDelta = Best.RPDelta;
982 ResDelta = Best.ResDelta;
983 }
984
985 void initResourceDelta(const ScheduleDAGMI *DAG,
986 const TargetSchedModel *SchedModel);
Andrew Trick7196a8f2012-05-10 21:06:16 +0000987 };
Andrew Trick3b87f622012-11-07 07:05:09 +0000988
989 /// Summarize the unscheduled region.
990 struct SchedRemainder {
991 // Critical path through the DAG in expected latency.
992 unsigned CriticalPath;
993
994 // Unscheduled resources
995 SmallVector<unsigned, 16> RemainingCounts;
996 // Critical resource for the unscheduled zone.
997 unsigned CritResIdx;
998 // Number of micro-ops left to schedule.
999 unsigned RemainingMicroOps;
Andrew Trick3b87f622012-11-07 07:05:09 +00001000
Andrew Trick3b87f622012-11-07 07:05:09 +00001001 void reset() {
1002 CriticalPath = 0;
1003 RemainingCounts.clear();
1004 CritResIdx = 0;
1005 RemainingMicroOps = 0;
Andrew Trick3b87f622012-11-07 07:05:09 +00001006 }
1007
1008 SchedRemainder() { reset(); }
1009
1010 void init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel);
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001011
1012 unsigned getMaxRemainingCount(const TargetSchedModel *SchedModel) const {
1013 if (!SchedModel->hasInstrSchedModel())
1014 return 0;
1015
1016 return std::max(
1017 RemainingMicroOps * SchedModel->getMicroOpFactor(),
1018 RemainingCounts[CritResIdx]);
1019 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001020 };
Andrew Trick7196a8f2012-05-10 21:06:16 +00001021
Andrew Trickf3234242012-05-24 22:11:12 +00001022 /// Each Scheduling boundary is associated with ready queues. It tracks the
Andrew Trick3b87f622012-11-07 07:05:09 +00001023 /// current cycle in the direction of movement, and maintains the state
Andrew Trickf3234242012-05-24 22:11:12 +00001024 /// of "hazards" and other interlocks at the current cycle.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001025 struct SchedBoundary {
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001026 ScheduleDAGMI *DAG;
Andrew Trick412cd2f2012-10-10 05:43:09 +00001027 const TargetSchedModel *SchedModel;
Andrew Trick3b87f622012-11-07 07:05:09 +00001028 SchedRemainder *Rem;
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001029
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001030 ReadyQueue Available;
1031 ReadyQueue Pending;
1032 bool CheckPending;
1033
Andrew Trick3b87f622012-11-07 07:05:09 +00001034 // For heuristics, keep a list of the nodes that immediately depend on the
1035 // most recently scheduled node.
1036 SmallPtrSet<const SUnit*, 8> NextSUs;
1037
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001038 ScheduleHazardRecognizer *HazardRec;
1039
1040 unsigned CurrCycle;
1041 unsigned IssueCount;
1042
1043 /// MinReadyCycle - Cycle of the soonest available instruction.
1044 unsigned MinReadyCycle;
1045
Andrew Trick3b87f622012-11-07 07:05:09 +00001046 // The expected latency of the critical path in this scheduled zone.
1047 unsigned ExpectedLatency;
1048
1049 // Resources used in the scheduled zone beyond this boundary.
1050 SmallVector<unsigned, 16> ResourceCounts;
1051
1052 // Cache the critical resources ID in this scheduled zone.
1053 unsigned CritResIdx;
1054
1055 // Is the scheduled region resource limited vs. latency limited.
1056 bool IsResourceLimited;
1057
1058 unsigned ExpectedCount;
1059
Andrew Trick3b87f622012-11-07 07:05:09 +00001060#ifndef NDEBUG
Andrew Trickb7e02892012-06-05 21:11:27 +00001061 // Remember the greatest min operand latency.
1062 unsigned MaxMinLatency;
Andrew Trick3b87f622012-11-07 07:05:09 +00001063#endif
1064
1065 void reset() {
Andrew Trickecb8c2b2013-02-13 19:22:27 +00001066 // A new HazardRec is created for each DAG and owned by SchedBoundary.
1067 delete HazardRec;
1068
Andrew Trick3b87f622012-11-07 07:05:09 +00001069 Available.clear();
1070 Pending.clear();
1071 CheckPending = false;
1072 NextSUs.clear();
1073 HazardRec = 0;
1074 CurrCycle = 0;
1075 IssueCount = 0;
1076 MinReadyCycle = UINT_MAX;
1077 ExpectedLatency = 0;
1078 ResourceCounts.resize(1);
1079 assert(!ResourceCounts[0] && "nonzero count for bad resource");
1080 CritResIdx = 0;
1081 IsResourceLimited = false;
1082 ExpectedCount = 0;
Andrew Trick3b87f622012-11-07 07:05:09 +00001083#ifndef NDEBUG
1084 MaxMinLatency = 0;
1085#endif
1086 // Reserve a zero-count for invalid CritResIdx.
1087 ResourceCounts.resize(1);
1088 }
Andrew Trickb7e02892012-06-05 21:11:27 +00001089
Andrew Trickf3234242012-05-24 22:11:12 +00001090 /// Pending queues extend the ready queues with the same ID and the
1091 /// PendingFlag set.
1092 SchedBoundary(unsigned ID, const Twine &Name):
Andrew Trick3b87f622012-11-07 07:05:09 +00001093 DAG(0), SchedModel(0), Rem(0), Available(ID, Name+".A"),
Andrew Trickecb8c2b2013-02-13 19:22:27 +00001094 Pending(ID << ConvergingScheduler::LogMaxQID, Name+".P"),
1095 HazardRec(0) {
Andrew Trick3b87f622012-11-07 07:05:09 +00001096 reset();
1097 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001098
1099 ~SchedBoundary() { delete HazardRec; }
1100
Andrew Trick3b87f622012-11-07 07:05:09 +00001101 void init(ScheduleDAGMI *dag, const TargetSchedModel *smodel,
1102 SchedRemainder *rem);
Andrew Trick412cd2f2012-10-10 05:43:09 +00001103
Andrew Trickf3234242012-05-24 22:11:12 +00001104 bool isTop() const {
1105 return Available.getID() == ConvergingScheduler::TopQID;
1106 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001107
Andrew Trick3b87f622012-11-07 07:05:09 +00001108 unsigned getUnscheduledLatency(SUnit *SU) const {
1109 if (isTop())
1110 return SU->getHeight();
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001111 return SU->getDepth() + SU->Latency;
Andrew Trick3b87f622012-11-07 07:05:09 +00001112 }
1113
1114 unsigned getCriticalCount() const {
1115 return ResourceCounts[CritResIdx];
1116 }
1117
Andrew Trick5559ffa2012-06-29 03:23:24 +00001118 bool checkHazard(SUnit *SU);
1119
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001120 void setLatencyPolicy(CandPolicy &Policy);
Andrew Trick3b87f622012-11-07 07:05:09 +00001121
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001122 void releaseNode(SUnit *SU, unsigned ReadyCycle);
1123
1124 void bumpCycle();
1125
Andrew Trick3b87f622012-11-07 07:05:09 +00001126 void countResource(unsigned PIdx, unsigned Cycles);
1127
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001128 void bumpNode(SUnit *SU);
Andrew Trickb7e02892012-06-05 21:11:27 +00001129
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001130 void releasePending();
1131
1132 void removeReady(SUnit *SU);
1133
1134 SUnit *pickOnlyChoice();
1135 };
1136
Andrew Trick3b87f622012-11-07 07:05:09 +00001137private:
Andrew Trick17d35e52012-03-14 04:00:41 +00001138 ScheduleDAGMI *DAG;
Andrew Trick412cd2f2012-10-10 05:43:09 +00001139 const TargetSchedModel *SchedModel;
Andrew Trick7196a8f2012-05-10 21:06:16 +00001140 const TargetRegisterInfo *TRI;
Andrew Trick42b7a712012-01-17 06:55:03 +00001141
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001142 // State of the top and bottom scheduled instruction boundaries.
Andrew Trick3b87f622012-11-07 07:05:09 +00001143 SchedRemainder Rem;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001144 SchedBoundary Top;
1145 SchedBoundary Bot;
Andrew Trick17d35e52012-03-14 04:00:41 +00001146
1147public:
Andrew Trickf3234242012-05-24 22:11:12 +00001148 /// SUnit::NodeQueueId: 0 (none), 1 (top), 2 (bot), 3 (both)
Andrew Trick7196a8f2012-05-10 21:06:16 +00001149 enum {
1150 TopQID = 1,
Andrew Trickf3234242012-05-24 22:11:12 +00001151 BotQID = 2,
1152 LogMaxQID = 2
Andrew Trick7196a8f2012-05-10 21:06:16 +00001153 };
1154
Andrew Trickf3234242012-05-24 22:11:12 +00001155 ConvergingScheduler():
Andrew Trick412cd2f2012-10-10 05:43:09 +00001156 DAG(0), SchedModel(0), TRI(0), Top(TopQID, "TopQ"), Bot(BotQID, "BotQ") {}
Andrew Trickd38f87e2012-05-10 21:06:12 +00001157
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001158 virtual void initialize(ScheduleDAGMI *dag);
Andrew Trick17d35e52012-03-14 04:00:41 +00001159
Andrew Trick7196a8f2012-05-10 21:06:16 +00001160 virtual SUnit *pickNode(bool &IsTopNode);
Andrew Trick17d35e52012-03-14 04:00:41 +00001161
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001162 virtual void schedNode(SUnit *SU, bool IsTopNode);
1163
1164 virtual void releaseTopNode(SUnit *SU);
1165
1166 virtual void releaseBottomNode(SUnit *SU);
1167
Andrew Trick3b87f622012-11-07 07:05:09 +00001168 virtual void registerRoots();
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001169
Andrew Trick3b87f622012-11-07 07:05:09 +00001170protected:
1171 void balanceZones(
1172 ConvergingScheduler::SchedBoundary &CriticalZone,
1173 ConvergingScheduler::SchedCandidate &CriticalCand,
1174 ConvergingScheduler::SchedBoundary &OppositeZone,
1175 ConvergingScheduler::SchedCandidate &OppositeCand);
1176
1177 void checkResourceLimits(ConvergingScheduler::SchedCandidate &TopCand,
1178 ConvergingScheduler::SchedCandidate &BotCand);
1179
1180 void tryCandidate(SchedCandidate &Cand,
1181 SchedCandidate &TryCand,
1182 SchedBoundary &Zone,
1183 const RegPressureTracker &RPTracker,
1184 RegPressureTracker &TempTracker);
1185
1186 SUnit *pickNodeBidirectional(bool &IsTopNode);
1187
1188 void pickNodeFromQueue(SchedBoundary &Zone,
1189 const RegPressureTracker &RPTracker,
1190 SchedCandidate &Candidate);
1191
Andrew Trick28ebc892012-05-10 21:06:19 +00001192#ifndef NDEBUG
Andrew Trick3b87f622012-11-07 07:05:09 +00001193 void traceCandidate(const SchedCandidate &Cand, const SchedBoundary &Zone);
Andrew Trick28ebc892012-05-10 21:06:19 +00001194#endif
Andrew Trick42b7a712012-01-17 06:55:03 +00001195};
1196} // namespace
1197
Andrew Trick3b87f622012-11-07 07:05:09 +00001198void ConvergingScheduler::SchedRemainder::
1199init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
1200 reset();
1201 if (!SchedModel->hasInstrSchedModel())
1202 return;
1203 RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
1204 for (std::vector<SUnit>::iterator
1205 I = DAG->SUnits.begin(), E = DAG->SUnits.end(); I != E; ++I) {
1206 const MCSchedClassDesc *SC = DAG->getSchedClass(&*I);
1207 RemainingMicroOps += SchedModel->getNumMicroOps(I->getInstr(), SC);
1208 for (TargetSchedModel::ProcResIter
1209 PI = SchedModel->getWriteProcResBegin(SC),
1210 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1211 unsigned PIdx = PI->ProcResourceIdx;
1212 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1213 RemainingCounts[PIdx] += (Factor * PI->Cycles);
1214 }
1215 }
Andrew Trick071966f2012-12-18 20:52:49 +00001216 for (unsigned PIdx = 0, PEnd = SchedModel->getNumProcResourceKinds();
1217 PIdx != PEnd; ++PIdx) {
1218 if ((int)(RemainingCounts[PIdx] - RemainingCounts[CritResIdx])
1219 >= (int)SchedModel->getLatencyFactor()) {
1220 CritResIdx = PIdx;
1221 }
1222 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001223}
1224
1225void ConvergingScheduler::SchedBoundary::
1226init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
1227 reset();
1228 DAG = dag;
1229 SchedModel = smodel;
1230 Rem = rem;
1231 if (SchedModel->hasInstrSchedModel())
1232 ResourceCounts.resize(SchedModel->getNumProcResourceKinds());
1233}
1234
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001235void ConvergingScheduler::initialize(ScheduleDAGMI *dag) {
1236 DAG = dag;
Andrew Trick412cd2f2012-10-10 05:43:09 +00001237 SchedModel = DAG->getSchedModel();
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001238 TRI = DAG->TRI;
Andrew Trickecb8c2b2013-02-13 19:22:27 +00001239
Andrew Trick3b87f622012-11-07 07:05:09 +00001240 Rem.init(DAG, SchedModel);
1241 Top.init(DAG, SchedModel, &Rem);
1242 Bot.init(DAG, SchedModel, &Rem);
1243
Andrew Trick4e1fb182013-01-25 06:33:57 +00001244 DAG->computeDFSResult();
Andrew Trick178f7d02013-01-25 04:01:04 +00001245
Andrew Trick3b87f622012-11-07 07:05:09 +00001246 // Initialize resource counts.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001247
Andrew Trick412cd2f2012-10-10 05:43:09 +00001248 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
1249 // are disabled, then these HazardRecs will be disabled.
1250 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001251 const TargetMachine &TM = DAG->MF.getTarget();
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001252 Top.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
1253 Bot.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
1254
1255 assert((!ForceTopDown || !ForceBottomUp) &&
1256 "-misched-topdown incompatible with -misched-bottomup");
1257}
1258
1259void ConvergingScheduler::releaseTopNode(SUnit *SU) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001260 if (SU->isScheduled)
1261 return;
1262
Andrew Trickd4539602012-12-18 20:52:52 +00001263 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
Andrew Trickb7e02892012-06-05 21:11:27 +00001264 I != E; ++I) {
1265 unsigned PredReadyCycle = I->getSUnit()->TopReadyCycle;
Andrew Trickffd25262012-08-23 00:39:43 +00001266 unsigned MinLatency = I->getMinLatency();
Andrew Trickb7e02892012-06-05 21:11:27 +00001267#ifndef NDEBUG
Andrew Trickffd25262012-08-23 00:39:43 +00001268 Top.MaxMinLatency = std::max(MinLatency, Top.MaxMinLatency);
Andrew Trickb7e02892012-06-05 21:11:27 +00001269#endif
Andrew Trickffd25262012-08-23 00:39:43 +00001270 if (SU->TopReadyCycle < PredReadyCycle + MinLatency)
1271 SU->TopReadyCycle = PredReadyCycle + MinLatency;
Andrew Trickb7e02892012-06-05 21:11:27 +00001272 }
1273 Top.releaseNode(SU, SU->TopReadyCycle);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001274}
1275
1276void ConvergingScheduler::releaseBottomNode(SUnit *SU) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001277 if (SU->isScheduled)
1278 return;
1279
1280 assert(SU->getInstr() && "Scheduled SUnit must have instr");
1281
1282 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1283 I != E; ++I) {
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001284 if (I->isWeak())
1285 continue;
Andrew Trickb7e02892012-06-05 21:11:27 +00001286 unsigned SuccReadyCycle = I->getSUnit()->BotReadyCycle;
Andrew Trickffd25262012-08-23 00:39:43 +00001287 unsigned MinLatency = I->getMinLatency();
Andrew Trickb7e02892012-06-05 21:11:27 +00001288#ifndef NDEBUG
Andrew Trickffd25262012-08-23 00:39:43 +00001289 Bot.MaxMinLatency = std::max(MinLatency, Bot.MaxMinLatency);
Andrew Trickb7e02892012-06-05 21:11:27 +00001290#endif
Andrew Trickffd25262012-08-23 00:39:43 +00001291 if (SU->BotReadyCycle < SuccReadyCycle + MinLatency)
1292 SU->BotReadyCycle = SuccReadyCycle + MinLatency;
Andrew Trickb7e02892012-06-05 21:11:27 +00001293 }
1294 Bot.releaseNode(SU, SU->BotReadyCycle);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001295}
1296
Andrew Trick3b87f622012-11-07 07:05:09 +00001297void ConvergingScheduler::registerRoots() {
1298 Rem.CriticalPath = DAG->ExitSU.getDepth();
1299 // Some roots may not feed into ExitSU. Check all of them in case.
1300 for (std::vector<SUnit*>::const_iterator
1301 I = Bot.Available.begin(), E = Bot.Available.end(); I != E; ++I) {
1302 if ((*I)->getDepth() > Rem.CriticalPath)
1303 Rem.CriticalPath = (*I)->getDepth();
1304 }
1305 DEBUG(dbgs() << "Critical Path: " << Rem.CriticalPath << '\n');
1306}
1307
Andrew Trick5559ffa2012-06-29 03:23:24 +00001308/// Does this SU have a hazard within the current instruction group.
1309///
1310/// The scheduler supports two modes of hazard recognition. The first is the
1311/// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
1312/// supports highly complicated in-order reservation tables
1313/// (ScoreboardHazardRecognizer) and arbitraty target-specific logic.
1314///
1315/// The second is a streamlined mechanism that checks for hazards based on
1316/// simple counters that the scheduler itself maintains. It explicitly checks
1317/// for instruction dispatch limitations, including the number of micro-ops that
1318/// can dispatch per cycle.
1319///
1320/// TODO: Also check whether the SU must start a new group.
1321bool ConvergingScheduler::SchedBoundary::checkHazard(SUnit *SU) {
1322 if (HazardRec->isEnabled())
1323 return HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard;
1324
Andrew Trick412cd2f2012-10-10 05:43:09 +00001325 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
Andrew Trick3b87f622012-11-07 07:05:09 +00001326 if ((IssueCount > 0) && (IssueCount + uops > SchedModel->getIssueWidth())) {
1327 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") uops="
1328 << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
Andrew Trick5559ffa2012-06-29 03:23:24 +00001329 return true;
Andrew Trick3b87f622012-11-07 07:05:09 +00001330 }
Andrew Trick5559ffa2012-06-29 03:23:24 +00001331 return false;
1332}
1333
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001334/// Compute the remaining latency to determine whether ILP should be increased.
1335void ConvergingScheduler::SchedBoundary::setLatencyPolicy(CandPolicy &Policy) {
1336 // FIXME: compile time. In all, we visit four queues here one we should only
1337 // need to visit the one that was last popped if we cache the result.
1338 unsigned RemLatency = 0;
1339 for (ReadyQueue::iterator I = Available.begin(), E = Available.end();
1340 I != E; ++I) {
1341 unsigned L = getUnscheduledLatency(*I);
1342 if (L > RemLatency)
1343 RemLatency = L;
1344 }
1345 for (ReadyQueue::iterator I = Pending.begin(), E = Pending.end();
1346 I != E; ++I) {
1347 unsigned L = getUnscheduledLatency(*I);
1348 if (L > RemLatency)
1349 RemLatency = L;
1350 }
Andrew Trick47579cf2013-01-09 03:36:49 +00001351 unsigned CriticalPathLimit = Rem->CriticalPath + SchedModel->getILPWindow();
1352 if (RemLatency + ExpectedLatency >= CriticalPathLimit
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001353 && RemLatency > Rem->getMaxRemainingCount(SchedModel)) {
1354 Policy.ReduceLatency = true;
1355 DEBUG(dbgs() << "Increase ILP: " << Available.getName() << '\n');
Andrew Trick3b87f622012-11-07 07:05:09 +00001356 }
1357}
1358
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001359void ConvergingScheduler::SchedBoundary::releaseNode(SUnit *SU,
1360 unsigned ReadyCycle) {
Andrew Trick3b87f622012-11-07 07:05:09 +00001361
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001362 if (ReadyCycle < MinReadyCycle)
1363 MinReadyCycle = ReadyCycle;
1364
1365 // Check for interlocks first. For the purpose of other heuristics, an
1366 // instruction that cannot issue appears as if it's not in the ReadyQueue.
Andrew Trick5559ffa2012-06-29 03:23:24 +00001367 if (ReadyCycle > CurrCycle || checkHazard(SU))
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001368 Pending.push(SU);
1369 else
1370 Available.push(SU);
Andrew Trick3b87f622012-11-07 07:05:09 +00001371
1372 // Record this node as an immediate dependent of the scheduled node.
1373 NextSUs.insert(SU);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001374}
1375
1376/// Move the boundary of scheduled code by one cycle.
1377void ConvergingScheduler::SchedBoundary::bumpCycle() {
Andrew Trick412cd2f2012-10-10 05:43:09 +00001378 unsigned Width = SchedModel->getIssueWidth();
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001379 IssueCount = (IssueCount <= Width) ? 0 : IssueCount - Width;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001380
Andrew Trick3b87f622012-11-07 07:05:09 +00001381 unsigned NextCycle = CurrCycle + 1;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001382 assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
Andrew Trick3b87f622012-11-07 07:05:09 +00001383 if (MinReadyCycle > NextCycle) {
1384 IssueCount = 0;
1385 NextCycle = MinReadyCycle;
1386 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001387
1388 if (!HazardRec->isEnabled()) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001389 // Bypass HazardRec virtual calls.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001390 CurrCycle = NextCycle;
1391 }
1392 else {
Andrew Trickb7e02892012-06-05 21:11:27 +00001393 // Bypass getHazardType calls in case of long latency.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001394 for (; CurrCycle != NextCycle; ++CurrCycle) {
1395 if (isTop())
1396 HazardRec->AdvanceCycle();
1397 else
1398 HazardRec->RecedeCycle();
1399 }
1400 }
1401 CheckPending = true;
Andrew Trick3b87f622012-11-07 07:05:09 +00001402 IsResourceLimited = getCriticalCount() > std::max(ExpectedLatency, CurrCycle);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001403
Andrew Trick3b87f622012-11-07 07:05:09 +00001404 DEBUG(dbgs() << " *** " << Available.getName() << " cycle "
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001405 << CurrCycle << '\n');
1406}
1407
Andrew Trick3b87f622012-11-07 07:05:09 +00001408/// Add the given processor resource to this scheduled zone.
1409void ConvergingScheduler::SchedBoundary::countResource(unsigned PIdx,
1410 unsigned Cycles) {
1411 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1412 DEBUG(dbgs() << " " << SchedModel->getProcResource(PIdx)->Name
1413 << " +(" << Cycles << "x" << Factor
1414 << ") / " << SchedModel->getLatencyFactor() << '\n');
1415
1416 unsigned Count = Factor * Cycles;
1417 ResourceCounts[PIdx] += Count;
1418 assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
1419 Rem->RemainingCounts[PIdx] -= Count;
1420
Andrew Trick3b87f622012-11-07 07:05:09 +00001421 // Check if this resource exceeds the current critical resource by a full
1422 // cycle. If so, it becomes the critical resource.
1423 if ((int)(ResourceCounts[PIdx] - ResourceCounts[CritResIdx])
1424 >= (int)SchedModel->getLatencyFactor()) {
1425 CritResIdx = PIdx;
1426 DEBUG(dbgs() << " *** Critical resource "
1427 << SchedModel->getProcResource(PIdx)->Name << " x"
1428 << ResourceCounts[PIdx] << '\n');
1429 }
1430}
1431
Andrew Trickb7e02892012-06-05 21:11:27 +00001432/// Move the boundary of scheduled code by one SUnit.
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001433void ConvergingScheduler::SchedBoundary::bumpNode(SUnit *SU) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001434 // Update the reservation table.
1435 if (HazardRec->isEnabled()) {
1436 if (!isTop() && SU->isCall) {
1437 // Calls are scheduled with their preceding instructions. For bottom-up
1438 // scheduling, clear the pipeline state before emitting.
1439 HazardRec->Reset();
1440 }
1441 HazardRec->EmitInstruction(SU);
1442 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001443 // Update resource counts and critical resource.
1444 if (SchedModel->hasInstrSchedModel()) {
1445 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1446 Rem->RemainingMicroOps -= SchedModel->getNumMicroOps(SU->getInstr(), SC);
1447 for (TargetSchedModel::ProcResIter
1448 PI = SchedModel->getWriteProcResBegin(SC),
1449 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1450 countResource(PI->ProcResourceIdx, PI->Cycles);
1451 }
1452 }
1453 if (isTop()) {
1454 if (SU->getDepth() > ExpectedLatency)
1455 ExpectedLatency = SU->getDepth();
1456 }
1457 else {
1458 if (SU->getHeight() > ExpectedLatency)
1459 ExpectedLatency = SU->getHeight();
1460 }
1461
1462 IsResourceLimited = getCriticalCount() > std::max(ExpectedLatency, CurrCycle);
1463
Andrew Trick5559ffa2012-06-29 03:23:24 +00001464 // Check the instruction group dispatch limit.
1465 // TODO: Check if this SU must end a dispatch group.
Andrew Trick412cd2f2012-10-10 05:43:09 +00001466 IssueCount += SchedModel->getNumMicroOps(SU->getInstr());
Andrew Trick3b87f622012-11-07 07:05:09 +00001467
1468 // checkHazard prevents scheduling multiple instructions per cycle that exceed
1469 // issue width. However, we commonly reach the maximum. In this case
1470 // opportunistically bump the cycle to avoid uselessly checking everything in
1471 // the readyQ. Furthermore, a single instruction may produce more than one
1472 // cycle's worth of micro-ops.
Andrew Trick412cd2f2012-10-10 05:43:09 +00001473 if (IssueCount >= SchedModel->getIssueWidth()) {
Andrew Trick3b87f622012-11-07 07:05:09 +00001474 DEBUG(dbgs() << " *** Max instrs at cycle " << CurrCycle << '\n');
Andrew Trickb7e02892012-06-05 21:11:27 +00001475 bumpCycle();
1476 }
1477}
1478
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001479/// Release pending ready nodes in to the available queue. This makes them
1480/// visible to heuristics.
1481void ConvergingScheduler::SchedBoundary::releasePending() {
1482 // If the available queue is empty, it is safe to reset MinReadyCycle.
1483 if (Available.empty())
1484 MinReadyCycle = UINT_MAX;
1485
1486 // Check to see if any of the pending instructions are ready to issue. If
1487 // so, add them to the available queue.
1488 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
1489 SUnit *SU = *(Pending.begin()+i);
Andrew Trickb7e02892012-06-05 21:11:27 +00001490 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001491
1492 if (ReadyCycle < MinReadyCycle)
1493 MinReadyCycle = ReadyCycle;
1494
1495 if (ReadyCycle > CurrCycle)
1496 continue;
1497
Andrew Trick5559ffa2012-06-29 03:23:24 +00001498 if (checkHazard(SU))
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001499 continue;
1500
1501 Available.push(SU);
1502 Pending.remove(Pending.begin()+i);
1503 --i; --e;
1504 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001505 DEBUG(if (!Pending.empty()) Pending.dump());
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001506 CheckPending = false;
1507}
1508
1509/// Remove SU from the ready set for this boundary.
1510void ConvergingScheduler::SchedBoundary::removeReady(SUnit *SU) {
1511 if (Available.isInQueue(SU))
1512 Available.remove(Available.find(SU));
1513 else {
1514 assert(Pending.isInQueue(SU) && "bad ready count");
1515 Pending.remove(Pending.find(SU));
1516 }
1517}
1518
1519/// If this queue only has one ready candidate, return it. As a side effect,
Andrew Trick3b87f622012-11-07 07:05:09 +00001520/// defer any nodes that now hit a hazard, and advance the cycle until at least
1521/// one node is ready. If multiple instructions are ready, return NULL.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001522SUnit *ConvergingScheduler::SchedBoundary::pickOnlyChoice() {
1523 if (CheckPending)
1524 releasePending();
1525
Andrew Trick3b87f622012-11-07 07:05:09 +00001526 if (IssueCount > 0) {
1527 // Defer any ready instrs that now have a hazard.
1528 for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
1529 if (checkHazard(*I)) {
1530 Pending.push(*I);
1531 I = Available.remove(I);
1532 continue;
1533 }
1534 ++I;
1535 }
1536 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001537 for (unsigned i = 0; Available.empty(); ++i) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001538 assert(i <= (HazardRec->getMaxLookAhead() + MaxMinLatency) &&
1539 "permanent hazard"); (void)i;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001540 bumpCycle();
1541 releasePending();
1542 }
1543 if (Available.size() == 1)
1544 return *Available.begin();
1545 return NULL;
1546}
1547
Andrew Trick3b87f622012-11-07 07:05:09 +00001548/// Record the candidate policy for opposite zones with different critical
1549/// resources.
1550///
1551/// If the CriticalZone is latency limited, don't force a policy for the
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001552/// candidates here. Instead, setLatencyPolicy sets ReduceLatency if needed.
Andrew Trick3b87f622012-11-07 07:05:09 +00001553void ConvergingScheduler::balanceZones(
1554 ConvergingScheduler::SchedBoundary &CriticalZone,
1555 ConvergingScheduler::SchedCandidate &CriticalCand,
1556 ConvergingScheduler::SchedBoundary &OppositeZone,
1557 ConvergingScheduler::SchedCandidate &OppositeCand) {
1558
1559 if (!CriticalZone.IsResourceLimited)
1560 return;
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001561 assert(SchedModel->hasInstrSchedModel() && "required schedmodel");
Andrew Trick3b87f622012-11-07 07:05:09 +00001562
1563 SchedRemainder *Rem = CriticalZone.Rem;
1564
1565 // If the critical zone is overconsuming a resource relative to the
1566 // remainder, try to reduce it.
1567 unsigned RemainingCritCount =
1568 Rem->RemainingCounts[CriticalZone.CritResIdx];
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001569 if ((int)(Rem->getMaxRemainingCount(SchedModel) - RemainingCritCount)
Andrew Trick3b87f622012-11-07 07:05:09 +00001570 > (int)SchedModel->getLatencyFactor()) {
1571 CriticalCand.Policy.ReduceResIdx = CriticalZone.CritResIdx;
1572 DEBUG(dbgs() << "Balance " << CriticalZone.Available.getName() << " reduce "
1573 << SchedModel->getProcResource(CriticalZone.CritResIdx)->Name
1574 << '\n');
1575 }
1576 // If the other zone is underconsuming a resource relative to the full zone,
1577 // try to increase it.
1578 unsigned OppositeCount =
1579 OppositeZone.ResourceCounts[CriticalZone.CritResIdx];
1580 if ((int)(OppositeZone.ExpectedCount - OppositeCount)
1581 > (int)SchedModel->getLatencyFactor()) {
1582 OppositeCand.Policy.DemandResIdx = CriticalZone.CritResIdx;
1583 DEBUG(dbgs() << "Balance " << OppositeZone.Available.getName() << " demand "
1584 << SchedModel->getProcResource(OppositeZone.CritResIdx)->Name
1585 << '\n');
1586 }
Andrew Trick28ebc892012-05-10 21:06:19 +00001587}
Andrew Trick3b87f622012-11-07 07:05:09 +00001588
1589/// Determine if the scheduled zones exceed resource limits or critical path and
1590/// set each candidate's ReduceHeight policy accordingly.
1591void ConvergingScheduler::checkResourceLimits(
1592 ConvergingScheduler::SchedCandidate &TopCand,
1593 ConvergingScheduler::SchedCandidate &BotCand) {
1594
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001595 // Set ReduceLatency to true if needed.
Andrew Trickeed4e012013-01-11 17:51:16 +00001596 Bot.setLatencyPolicy(BotCand.Policy);
1597 Top.setLatencyPolicy(TopCand.Policy);
Andrew Trick3b87f622012-11-07 07:05:09 +00001598
1599 // Handle resource-limited regions.
1600 if (Top.IsResourceLimited && Bot.IsResourceLimited
1601 && Top.CritResIdx == Bot.CritResIdx) {
1602 // If the scheduled critical resource in both zones is no longer the
1603 // critical remaining resource, attempt to reduce resource height both ways.
1604 if (Top.CritResIdx != Rem.CritResIdx) {
1605 TopCand.Policy.ReduceResIdx = Top.CritResIdx;
1606 BotCand.Policy.ReduceResIdx = Bot.CritResIdx;
1607 DEBUG(dbgs() << "Reduce scheduled "
1608 << SchedModel->getProcResource(Top.CritResIdx)->Name << '\n');
1609 }
1610 return;
1611 }
1612 // Handle latency-limited regions.
1613 if (!Top.IsResourceLimited && !Bot.IsResourceLimited) {
1614 // If the total scheduled expected latency exceeds the region's critical
1615 // path then reduce latency both ways.
1616 //
1617 // Just because a zone is not resource limited does not mean it is latency
1618 // limited. Unbuffered resource, such as max micro-ops may cause CurrCycle
1619 // to exceed expected latency.
1620 if ((Top.ExpectedLatency + Bot.ExpectedLatency >= Rem.CriticalPath)
1621 && (Rem.CriticalPath > Top.CurrCycle + Bot.CurrCycle)) {
1622 TopCand.Policy.ReduceLatency = true;
1623 BotCand.Policy.ReduceLatency = true;
1624 DEBUG(dbgs() << "Reduce scheduled latency " << Top.ExpectedLatency
1625 << " + " << Bot.ExpectedLatency << '\n');
1626 }
1627 return;
1628 }
1629 // The critical resource is different in each zone, so request balancing.
1630
1631 // Compute the cost of each zone.
Andrew Trick3b87f622012-11-07 07:05:09 +00001632 Top.ExpectedCount = std::max(Top.ExpectedLatency, Top.CurrCycle);
1633 Top.ExpectedCount = std::max(
1634 Top.getCriticalCount(),
1635 Top.ExpectedCount * SchedModel->getLatencyFactor());
1636 Bot.ExpectedCount = std::max(Bot.ExpectedLatency, Bot.CurrCycle);
1637 Bot.ExpectedCount = std::max(
1638 Bot.getCriticalCount(),
1639 Bot.ExpectedCount * SchedModel->getLatencyFactor());
1640
1641 balanceZones(Top, TopCand, Bot, BotCand);
1642 balanceZones(Bot, BotCand, Top, TopCand);
1643}
1644
1645void ConvergingScheduler::SchedCandidate::
1646initResourceDelta(const ScheduleDAGMI *DAG,
1647 const TargetSchedModel *SchedModel) {
1648 if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
1649 return;
1650
1651 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1652 for (TargetSchedModel::ProcResIter
1653 PI = SchedModel->getWriteProcResBegin(SC),
1654 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1655 if (PI->ProcResourceIdx == Policy.ReduceResIdx)
1656 ResDelta.CritResources += PI->Cycles;
1657 if (PI->ProcResourceIdx == Policy.DemandResIdx)
1658 ResDelta.DemandedResources += PI->Cycles;
1659 }
1660}
1661
1662/// Return true if this heuristic determines order.
1663static bool tryLess(unsigned TryVal, unsigned CandVal,
1664 ConvergingScheduler::SchedCandidate &TryCand,
1665 ConvergingScheduler::SchedCandidate &Cand,
1666 ConvergingScheduler::CandReason Reason) {
1667 if (TryVal < CandVal) {
1668 TryCand.Reason = Reason;
1669 return true;
1670 }
1671 if (TryVal > CandVal) {
1672 if (Cand.Reason > Reason)
1673 Cand.Reason = Reason;
1674 return true;
1675 }
1676 return false;
1677}
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001678
Andrew Trick3b87f622012-11-07 07:05:09 +00001679static bool tryGreater(unsigned TryVal, unsigned CandVal,
1680 ConvergingScheduler::SchedCandidate &TryCand,
1681 ConvergingScheduler::SchedCandidate &Cand,
1682 ConvergingScheduler::CandReason Reason) {
1683 if (TryVal > CandVal) {
1684 TryCand.Reason = Reason;
1685 return true;
1686 }
1687 if (TryVal < CandVal) {
1688 if (Cand.Reason > Reason)
1689 Cand.Reason = Reason;
1690 return true;
1691 }
1692 return false;
1693}
1694
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001695static unsigned getWeakLeft(const SUnit *SU, bool isTop) {
1696 return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
1697}
1698
Andrew Trick3b87f622012-11-07 07:05:09 +00001699/// Apply a set of heursitics to a new candidate. Heuristics are currently
1700/// hierarchical. This may be more efficient than a graduated cost model because
1701/// we don't need to evaluate all aspects of the model for each node in the
1702/// queue. But it's really done to make the heuristics easier to debug and
1703/// statistically analyze.
1704///
1705/// \param Cand provides the policy and current best candidate.
1706/// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
1707/// \param Zone describes the scheduled zone that we are extending.
1708/// \param RPTracker describes reg pressure within the scheduled zone.
1709/// \param TempTracker is a scratch pressure tracker to reuse in queries.
1710void ConvergingScheduler::tryCandidate(SchedCandidate &Cand,
1711 SchedCandidate &TryCand,
1712 SchedBoundary &Zone,
1713 const RegPressureTracker &RPTracker,
1714 RegPressureTracker &TempTracker) {
1715
1716 // Always initialize TryCand's RPDelta.
1717 TempTracker.getMaxPressureDelta(TryCand.SU->getInstr(), TryCand.RPDelta,
1718 DAG->getRegionCriticalPSets(),
1719 DAG->getRegPressure().MaxSetPressure);
1720
1721 // Initialize the candidate if needed.
1722 if (!Cand.isValid()) {
1723 TryCand.Reason = NodeOrder;
1724 return;
1725 }
1726 // Avoid exceeding the target's limit.
1727 if (tryLess(TryCand.RPDelta.Excess.UnitIncrease,
1728 Cand.RPDelta.Excess.UnitIncrease, TryCand, Cand, SingleExcess))
1729 return;
1730 if (Cand.Reason == SingleExcess)
1731 Cand.Reason = MultiPressure;
1732
1733 // Avoid increasing the max critical pressure in the scheduled region.
1734 if (tryLess(TryCand.RPDelta.CriticalMax.UnitIncrease,
1735 Cand.RPDelta.CriticalMax.UnitIncrease,
1736 TryCand, Cand, SingleCritical))
1737 return;
1738 if (Cand.Reason == SingleCritical)
1739 Cand.Reason = MultiPressure;
1740
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001741 // Keep clustered nodes together to encourage downstream peephole
1742 // optimizations which may reduce resource requirements.
1743 //
1744 // This is a best effort to set things up for a post-RA pass. Optimizations
1745 // like generating loads of multiple registers should ideally be done within
1746 // the scheduler pass by combining the loads during DAG postprocessing.
1747 const SUnit *NextClusterSU =
1748 Zone.isTop() ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
1749 if (tryGreater(TryCand.SU == NextClusterSU, Cand.SU == NextClusterSU,
1750 TryCand, Cand, Cluster))
1751 return;
1752 // Currently, weak edges are for clustering, so we hard-code that reason.
1753 // However, deferring the current TryCand will not change Cand's reason.
1754 CandReason OrigReason = Cand.Reason;
1755 if (tryLess(getWeakLeft(TryCand.SU, Zone.isTop()),
1756 getWeakLeft(Cand.SU, Zone.isTop()),
1757 TryCand, Cand, Cluster)) {
1758 Cand.Reason = OrigReason;
1759 return;
1760 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001761 // Avoid critical resource consumption and balance the schedule.
1762 TryCand.initResourceDelta(DAG, SchedModel);
1763 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
1764 TryCand, Cand, ResourceReduce))
1765 return;
1766 if (tryGreater(TryCand.ResDelta.DemandedResources,
1767 Cand.ResDelta.DemandedResources,
1768 TryCand, Cand, ResourceDemand))
1769 return;
1770
1771 // Avoid serializing long latency dependence chains.
1772 if (Cand.Policy.ReduceLatency) {
1773 if (Zone.isTop()) {
1774 if (Cand.SU->getDepth() * SchedModel->getLatencyFactor()
1775 > Zone.ExpectedCount) {
1776 if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
1777 TryCand, Cand, TopDepthReduce))
1778 return;
1779 }
1780 if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
1781 TryCand, Cand, TopPathReduce))
1782 return;
1783 }
1784 else {
1785 if (Cand.SU->getHeight() * SchedModel->getLatencyFactor()
1786 > Zone.ExpectedCount) {
1787 if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
1788 TryCand, Cand, BotHeightReduce))
1789 return;
1790 }
1791 if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
1792 TryCand, Cand, BotPathReduce))
1793 return;
1794 }
1795 }
1796
1797 // Avoid increasing the max pressure of the entire region.
1798 if (tryLess(TryCand.RPDelta.CurrentMax.UnitIncrease,
1799 Cand.RPDelta.CurrentMax.UnitIncrease, TryCand, Cand, SingleMax))
1800 return;
1801 if (Cand.Reason == SingleMax)
1802 Cand.Reason = MultiPressure;
1803
1804 // Prefer immediate defs/users of the last scheduled instruction. This is a
1805 // nice pressure avoidance strategy that also conserves the processor's
1806 // register renaming resources and keeps the machine code readable.
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001807 if (tryGreater(Zone.NextSUs.count(TryCand.SU), Zone.NextSUs.count(Cand.SU),
1808 TryCand, Cand, NextDefUse))
Andrew Trick3b87f622012-11-07 07:05:09 +00001809 return;
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001810
Andrew Trick3b87f622012-11-07 07:05:09 +00001811 // Fall through to original instruction order.
1812 if ((Zone.isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
1813 || (!Zone.isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
1814 TryCand.Reason = NodeOrder;
1815 }
1816}
Andrew Trick28ebc892012-05-10 21:06:19 +00001817
Andrew Trick5429a6b2012-05-17 22:37:09 +00001818/// pickNodeFromQueue helper that returns true if the LHS reg pressure effect is
1819/// more desirable than RHS from scheduling standpoint.
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001820static bool compareRPDelta(const RegPressureDelta &LHS,
1821 const RegPressureDelta &RHS) {
1822 // Compare each component of pressure in decreasing order of importance
1823 // without checking if any are valid. Invalid PressureElements are assumed to
1824 // have UnitIncrease==0, so are neutral.
Andrew Trickc8fe4ec2012-05-24 22:11:01 +00001825
1826 // Avoid increasing the max critical pressure in the scheduled region.
Andrew Trick3b87f622012-11-07 07:05:09 +00001827 if (LHS.Excess.UnitIncrease != RHS.Excess.UnitIncrease) {
1828 DEBUG(dbgs() << "RP excess top - bot: "
1829 << (LHS.Excess.UnitIncrease - RHS.Excess.UnitIncrease) << '\n');
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001830 return LHS.Excess.UnitIncrease < RHS.Excess.UnitIncrease;
Andrew Trick3b87f622012-11-07 07:05:09 +00001831 }
Andrew Trickc8fe4ec2012-05-24 22:11:01 +00001832 // Avoid increasing the max critical pressure in the scheduled region.
Andrew Trick3b87f622012-11-07 07:05:09 +00001833 if (LHS.CriticalMax.UnitIncrease != RHS.CriticalMax.UnitIncrease) {
1834 DEBUG(dbgs() << "RP critical top - bot: "
1835 << (LHS.CriticalMax.UnitIncrease - RHS.CriticalMax.UnitIncrease)
1836 << '\n');
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001837 return LHS.CriticalMax.UnitIncrease < RHS.CriticalMax.UnitIncrease;
Andrew Trick3b87f622012-11-07 07:05:09 +00001838 }
Andrew Trickc8fe4ec2012-05-24 22:11:01 +00001839 // Avoid increasing the max pressure of the entire region.
Andrew Trick3b87f622012-11-07 07:05:09 +00001840 if (LHS.CurrentMax.UnitIncrease != RHS.CurrentMax.UnitIncrease) {
1841 DEBUG(dbgs() << "RP current top - bot: "
1842 << (LHS.CurrentMax.UnitIncrease - RHS.CurrentMax.UnitIncrease)
1843 << '\n');
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001844 return LHS.CurrentMax.UnitIncrease < RHS.CurrentMax.UnitIncrease;
Andrew Trick3b87f622012-11-07 07:05:09 +00001845 }
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001846 return false;
1847}
1848
Andrew Trick3b87f622012-11-07 07:05:09 +00001849#ifndef NDEBUG
1850const char *ConvergingScheduler::getReasonStr(
1851 ConvergingScheduler::CandReason Reason) {
1852 switch (Reason) {
1853 case NoCand: return "NOCAND ";
1854 case SingleExcess: return "REG-EXCESS";
1855 case SingleCritical: return "REG-CRIT ";
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001856 case Cluster: return "CLUSTER ";
Andrew Trick3b87f622012-11-07 07:05:09 +00001857 case SingleMax: return "REG-MAX ";
1858 case MultiPressure: return "REG-MULTI ";
1859 case ResourceReduce: return "RES-REDUCE";
1860 case ResourceDemand: return "RES-DEMAND";
1861 case TopDepthReduce: return "TOP-DEPTH ";
1862 case TopPathReduce: return "TOP-PATH ";
1863 case BotHeightReduce:return "BOT-HEIGHT";
1864 case BotPathReduce: return "BOT-PATH ";
1865 case NextDefUse: return "DEF-USE ";
1866 case NodeOrder: return "ORDER ";
1867 };
Benjamin Kramerb7546872012-11-09 15:45:22 +00001868 llvm_unreachable("Unknown reason!");
Andrew Trick3b87f622012-11-07 07:05:09 +00001869}
1870
1871void ConvergingScheduler::traceCandidate(const SchedCandidate &Cand,
1872 const SchedBoundary &Zone) {
1873 const char *Label = getReasonStr(Cand.Reason);
1874 PressureElement P;
1875 unsigned ResIdx = 0;
1876 unsigned Latency = 0;
1877 switch (Cand.Reason) {
1878 default:
1879 break;
1880 case SingleExcess:
1881 P = Cand.RPDelta.Excess;
1882 break;
1883 case SingleCritical:
1884 P = Cand.RPDelta.CriticalMax;
1885 break;
1886 case SingleMax:
1887 P = Cand.RPDelta.CurrentMax;
1888 break;
1889 case ResourceReduce:
1890 ResIdx = Cand.Policy.ReduceResIdx;
1891 break;
1892 case ResourceDemand:
1893 ResIdx = Cand.Policy.DemandResIdx;
1894 break;
1895 case TopDepthReduce:
1896 Latency = Cand.SU->getDepth();
1897 break;
1898 case TopPathReduce:
1899 Latency = Cand.SU->getHeight();
1900 break;
1901 case BotHeightReduce:
1902 Latency = Cand.SU->getHeight();
1903 break;
1904 case BotPathReduce:
1905 Latency = Cand.SU->getDepth();
1906 break;
1907 }
1908 dbgs() << Label << " " << Zone.Available.getName() << " ";
1909 if (P.isValid())
1910 dbgs() << TRI->getRegPressureSetName(P.PSetID) << ":" << P.UnitIncrease
1911 << " ";
1912 else
1913 dbgs() << " ";
1914 if (ResIdx)
1915 dbgs() << SchedModel->getProcResource(ResIdx)->Name << " ";
1916 else
1917 dbgs() << " ";
1918 if (Latency)
1919 dbgs() << Latency << " cycles ";
1920 else
1921 dbgs() << " ";
1922 Cand.SU->dump(DAG);
1923}
1924#endif
1925
Andrew Trick7196a8f2012-05-10 21:06:16 +00001926/// Pick the best candidate from the top queue.
1927///
1928/// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
1929/// DAG building. To adjust for the current scheduling location we need to
1930/// maintain the number of vreg uses remaining to be top-scheduled.
Andrew Trick3b87f622012-11-07 07:05:09 +00001931void ConvergingScheduler::pickNodeFromQueue(SchedBoundary &Zone,
1932 const RegPressureTracker &RPTracker,
1933 SchedCandidate &Cand) {
1934 ReadyQueue &Q = Zone.Available;
1935
Andrew Trickf3234242012-05-24 22:11:12 +00001936 DEBUG(Q.dump());
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001937
Andrew Trick7196a8f2012-05-10 21:06:16 +00001938 // getMaxPressureDelta temporarily modifies the tracker.
1939 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
1940
Andrew Trick8c2d9212012-05-24 22:11:03 +00001941 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
Andrew Trick7196a8f2012-05-10 21:06:16 +00001942
Andrew Trick3b87f622012-11-07 07:05:09 +00001943 SchedCandidate TryCand(Cand.Policy);
1944 TryCand.SU = *I;
1945 tryCandidate(Cand, TryCand, Zone, RPTracker, TempTracker);
1946 if (TryCand.Reason != NoCand) {
1947 // Initialize resource delta if needed in case future heuristics query it.
1948 if (TryCand.ResDelta == SchedResourceDelta())
1949 TryCand.initResourceDelta(DAG, SchedModel);
1950 Cand.setBest(TryCand);
1951 DEBUG(traceCandidate(Cand, Zone));
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001952 }
Andrew Trick7196a8f2012-05-10 21:06:16 +00001953 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001954}
1955
1956static void tracePick(const ConvergingScheduler::SchedCandidate &Cand,
1957 bool IsTop) {
1958 DEBUG(dbgs() << "Pick " << (IsTop ? "top" : "bot")
1959 << " SU(" << Cand.SU->NodeNum << ") "
1960 << ConvergingScheduler::getReasonStr(Cand.Reason) << '\n');
Andrew Trick7196a8f2012-05-10 21:06:16 +00001961}
1962
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001963/// Pick the best candidate node from either the top or bottom queue.
Andrew Trick3b87f622012-11-07 07:05:09 +00001964SUnit *ConvergingScheduler::pickNodeBidirectional(bool &IsTopNode) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001965 // Schedule as far as possible in the direction of no choice. This is most
1966 // efficient, but also provides the best heuristics for CriticalPSets.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001967 if (SUnit *SU = Bot.pickOnlyChoice()) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001968 IsTopNode = false;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001969 return SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001970 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001971 if (SUnit *SU = Top.pickOnlyChoice()) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001972 IsTopNode = true;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001973 return SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001974 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001975 CandPolicy NoPolicy;
1976 SchedCandidate BotCand(NoPolicy);
1977 SchedCandidate TopCand(NoPolicy);
1978 checkResourceLimits(TopCand, BotCand);
1979
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001980 // Prefer bottom scheduling when heuristics are silent.
Andrew Trick3b87f622012-11-07 07:05:09 +00001981 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
1982 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001983
1984 // If either Q has a single candidate that provides the least increase in
1985 // Excess pressure, we can immediately schedule from that Q.
1986 //
1987 // RegionCriticalPSets summarizes the pressure within the scheduled region and
1988 // affects picking from either Q. If scheduling in one direction must
1989 // increase pressure for one of the excess PSets, then schedule in that
1990 // direction first to provide more freedom in the other direction.
Andrew Trick3b87f622012-11-07 07:05:09 +00001991 if (BotCand.Reason == SingleExcess || BotCand.Reason == SingleCritical) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001992 IsTopNode = false;
Andrew Trick3b87f622012-11-07 07:05:09 +00001993 tracePick(BotCand, IsTopNode);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001994 return BotCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001995 }
1996 // Check if the top Q has a better candidate.
Andrew Trick3b87f622012-11-07 07:05:09 +00001997 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
1998 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001999
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002000 // If either Q has a single candidate that minimizes pressure above the
2001 // original region's pressure pick it.
Andrew Trick3b87f622012-11-07 07:05:09 +00002002 if (TopCand.Reason <= SingleMax || BotCand.Reason <= SingleMax) {
2003 if (TopCand.Reason < BotCand.Reason) {
2004 IsTopNode = true;
2005 tracePick(TopCand, IsTopNode);
2006 return TopCand.SU;
2007 }
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002008 IsTopNode = false;
Andrew Trick3b87f622012-11-07 07:05:09 +00002009 tracePick(BotCand, IsTopNode);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002010 return BotCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002011 }
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002012 // Check for a salient pressure difference and pick the best from either side.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002013 if (compareRPDelta(TopCand.RPDelta, BotCand.RPDelta)) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002014 IsTopNode = true;
Andrew Trick3b87f622012-11-07 07:05:09 +00002015 tracePick(TopCand, IsTopNode);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002016 return TopCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002017 }
Andrew Trick3b87f622012-11-07 07:05:09 +00002018 // Otherwise prefer the bottom candidate, in node order if all else failed.
2019 if (TopCand.Reason < BotCand.Reason) {
2020 IsTopNode = true;
2021 tracePick(TopCand, IsTopNode);
2022 return TopCand.SU;
2023 }
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002024 IsTopNode = false;
Andrew Trick3b87f622012-11-07 07:05:09 +00002025 tracePick(BotCand, IsTopNode);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002026 return BotCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002027}
2028
2029/// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
Andrew Trick7196a8f2012-05-10 21:06:16 +00002030SUnit *ConvergingScheduler::pickNode(bool &IsTopNode) {
2031 if (DAG->top() == DAG->bottom()) {
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002032 assert(Top.Available.empty() && Top.Pending.empty() &&
2033 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
Andrew Trick7196a8f2012-05-10 21:06:16 +00002034 return NULL;
2035 }
Andrew Trick7196a8f2012-05-10 21:06:16 +00002036 SUnit *SU;
Andrew Trick30c6ec22012-10-08 18:53:53 +00002037 do {
2038 if (ForceTopDown) {
2039 SU = Top.pickOnlyChoice();
2040 if (!SU) {
Andrew Trick3b87f622012-11-07 07:05:09 +00002041 CandPolicy NoPolicy;
2042 SchedCandidate TopCand(NoPolicy);
2043 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
2044 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick30c6ec22012-10-08 18:53:53 +00002045 SU = TopCand.SU;
2046 }
2047 IsTopNode = true;
Andrew Trick8ddd9d52012-05-24 23:11:17 +00002048 }
Andrew Trick30c6ec22012-10-08 18:53:53 +00002049 else if (ForceBottomUp) {
2050 SU = Bot.pickOnlyChoice();
2051 if (!SU) {
Andrew Trick3b87f622012-11-07 07:05:09 +00002052 CandPolicy NoPolicy;
2053 SchedCandidate BotCand(NoPolicy);
2054 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
2055 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick30c6ec22012-10-08 18:53:53 +00002056 SU = BotCand.SU;
2057 }
2058 IsTopNode = false;
Andrew Trick8ddd9d52012-05-24 23:11:17 +00002059 }
Andrew Trick30c6ec22012-10-08 18:53:53 +00002060 else {
Andrew Trick3b87f622012-11-07 07:05:09 +00002061 SU = pickNodeBidirectional(IsTopNode);
Andrew Trick30c6ec22012-10-08 18:53:53 +00002062 }
2063 } while (SU->isScheduled);
2064
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002065 if (SU->isTopReady())
2066 Top.removeReady(SU);
2067 if (SU->isBottomReady())
2068 Bot.removeReady(SU);
Andrew Trickc7a098f2012-05-25 02:02:39 +00002069
2070 DEBUG(dbgs() << "*** " << (IsTopNode ? "Top" : "Bottom")
2071 << " Scheduling Instruction in cycle "
2072 << (IsTopNode ? Top.CurrCycle : Bot.CurrCycle) << '\n';
2073 SU->dump(DAG));
Andrew Trick7196a8f2012-05-10 21:06:16 +00002074 return SU;
2075}
2076
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002077/// Update the scheduler's state after scheduling a node. This is the same node
2078/// that was just returned by pickNode(). However, ScheduleDAGMI needs to update
Andrew Trickb7e02892012-06-05 21:11:27 +00002079/// it's state based on the current cycle before MachineSchedStrategy does.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002080void ConvergingScheduler::schedNode(SUnit *SU, bool IsTopNode) {
Andrew Trickb7e02892012-06-05 21:11:27 +00002081 if (IsTopNode) {
2082 SU->TopReadyCycle = Top.CurrCycle;
Andrew Trick7f8c74c2012-06-29 03:23:22 +00002083 Top.bumpNode(SU);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002084 }
Andrew Trickb7e02892012-06-05 21:11:27 +00002085 else {
2086 SU->BotReadyCycle = Bot.CurrCycle;
Andrew Trick7f8c74c2012-06-29 03:23:22 +00002087 Bot.bumpNode(SU);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002088 }
2089}
2090
Andrew Trick17d35e52012-03-14 04:00:41 +00002091/// Create the standard converging machine scheduler. This will be used as the
2092/// default scheduler if the target does not set a default.
2093static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C) {
Benjamin Kramer689e0b42012-03-14 11:26:37 +00002094 assert((!ForceTopDown || !ForceBottomUp) &&
Andrew Trick17d35e52012-03-14 04:00:41 +00002095 "-misched-topdown incompatible with -misched-bottomup");
Andrew Trick9b5caaa2012-11-12 19:40:10 +00002096 ScheduleDAGMI *DAG = new ScheduleDAGMI(C, new ConvergingScheduler());
2097 // Register DAG post-processors.
2098 if (EnableLoadCluster)
2099 DAG->addMutation(new LoadClusterMutation(DAG->TII, DAG->TRI));
Andrew Trick6996fd02012-11-12 19:52:20 +00002100 if (EnableMacroFusion)
2101 DAG->addMutation(new MacroFusion(DAG->TII));
Andrew Trick9b5caaa2012-11-12 19:40:10 +00002102 return DAG;
Andrew Trick42b7a712012-01-17 06:55:03 +00002103}
2104static MachineSchedRegistry
Andrew Trick17d35e52012-03-14 04:00:41 +00002105ConvergingSchedRegistry("converge", "Standard converging scheduler.",
2106 createConvergingSched);
Andrew Trick42b7a712012-01-17 06:55:03 +00002107
2108//===----------------------------------------------------------------------===//
Andrew Trick1e94e982012-10-15 18:02:27 +00002109// ILP Scheduler. Currently for experimental analysis of heuristics.
2110//===----------------------------------------------------------------------===//
2111
2112namespace {
2113/// \brief Order nodes by the ILP metric.
2114struct ILPOrder {
Andrew Trick178f7d02013-01-25 04:01:04 +00002115 const SchedDFSResult *DFSResult;
2116 const BitVector *ScheduledTrees;
Andrew Trick1e94e982012-10-15 18:02:27 +00002117 bool MaximizeILP;
2118
Andrew Trick178f7d02013-01-25 04:01:04 +00002119 ILPOrder(bool MaxILP): DFSResult(0), ScheduledTrees(0), MaximizeILP(MaxILP) {}
Andrew Trick1e94e982012-10-15 18:02:27 +00002120
2121 /// \brief Apply a less-than relation on node priority.
Andrew Trick8b1496c2012-11-28 05:13:28 +00002122 ///
2123 /// (Return true if A comes after B in the Q.)
Andrew Trick1e94e982012-10-15 18:02:27 +00002124 bool operator()(const SUnit *A, const SUnit *B) const {
Andrew Trick8b1496c2012-11-28 05:13:28 +00002125 unsigned SchedTreeA = DFSResult->getSubtreeID(A);
2126 unsigned SchedTreeB = DFSResult->getSubtreeID(B);
2127 if (SchedTreeA != SchedTreeB) {
2128 // Unscheduled trees have lower priority.
2129 if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
2130 return ScheduledTrees->test(SchedTreeB);
2131
2132 // Trees with shallower connections have have lower priority.
2133 if (DFSResult->getSubtreeLevel(SchedTreeA)
2134 != DFSResult->getSubtreeLevel(SchedTreeB)) {
2135 return DFSResult->getSubtreeLevel(SchedTreeA)
2136 < DFSResult->getSubtreeLevel(SchedTreeB);
2137 }
2138 }
Andrew Trick1e94e982012-10-15 18:02:27 +00002139 if (MaximizeILP)
Andrew Trick8b1496c2012-11-28 05:13:28 +00002140 return DFSResult->getILP(A) < DFSResult->getILP(B);
Andrew Trick1e94e982012-10-15 18:02:27 +00002141 else
Andrew Trick8b1496c2012-11-28 05:13:28 +00002142 return DFSResult->getILP(A) > DFSResult->getILP(B);
Andrew Trick1e94e982012-10-15 18:02:27 +00002143 }
2144};
2145
2146/// \brief Schedule based on the ILP metric.
2147class ILPScheduler : public MachineSchedStrategy {
Andrew Trick8b1496c2012-11-28 05:13:28 +00002148 /// In case all subtrees are eventually connected to a common root through
2149 /// data dependence (e.g. reduction), place an upper limit on their size.
2150 ///
2151 /// FIXME: A subtree limit is generally good, but in the situation commented
2152 /// above, where multiple similar subtrees feed a common root, we should
2153 /// only split at a point where the resulting subtrees will be balanced.
2154 /// (a motivating test case must be found).
2155 static const unsigned SubtreeLimit = 16;
2156
Andrew Trick178f7d02013-01-25 04:01:04 +00002157 ScheduleDAGMI *DAG;
Andrew Trick1e94e982012-10-15 18:02:27 +00002158 ILPOrder Cmp;
2159
2160 std::vector<SUnit*> ReadyQ;
2161public:
Andrew Trick178f7d02013-01-25 04:01:04 +00002162 ILPScheduler(bool MaximizeILP): DAG(0), Cmp(MaximizeILP) {}
Andrew Trick1e94e982012-10-15 18:02:27 +00002163
Andrew Trick178f7d02013-01-25 04:01:04 +00002164 virtual void initialize(ScheduleDAGMI *dag) {
2165 DAG = dag;
Andrew Trick4e1fb182013-01-25 06:33:57 +00002166 DAG->computeDFSResult();
Andrew Trick178f7d02013-01-25 04:01:04 +00002167 Cmp.DFSResult = DAG->getDFSResult();
2168 Cmp.ScheduledTrees = &DAG->getScheduledTrees();
Andrew Trick1e94e982012-10-15 18:02:27 +00002169 ReadyQ.clear();
Andrew Trick1e94e982012-10-15 18:02:27 +00002170 }
2171
2172 virtual void registerRoots() {
Benjamin Kramer5175fd92012-11-29 14:36:26 +00002173 // Restore the heap in ReadyQ with the updated DFS results.
2174 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
Andrew Trick1e94e982012-10-15 18:02:27 +00002175 }
2176
2177 /// Implement MachineSchedStrategy interface.
2178 /// -----------------------------------------
2179
Andrew Trick8b1496c2012-11-28 05:13:28 +00002180 /// Callback to select the highest priority node from the ready Q.
Andrew Trick1e94e982012-10-15 18:02:27 +00002181 virtual SUnit *pickNode(bool &IsTopNode) {
2182 if (ReadyQ.empty()) return NULL;
2183 pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2184 SUnit *SU = ReadyQ.back();
2185 ReadyQ.pop_back();
2186 IsTopNode = false;
Andrew Trick8b1496c2012-11-28 05:13:28 +00002187 DEBUG(dbgs() << "*** Scheduling " << "SU(" << SU->NodeNum << "): "
2188 << *SU->getInstr()
Andrew Trick178f7d02013-01-25 04:01:04 +00002189 << " ILP: " << DAG->getDFSResult()->getILP(SU)
2190 << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU) << " @"
2191 << DAG->getDFSResult()->getSubtreeLevel(
2192 DAG->getDFSResult()->getSubtreeID(SU)) << '\n');
Andrew Trick1e94e982012-10-15 18:02:27 +00002193 return SU;
2194 }
2195
Andrew Trick178f7d02013-01-25 04:01:04 +00002196 /// \brief Scheduler callback to notify that a new subtree is scheduled.
2197 virtual void scheduleTree(unsigned SubtreeID) {
2198 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2199 }
2200
Andrew Trick8b1496c2012-11-28 05:13:28 +00002201 /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
2202 /// DFSResults, and resort the priority Q.
2203 virtual void schedNode(SUnit *SU, bool IsTopNode) {
2204 assert(!IsTopNode && "SchedDFSResult needs bottom-up");
Andrew Trick8b1496c2012-11-28 05:13:28 +00002205 }
Andrew Trick1e94e982012-10-15 18:02:27 +00002206
2207 virtual void releaseTopNode(SUnit *) { /*only called for top roots*/ }
2208
2209 virtual void releaseBottomNode(SUnit *SU) {
2210 ReadyQ.push_back(SU);
2211 std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2212 }
2213};
2214} // namespace
2215
2216static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
2217 return new ScheduleDAGMI(C, new ILPScheduler(true));
2218}
2219static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
2220 return new ScheduleDAGMI(C, new ILPScheduler(false));
2221}
2222static MachineSchedRegistry ILPMaxRegistry(
2223 "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
2224static MachineSchedRegistry ILPMinRegistry(
2225 "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
2226
2227//===----------------------------------------------------------------------===//
Andrew Trick5edf2f02012-01-14 02:17:06 +00002228// Machine Instruction Shuffler for Correctness Testing
2229//===----------------------------------------------------------------------===//
2230
Andrew Trick96f678f2012-01-13 06:30:30 +00002231#ifndef NDEBUG
2232namespace {
Andrew Trick17d35e52012-03-14 04:00:41 +00002233/// Apply a less-than relation on the node order, which corresponds to the
2234/// instruction order prior to scheduling. IsReverse implements greater-than.
2235template<bool IsReverse>
2236struct SUnitOrder {
Andrew Trickc6cf11b2012-01-17 06:55:07 +00002237 bool operator()(SUnit *A, SUnit *B) const {
Andrew Trick17d35e52012-03-14 04:00:41 +00002238 if (IsReverse)
2239 return A->NodeNum > B->NodeNum;
2240 else
2241 return A->NodeNum < B->NodeNum;
Andrew Trickc6cf11b2012-01-17 06:55:07 +00002242 }
2243};
2244
Andrew Trick96f678f2012-01-13 06:30:30 +00002245/// Reorder instructions as much as possible.
Andrew Trick17d35e52012-03-14 04:00:41 +00002246class InstructionShuffler : public MachineSchedStrategy {
2247 bool IsAlternating;
2248 bool IsTopDown;
2249
2250 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
2251 // gives nodes with a higher number higher priority causing the latest
2252 // instructions to be scheduled first.
2253 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
2254 TopQ;
2255 // When scheduling bottom-up, use greater-than as the queue priority.
2256 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
2257 BottomQ;
Andrew Trick96f678f2012-01-13 06:30:30 +00002258public:
Andrew Trick17d35e52012-03-14 04:00:41 +00002259 InstructionShuffler(bool alternate, bool topdown)
2260 : IsAlternating(alternate), IsTopDown(topdown) {}
Andrew Trick96f678f2012-01-13 06:30:30 +00002261
Andrew Trick17d35e52012-03-14 04:00:41 +00002262 virtual void initialize(ScheduleDAGMI *) {
2263 TopQ.clear();
2264 BottomQ.clear();
2265 }
Andrew Trickc6cf11b2012-01-17 06:55:07 +00002266
Andrew Trick17d35e52012-03-14 04:00:41 +00002267 /// Implement MachineSchedStrategy interface.
2268 /// -----------------------------------------
2269
2270 virtual SUnit *pickNode(bool &IsTopNode) {
2271 SUnit *SU;
2272 if (IsTopDown) {
2273 do {
2274 if (TopQ.empty()) return NULL;
2275 SU = TopQ.top();
2276 TopQ.pop();
2277 } while (SU->isScheduled);
2278 IsTopNode = true;
2279 }
2280 else {
2281 do {
2282 if (BottomQ.empty()) return NULL;
2283 SU = BottomQ.top();
2284 BottomQ.pop();
2285 } while (SU->isScheduled);
2286 IsTopNode = false;
2287 }
2288 if (IsAlternating)
2289 IsTopDown = !IsTopDown;
Andrew Trickc6cf11b2012-01-17 06:55:07 +00002290 return SU;
2291 }
2292
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002293 virtual void schedNode(SUnit *SU, bool IsTopNode) {}
2294
Andrew Trick17d35e52012-03-14 04:00:41 +00002295 virtual void releaseTopNode(SUnit *SU) {
2296 TopQ.push(SU);
2297 }
2298 virtual void releaseBottomNode(SUnit *SU) {
2299 BottomQ.push(SU);
Andrew Trick96f678f2012-01-13 06:30:30 +00002300 }
2301};
2302} // namespace
2303
Andrew Trickc174eaf2012-03-08 01:41:12 +00002304static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
Andrew Trick17d35e52012-03-14 04:00:41 +00002305 bool Alternate = !ForceTopDown && !ForceBottomUp;
2306 bool TopDown = !ForceBottomUp;
Benjamin Kramer689e0b42012-03-14 11:26:37 +00002307 assert((TopDown || !ForceTopDown) &&
Andrew Trick17d35e52012-03-14 04:00:41 +00002308 "-misched-topdown incompatible with -misched-bottomup");
2309 return new ScheduleDAGMI(C, new InstructionShuffler(Alternate, TopDown));
Andrew Trick96f678f2012-01-13 06:30:30 +00002310}
Andrew Trick17d35e52012-03-14 04:00:41 +00002311static MachineSchedRegistry ShufflerRegistry(
2312 "shuffle", "Shuffle machine instructions alternating directions",
2313 createInstructionShuffler);
Andrew Trick96f678f2012-01-13 06:30:30 +00002314#endif // !NDEBUG
Andrew Trick30849792013-01-25 07:45:29 +00002315
2316//===----------------------------------------------------------------------===//
2317// GraphWriter support for ScheduleDAGMI.
2318//===----------------------------------------------------------------------===//
2319
2320#ifndef NDEBUG
2321namespace llvm {
2322
2323template<> struct GraphTraits<
2324 ScheduleDAGMI*> : public GraphTraits<ScheduleDAG*> {};
2325
2326template<>
2327struct DOTGraphTraits<ScheduleDAGMI*> : public DefaultDOTGraphTraits {
2328
2329 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
2330
2331 static std::string getGraphName(const ScheduleDAG *G) {
2332 return G->MF.getName();
2333 }
2334
2335 static bool renderGraphFromBottomUp() {
2336 return true;
2337 }
2338
2339 static bool isNodeHidden(const SUnit *Node) {
2340 return (Node->NumPreds > 10 || Node->NumSuccs > 10);
2341 }
2342
2343 static bool hasNodeAddressLabel(const SUnit *Node,
2344 const ScheduleDAG *Graph) {
2345 return false;
2346 }
2347
2348 /// If you want to override the dot attributes printed for a particular
2349 /// edge, override this method.
2350 static std::string getEdgeAttributes(const SUnit *Node,
2351 SUnitIterator EI,
2352 const ScheduleDAG *Graph) {
2353 if (EI.isArtificialDep())
2354 return "color=cyan,style=dashed";
2355 if (EI.isCtrlDep())
2356 return "color=blue,style=dashed";
2357 return "";
2358 }
2359
2360 static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) {
2361 std::string Str;
2362 raw_string_ostream SS(Str);
2363 SS << "SU(" << SU->NodeNum << ')';
2364 return SS.str();
2365 }
2366 static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G) {
2367 return G->getGraphNodeLabel(SU);
2368 }
2369
2370 static std::string getNodeAttributes(const SUnit *N,
2371 const ScheduleDAG *Graph) {
2372 std::string Str("shape=Mrecord");
2373 const SchedDFSResult *DFS =
2374 static_cast<const ScheduleDAGMI*>(Graph)->getDFSResult();
2375 if (DFS) {
2376 Str += ",style=filled,fillcolor=\"#";
2377 Str += DOT::getColorString(DFS->getSubtreeID(N));
2378 Str += '"';
2379 }
2380 return Str;
2381 }
2382};
2383} // namespace llvm
2384#endif // NDEBUG
2385
2386/// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
2387/// rendered using 'dot'.
2388///
2389void ScheduleDAGMI::viewGraph(const Twine &Name, const Twine &Title) {
2390#ifndef NDEBUG
2391 ViewGraph(this, Name, false, Title);
2392#else
2393 errs() << "ScheduleDAGMI::viewGraph is only available in debug builds on "
2394 << "systems with Graphviz or gv!\n";
2395#endif // NDEBUG
2396}
2397
2398/// Out-of-line implementation with no arguments is handy for gdb.
2399void ScheduleDAGMI::viewGraph() {
2400 viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName());
2401}