blob: a7a3bb80730e3988dc69f35729701bef98046e45 [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"
Jakub Staszak760fa5d2013-03-10 13:11:23 +000022#include "llvm/CodeGen/MachineDominators.h"
23#include "llvm/CodeGen/MachineLoopInfo.h"
Andrew Trick1f8b48a2013-06-21 18:32:58 +000024#include "llvm/CodeGen/MachineRegisterInfo.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000025#include "llvm/CodeGen/Passes.h"
Andrew Trick15252602012-06-06 20:29:31 +000026#include "llvm/CodeGen/RegisterClassInfo.h"
Andrew Trick53e98a22012-11-28 05:13:24 +000027#include "llvm/CodeGen/ScheduleDFS.h"
Andrew Trick0a39d4e2012-05-24 22:11:09 +000028#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000029#include "llvm/Support/CommandLine.h"
30#include "llvm/Support/Debug.h"
31#include "llvm/Support/ErrorHandling.h"
Andrew Trick30849792013-01-25 07:45:29 +000032#include "llvm/Support/GraphWriter.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000033#include "llvm/Support/raw_ostream.h"
Jakub Staszak38084db2013-06-14 00:00:13 +000034#include "llvm/Target/TargetInstrInfo.h"
Andrew Trickc6cf11b2012-01-17 06:55:07 +000035#include <queue>
36
Andrew Trick96f678f2012-01-13 06:30:30 +000037using namespace llvm;
38
Andrew Trick78e5efe2012-09-11 00:39:15 +000039namespace llvm {
40cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
41 cl::desc("Force top-down list scheduling"));
42cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
43 cl::desc("Force bottom-up list scheduling"));
44}
Andrew Trick17d35e52012-03-14 04:00:41 +000045
Andrew Trick0df7f882012-03-07 00:18:25 +000046#ifndef NDEBUG
47static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
48 cl::desc("Pop up a window to show MISched dags after they are processed"));
Lang Hames23f1cbb2012-03-19 18:38:38 +000049
50static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
51 cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
Andrew Trick0df7f882012-03-07 00:18:25 +000052#else
53static bool ViewMISchedDAGs = false;
54#endif // NDEBUG
55
Andrew Trickea574332013-08-23 17:48:43 +000056static cl::opt<bool> EnableCyclicPath("misched-cyclicpath", cl::Hidden,
57 cl::desc("Enable cyclic critical path analysis."), cl::init(false));
58
Andrew Trick9b5caaa2012-11-12 19:40:10 +000059static cl::opt<bool> EnableLoadCluster("misched-cluster", cl::Hidden,
Andrew Trickad1cc1d2012-11-13 08:47:29 +000060 cl::desc("Enable load clustering."), cl::init(true));
Andrew Trick9b5caaa2012-11-12 19:40:10 +000061
Andrew Trick6996fd02012-11-12 19:52:20 +000062// Experimental heuristics
63static cl::opt<bool> EnableMacroFusion("misched-fusion", cl::Hidden,
Andrew Trickad1cc1d2012-11-13 08:47:29 +000064 cl::desc("Enable scheduling for macro fusion."), cl::init(true));
Andrew Trick6996fd02012-11-12 19:52:20 +000065
Andrew Trickfff2d3a2013-03-08 05:40:34 +000066static cl::opt<bool> VerifyScheduling("verify-misched", cl::Hidden,
67 cl::desc("Verify machine instrs before and after machine scheduling"));
68
Andrew Trick178f7d02013-01-25 04:01:04 +000069// DAG subtrees must have at least this many nodes.
70static const unsigned MinSubtreeSize = 8;
71
Andrew Trick5edf2f02012-01-14 02:17:06 +000072//===----------------------------------------------------------------------===//
73// Machine Instruction Scheduling Pass and Registry
74//===----------------------------------------------------------------------===//
75
Andrew Trick86b7e2a2012-04-24 20:36:19 +000076MachineSchedContext::MachineSchedContext():
77 MF(0), MLI(0), MDT(0), PassConfig(0), AA(0), LIS(0) {
78 RegClassInfo = new RegisterClassInfo();
79}
80
81MachineSchedContext::~MachineSchedContext() {
82 delete RegClassInfo;
83}
84
Andrew Trick96f678f2012-01-13 06:30:30 +000085namespace {
Andrew Trick42b7a712012-01-17 06:55:03 +000086/// MachineScheduler runs after coalescing and before register allocation.
Andrew Trickc174eaf2012-03-08 01:41:12 +000087class MachineScheduler : public MachineSchedContext,
88 public MachineFunctionPass {
Andrew Trick96f678f2012-01-13 06:30:30 +000089public:
Andrew Trick42b7a712012-01-17 06:55:03 +000090 MachineScheduler();
Andrew Trick96f678f2012-01-13 06:30:30 +000091
92 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
93
94 virtual void releaseMemory() {}
95
96 virtual bool runOnMachineFunction(MachineFunction&);
97
98 virtual void print(raw_ostream &O, const Module* = 0) const;
99
100 static char ID; // Class identification, replacement for typeinfo
101};
102} // namespace
103
Andrew Trick42b7a712012-01-17 06:55:03 +0000104char MachineScheduler::ID = 0;
Andrew Trick96f678f2012-01-13 06:30:30 +0000105
Andrew Trick42b7a712012-01-17 06:55:03 +0000106char &llvm::MachineSchedulerID = MachineScheduler::ID;
Andrew Trick96f678f2012-01-13 06:30:30 +0000107
Andrew Trick42b7a712012-01-17 06:55:03 +0000108INITIALIZE_PASS_BEGIN(MachineScheduler, "misched",
Andrew Trick96f678f2012-01-13 06:30:30 +0000109 "Machine Instruction Scheduler", false, false)
110INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
111INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
112INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
Andrew Trick42b7a712012-01-17 06:55:03 +0000113INITIALIZE_PASS_END(MachineScheduler, "misched",
Andrew Trick96f678f2012-01-13 06:30:30 +0000114 "Machine Instruction Scheduler", false, false)
115
Andrew Trick42b7a712012-01-17 06:55:03 +0000116MachineScheduler::MachineScheduler()
Andrew Trickc174eaf2012-03-08 01:41:12 +0000117: MachineFunctionPass(ID) {
Andrew Trick42b7a712012-01-17 06:55:03 +0000118 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Andrew Trick96f678f2012-01-13 06:30:30 +0000119}
120
Andrew Trick42b7a712012-01-17 06:55:03 +0000121void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
Andrew Trick96f678f2012-01-13 06:30:30 +0000122 AU.setPreservesCFG();
123 AU.addRequiredID(MachineDominatorsID);
124 AU.addRequired<MachineLoopInfo>();
125 AU.addRequired<AliasAnalysis>();
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000126 AU.addRequired<TargetPassConfig>();
Andrew Trick96f678f2012-01-13 06:30:30 +0000127 AU.addRequired<SlotIndexes>();
128 AU.addPreserved<SlotIndexes>();
129 AU.addRequired<LiveIntervals>();
130 AU.addPreserved<LiveIntervals>();
Andrew Trick96f678f2012-01-13 06:30:30 +0000131 MachineFunctionPass::getAnalysisUsage(AU);
132}
133
Andrew Trick96f678f2012-01-13 06:30:30 +0000134MachinePassRegistry MachineSchedRegistry::Registry;
135
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000136/// A dummy default scheduler factory indicates whether the scheduler
137/// is overridden on the command line.
138static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
139 return 0;
140}
Andrew Trick96f678f2012-01-13 06:30:30 +0000141
142/// MachineSchedOpt allows command line selection of the scheduler.
143static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
144 RegisterPassParser<MachineSchedRegistry> >
145MachineSchedOpt("misched",
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000146 cl::init(&useDefaultMachineSched), cl::Hidden,
Andrew Trick96f678f2012-01-13 06:30:30 +0000147 cl::desc("Machine instruction scheduler to use"));
148
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000149static MachineSchedRegistry
Andrew Trick17d35e52012-03-14 04:00:41 +0000150DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000151 useDefaultMachineSched);
152
Andrew Trick17d35e52012-03-14 04:00:41 +0000153/// Forward declare the standard machine scheduler. This will be used as the
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000154/// default scheduler if the target does not set a default.
Andrew Trick17d35e52012-03-14 04:00:41 +0000155static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C);
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000156
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000157
158/// Decrement this iterator until reaching the top or a non-debug instr.
Andrew Trick663bd992013-08-30 04:36:57 +0000159static MachineBasicBlock::const_iterator
160priorNonDebug(MachineBasicBlock::const_iterator I,
161 MachineBasicBlock::const_iterator Beg) {
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000162 assert(I != Beg && "reached the top of the region, cannot decrement");
163 while (--I != Beg) {
164 if (!I->isDebugValue())
165 break;
166 }
167 return I;
168}
169
Andrew Trick663bd992013-08-30 04:36:57 +0000170/// Non-const version.
171static MachineBasicBlock::iterator
172priorNonDebug(MachineBasicBlock::iterator I,
173 MachineBasicBlock::const_iterator Beg) {
174 return const_cast<MachineInstr*>(
175 &*priorNonDebug(MachineBasicBlock::const_iterator(I), Beg));
176}
177
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000178/// If this iterator is a debug value, increment until reaching the End or a
179/// non-debug instruction.
180static MachineBasicBlock::iterator
181nextIfDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator End) {
Andrew Trick811d92682012-05-17 18:35:03 +0000182 for(; I != End; ++I) {
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000183 if (!I->isDebugValue())
184 break;
185 }
186 return I;
187}
188
Andrew Trickcb058d52012-03-14 04:00:38 +0000189/// Top-level MachineScheduler pass driver.
190///
191/// Visit blocks in function order. Divide each block into scheduling regions
Andrew Trick17d35e52012-03-14 04:00:41 +0000192/// and visit them bottom-up. Visiting regions bottom-up is not required, but is
193/// consistent with the DAG builder, which traverses the interior of the
194/// scheduling regions bottom-up.
Andrew Trickcb058d52012-03-14 04:00:38 +0000195///
196/// This design avoids exposing scheduling boundaries to the DAG builder,
Andrew Trick17d35e52012-03-14 04:00:41 +0000197/// simplifying the DAG builder's support for "special" target instructions.
198/// At the same time the design allows target schedulers to operate across
Andrew Trickcb058d52012-03-14 04:00:38 +0000199/// scheduling boundaries, for example to bundle the boudary instructions
200/// without reordering them. This creates complexity, because the target
201/// scheduler must update the RegionBegin and RegionEnd positions cached by
202/// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
203/// design would be to split blocks at scheduling boundaries, but LLVM has a
204/// general bias against block splitting purely for implementation simplicity.
Andrew Trick42b7a712012-01-17 06:55:03 +0000205bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
Andrew Trick89c324b2012-05-10 21:06:21 +0000206 DEBUG(dbgs() << "Before MISsched:\n"; mf.print(dbgs()));
207
Andrew Trick96f678f2012-01-13 06:30:30 +0000208 // Initialize the context of the pass.
209 MF = &mf;
210 MLI = &getAnalysis<MachineLoopInfo>();
211 MDT = &getAnalysis<MachineDominatorTree>();
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000212 PassConfig = &getAnalysis<TargetPassConfig>();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000213 AA = &getAnalysis<AliasAnalysis>();
214
Lang Hames907cc8f2012-01-27 22:36:19 +0000215 LIS = &getAnalysis<LiveIntervals>();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000216 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
Andrew Trick96f678f2012-01-13 06:30:30 +0000217
Andrew Trickfff2d3a2013-03-08 05:40:34 +0000218 if (VerifyScheduling) {
Andrew Trick5dca6132013-07-25 07:26:26 +0000219 DEBUG(LIS->dump());
Andrew Trickfff2d3a2013-03-08 05:40:34 +0000220 MF->verify(this, "Before machine scheduling.");
221 }
Andrew Trick86b7e2a2012-04-24 20:36:19 +0000222 RegClassInfo->runOnMachineFunction(*MF);
Andrew Trick006e1ab2012-04-24 17:56:43 +0000223
Andrew Trick96f678f2012-01-13 06:30:30 +0000224 // Select the scheduler, or set the default.
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000225 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
226 if (Ctor == useDefaultMachineSched) {
227 // Get the default scheduler set by the target.
228 Ctor = MachineSchedRegistry::getDefault();
229 if (!Ctor) {
Andrew Trick17d35e52012-03-14 04:00:41 +0000230 Ctor = createConvergingSched;
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000231 MachineSchedRegistry::setDefault(Ctor);
232 }
Andrew Trick96f678f2012-01-13 06:30:30 +0000233 }
234 // Instantiate the selected scheduler.
235 OwningPtr<ScheduleDAGInstrs> Scheduler(Ctor(this));
236
237 // Visit all machine basic blocks.
Andrew Trick006e1ab2012-04-24 17:56:43 +0000238 //
239 // TODO: Visit blocks in global postorder or postorder within the bottom-up
240 // loop tree. Then we can optionally compute global RegPressure.
Andrew Trick96f678f2012-01-13 06:30:30 +0000241 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
242 MBB != MBBEnd; ++MBB) {
243
Andrew Trick1fabd9f2012-03-09 08:02:51 +0000244 Scheduler->startBlock(MBB);
245
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000246 // Break the block into scheduling regions [I, RegionEnd), and schedule each
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +0000247 // region as soon as it is discovered. RegionEnd points the scheduling
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000248 // boundary at the bottom of the region. The DAG does not include RegionEnd,
249 // but the region does (i.e. the next RegionEnd is above the previous
250 // RegionBegin). If the current block has no terminator then RegionEnd ==
251 // MBB->end() for the bottom region.
252 //
253 // The Scheduler may insert instructions during either schedule() or
254 // exitRegion(), even for empty regions. So the local iterators 'I' and
255 // 'RegionEnd' are invalid across these calls.
Andrew Trick22764532012-11-06 07:10:34 +0000256 unsigned RemainingInstrs = MBB->size();
Andrew Trick7799eb42012-03-09 03:46:39 +0000257 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000258 RegionEnd != MBB->begin(); RegionEnd = Scheduler->begin()) {
Andrew Trick006e1ab2012-04-24 17:56:43 +0000259
Andrew Trick1fabd9f2012-03-09 08:02:51 +0000260 // Avoid decrementing RegionEnd for blocks with no terminator.
261 if (RegionEnd != MBB->end()
262 || TII->isSchedulingBoundary(llvm::prior(RegionEnd), MBB, *MF)) {
263 --RegionEnd;
264 // Count the boundary instruction.
Andrew Trick22764532012-11-06 07:10:34 +0000265 --RemainingInstrs;
Andrew Trick1fabd9f2012-03-09 08:02:51 +0000266 }
267
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000268 // The next region starts above the previous region. Look backward in the
269 // instruction stream until we find the nearest boundary.
Andrew Trickd2763f62013-08-23 17:48:33 +0000270 unsigned NumRegionInstrs = 0;
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000271 MachineBasicBlock::iterator I = RegionEnd;
Andrew Trickd2763f62013-08-23 17:48:33 +0000272 for(;I != MBB->begin(); --I, --RemainingInstrs, ++NumRegionInstrs) {
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000273 if (TII->isSchedulingBoundary(llvm::prior(I), MBB, *MF))
274 break;
275 }
Andrew Trick47c14452012-03-07 05:21:52 +0000276 // Notify the scheduler of the region, even if we may skip scheduling
277 // it. Perhaps it still needs to be bundled.
Andrew Trickd2763f62013-08-23 17:48:33 +0000278 Scheduler->enterRegion(MBB, I, RegionEnd, NumRegionInstrs);
Andrew Trick47c14452012-03-07 05:21:52 +0000279
280 // Skip empty scheduling regions (0 or 1 schedulable instructions).
281 if (I == RegionEnd || I == llvm::prior(RegionEnd)) {
Andrew Trick47c14452012-03-07 05:21:52 +0000282 // Close the current region. Bundle the terminator if needed.
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000283 // This invalidates 'RegionEnd' and 'I'.
Andrew Trick47c14452012-03-07 05:21:52 +0000284 Scheduler->exitRegion();
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000285 continue;
Andrew Trick3c58ba82012-01-14 02:17:18 +0000286 }
Andrew Trickbb0a2422012-05-24 22:11:14 +0000287 DEBUG(dbgs() << "********** MI Scheduling **********\n");
Craig Topper96601ca2012-08-22 06:07:19 +0000288 DEBUG(dbgs() << MF->getName()
Andrew Trickc8554232013-01-25 07:45:31 +0000289 << ":BB#" << MBB->getNumber() << " " << MBB->getName()
290 << "\n From: " << *I << " To: ";
Andrew Trick291411c2012-02-08 02:17:21 +0000291 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
292 else dbgs() << "End";
Andrew Trickd2763f62013-08-23 17:48:33 +0000293 dbgs() << " RegionInstrs: " << NumRegionInstrs
294 << " Remaining: " << RemainingInstrs << "\n");
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000295
Andrew Trickd24da972012-03-09 03:46:42 +0000296 // Schedule a region: possibly reorder instructions.
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000297 // This invalidates 'RegionEnd' and 'I'.
Andrew Trick953be892012-03-07 23:00:49 +0000298 Scheduler->schedule();
Andrew Trickd24da972012-03-09 03:46:42 +0000299
300 // Close the current region.
Andrew Trick47c14452012-03-07 05:21:52 +0000301 Scheduler->exitRegion();
302
303 // Scheduling has invalidated the current iterator 'I'. Ask the
304 // scheduler for the top of it's scheduled region.
305 RegionEnd = Scheduler->begin();
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000306 }
Andrew Trick22764532012-11-06 07:10:34 +0000307 assert(RemainingInstrs == 0 && "Instruction count mismatch!");
Andrew Trick953be892012-03-07 23:00:49 +0000308 Scheduler->finishBlock();
Andrew Trick96f678f2012-01-13 06:30:30 +0000309 }
Andrew Trick830da402012-04-01 07:24:23 +0000310 Scheduler->finalizeSchedule();
Andrew Trick5dca6132013-07-25 07:26:26 +0000311 DEBUG(LIS->dump());
Andrew Trickfff2d3a2013-03-08 05:40:34 +0000312 if (VerifyScheduling)
313 MF->verify(this, "After machine scheduling.");
Andrew Trick96f678f2012-01-13 06:30:30 +0000314 return true;
315}
316
Andrew Trick42b7a712012-01-17 06:55:03 +0000317void MachineScheduler::print(raw_ostream &O, const Module* m) const {
Andrew Trick96f678f2012-01-13 06:30:30 +0000318 // unimplemented
319}
320
Manman Renb720be62012-09-11 22:23:19 +0000321#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Andrew Trick78e5efe2012-09-11 00:39:15 +0000322void ReadyQueue::dump() {
Andrew Tricke52d5022013-06-17 21:45:05 +0000323 dbgs() << Name << ": ";
Andrew Trick78e5efe2012-09-11 00:39:15 +0000324 for (unsigned i = 0, e = Queue.size(); i < e; ++i)
325 dbgs() << Queue[i]->NodeNum << " ";
326 dbgs() << "\n";
327}
328#endif
Andrew Trick17d35e52012-03-14 04:00:41 +0000329
330//===----------------------------------------------------------------------===//
331// ScheduleDAGMI - Base class for MachineInstr scheduling with LiveIntervals
332// preservation.
333//===----------------------------------------------------------------------===//
334
Andrew Trick178f7d02013-01-25 04:01:04 +0000335ScheduleDAGMI::~ScheduleDAGMI() {
336 delete DFSResult;
337 DeleteContainerPointers(Mutations);
338 delete SchedImpl;
339}
340
Andrew Tricke38afe12013-04-24 15:54:43 +0000341bool ScheduleDAGMI::canAddEdge(SUnit *SuccSU, SUnit *PredSU) {
342 return SuccSU == &ExitSU || !Topo.IsReachable(PredSU, SuccSU);
343}
344
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000345bool ScheduleDAGMI::addEdge(SUnit *SuccSU, const SDep &PredDep) {
Andrew Trick6996fd02012-11-12 19:52:20 +0000346 if (SuccSU != &ExitSU) {
347 // Do not use WillCreateCycle, it assumes SD scheduling.
348 // If Pred is reachable from Succ, then the edge creates a cycle.
349 if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
350 return false;
351 Topo.AddPred(SuccSU, PredDep.getSUnit());
352 }
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000353 SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
354 // Return true regardless of whether a new edge needed to be inserted.
355 return true;
356}
357
Andrew Trickc174eaf2012-03-08 01:41:12 +0000358/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
359/// NumPredsLeft reaches zero, release the successor node.
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000360///
361/// FIXME: Adjust SuccSU height based on MinLatency.
Andrew Trick17d35e52012-03-14 04:00:41 +0000362void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
Andrew Trickc174eaf2012-03-08 01:41:12 +0000363 SUnit *SuccSU = SuccEdge->getSUnit();
364
Andrew Trickae692f22012-11-12 19:28:57 +0000365 if (SuccEdge->isWeak()) {
366 --SuccSU->WeakPredsLeft;
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000367 if (SuccEdge->isCluster())
368 NextClusterSucc = SuccSU;
Andrew Trickae692f22012-11-12 19:28:57 +0000369 return;
370 }
Andrew Trickc174eaf2012-03-08 01:41:12 +0000371#ifndef NDEBUG
372 if (SuccSU->NumPredsLeft == 0) {
373 dbgs() << "*** Scheduling failed! ***\n";
374 SuccSU->dump(this);
375 dbgs() << " has been released too many times!\n";
376 llvm_unreachable(0);
377 }
378#endif
379 --SuccSU->NumPredsLeft;
380 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
Andrew Trick17d35e52012-03-14 04:00:41 +0000381 SchedImpl->releaseTopNode(SuccSU);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000382}
383
384/// releaseSuccessors - Call releaseSucc on each of SU's successors.
Andrew Trick17d35e52012-03-14 04:00:41 +0000385void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
Andrew Trickc174eaf2012-03-08 01:41:12 +0000386 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
387 I != E; ++I) {
388 releaseSucc(SU, &*I);
389 }
390}
391
Andrew Trick17d35e52012-03-14 04:00:41 +0000392/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
393/// NumSuccsLeft reaches zero, release the predecessor node.
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000394///
395/// FIXME: Adjust PredSU height based on MinLatency.
Andrew Trick17d35e52012-03-14 04:00:41 +0000396void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
397 SUnit *PredSU = PredEdge->getSUnit();
398
Andrew Trickae692f22012-11-12 19:28:57 +0000399 if (PredEdge->isWeak()) {
400 --PredSU->WeakSuccsLeft;
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000401 if (PredEdge->isCluster())
402 NextClusterPred = PredSU;
Andrew Trickae692f22012-11-12 19:28:57 +0000403 return;
404 }
Andrew Trick17d35e52012-03-14 04:00:41 +0000405#ifndef NDEBUG
406 if (PredSU->NumSuccsLeft == 0) {
407 dbgs() << "*** Scheduling failed! ***\n";
408 PredSU->dump(this);
409 dbgs() << " has been released too many times!\n";
410 llvm_unreachable(0);
411 }
412#endif
413 --PredSU->NumSuccsLeft;
414 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
415 SchedImpl->releaseBottomNode(PredSU);
416}
417
418/// releasePredecessors - Call releasePred on each of SU's predecessors.
419void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
420 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
421 I != E; ++I) {
422 releasePred(SU, &*I);
423 }
424}
425
Andrew Trick4392f0f2013-04-13 06:07:40 +0000426/// This is normally called from the main scheduler loop but may also be invoked
427/// by the scheduling strategy to perform additional code motion.
Andrew Trick17d35e52012-03-14 04:00:41 +0000428void ScheduleDAGMI::moveInstruction(MachineInstr *MI,
429 MachineBasicBlock::iterator InsertPos) {
Andrew Trick811d92682012-05-17 18:35:03 +0000430 // Advance RegionBegin if the first instruction moves down.
Andrew Trick1ce062f2012-03-21 04:12:10 +0000431 if (&*RegionBegin == MI)
Andrew Trick811d92682012-05-17 18:35:03 +0000432 ++RegionBegin;
433
434 // Update the instruction stream.
Andrew Trick17d35e52012-03-14 04:00:41 +0000435 BB->splice(InsertPos, BB, MI);
Andrew Trick811d92682012-05-17 18:35:03 +0000436
437 // Update LiveIntervals
Andrew Trick27c28ce2012-10-16 00:22:51 +0000438 LIS->handleMove(MI, /*UpdateFlags=*/true);
Andrew Trick811d92682012-05-17 18:35:03 +0000439
440 // Recede RegionBegin if an instruction moves above the first.
Andrew Trick17d35e52012-03-14 04:00:41 +0000441 if (RegionBegin == InsertPos)
442 RegionBegin = MI;
443}
444
Andrew Trick0b0d8992012-03-21 04:12:07 +0000445bool ScheduleDAGMI::checkSchedLimit() {
446#ifndef NDEBUG
447 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
448 CurrentTop = CurrentBottom;
449 return false;
450 }
451 ++NumInstrsScheduled;
452#endif
453 return true;
454}
455
Andrew Trick006e1ab2012-04-24 17:56:43 +0000456/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
457/// crossing a scheduling boundary. [begin, end) includes all instructions in
458/// the region, including the boundary itself and single-instruction regions
459/// that don't get scheduled.
460void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
461 MachineBasicBlock::iterator begin,
462 MachineBasicBlock::iterator end,
Andrew Trickd2763f62013-08-23 17:48:33 +0000463 unsigned regioninstrs)
Andrew Trick006e1ab2012-04-24 17:56:43 +0000464{
Andrew Trickd2763f62013-08-23 17:48:33 +0000465 ScheduleDAGInstrs::enterRegion(bb, begin, end, regioninstrs);
Andrew Trick7f8ab782012-05-10 21:06:10 +0000466
467 // For convenience remember the end of the liveness region.
468 LiveRegionEnd =
469 (RegionEnd == bb->end()) ? RegionEnd : llvm::next(RegionEnd);
470}
471
472// Setup the register pressure trackers for the top scheduled top and bottom
473// scheduled regions.
474void ScheduleDAGMI::initRegPressure() {
475 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin);
476 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
477
478 // Close the RPTracker to finalize live ins.
479 RPTracker.closeRegion();
480
Andrew Trickd71efff2013-07-30 19:59:12 +0000481 DEBUG(RPTracker.dump());
Andrew Trickbb0a2422012-05-24 22:11:14 +0000482
Andrew Trick7f8ab782012-05-10 21:06:10 +0000483 // Initialize the live ins and live outs.
484 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
485 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
486
487 // Close one end of the tracker so we can call
488 // getMaxUpward/DownwardPressureDelta before advancing across any
489 // instructions. This converts currently live regs into live ins/outs.
490 TopRPTracker.closeTop();
491 BotRPTracker.closeBottom();
492
Andrew Trickd71efff2013-07-30 19:59:12 +0000493 BotRPTracker.initLiveThru(RPTracker);
494 if (!BotRPTracker.getLiveThru().empty()) {
495 TopRPTracker.initLiveThru(BotRPTracker.getLiveThru());
496 DEBUG(dbgs() << "Live Thru: ";
497 dumpRegSetPressure(BotRPTracker.getLiveThru(), TRI));
498 };
499
Andrew Trick663bd992013-08-30 04:36:57 +0000500 // For each live out vreg reduce the pressure change associated with other
501 // uses of the same vreg below the live-out reaching def.
502 updatePressureDiffs(RPTracker.getPressure().LiveOutRegs);
503
Andrew Trick7f8ab782012-05-10 21:06:10 +0000504 // Account for liveness generated by the region boundary.
Andrew Trick663bd992013-08-30 04:36:57 +0000505 if (LiveRegionEnd != RegionEnd) {
506 SmallVector<unsigned, 8> LiveUses;
507 BotRPTracker.recede(&LiveUses);
508 updatePressureDiffs(LiveUses);
509 }
Andrew Trick7f8ab782012-05-10 21:06:10 +0000510
511 assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000512
513 // Cache the list of excess pressure sets in this region. This will also track
514 // the max pressure in the scheduled code for these sets.
515 RegionCriticalPSets.clear();
Jakub Staszakb74564a2013-01-25 21:44:27 +0000516 const std::vector<unsigned> &RegionPressure =
517 RPTracker.getPressure().MaxSetPressure;
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000518 for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
Andrew Trick1f8b48a2013-06-21 18:32:58 +0000519 unsigned Limit = RegClassInfo->getRegPressureSetLimit(i);
Andrew Trick3bf23302013-06-21 18:33:01 +0000520 if (RegionPressure[i] > Limit) {
521 DEBUG(dbgs() << TRI->getRegPressureSetName(i)
522 << " Limit " << Limit
523 << " Actual " << RegionPressure[i] << "\n");
Andrew Trick4c60b8a2013-08-30 03:49:48 +0000524 RegionCriticalPSets.push_back(PressureChange(i));
Andrew Trick3bf23302013-06-21 18:33:01 +0000525 }
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000526 }
527 DEBUG(dbgs() << "Excess PSets: ";
528 for (unsigned i = 0, e = RegionCriticalPSets.size(); i != e; ++i)
529 dbgs() << TRI->getRegPressureSetName(
Andrew Trick4c60b8a2013-08-30 03:49:48 +0000530 RegionCriticalPSets[i].getPSet()) << " ";
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000531 dbgs() << "\n");
532}
533
534// FIXME: When the pressure tracker deals in pressure differences then we won't
535// iterate over all RegionCriticalPSets[i].
536void ScheduleDAGMI::
Jakub Staszakb717a502013-02-16 15:47:26 +0000537updateScheduledPressure(const std::vector<unsigned> &NewMaxPressure) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000538 for (unsigned i = 0, e = RegionCriticalPSets.size(); i < e; ++i) {
Andrew Trick4c60b8a2013-08-30 03:49:48 +0000539 unsigned ID = RegionCriticalPSets[i].getPSet();
540 if ((int)NewMaxPressure[ID] > RegionCriticalPSets[i].getUnitInc()
541 && NewMaxPressure[ID] <= INT16_MAX)
542 RegionCriticalPSets[i].setUnitInc(NewMaxPressure[ID]);
Andrew Trick73a0d8e2012-05-17 18:35:10 +0000543 }
Andrew Trick811a3722013-04-24 15:54:36 +0000544 DEBUG(
545 for (unsigned i = 0, e = NewMaxPressure.size(); i < e; ++i) {
Andrew Trick1f8b48a2013-06-21 18:32:58 +0000546 unsigned Limit = RegClassInfo->getRegPressureSetLimit(i);
Andrew Trick811a3722013-04-24 15:54:36 +0000547 if (NewMaxPressure[i] > Limit ) {
548 dbgs() << " " << TRI->getRegPressureSetName(i) << ": "
549 << NewMaxPressure[i] << " > " << Limit << "\n";
550 }
551 });
Andrew Trick006e1ab2012-04-24 17:56:43 +0000552}
553
Andrew Trick663bd992013-08-30 04:36:57 +0000554/// Update the PressureDiff array for liveness after scheduling this
555/// instruction.
556void ScheduleDAGMI::updatePressureDiffs(ArrayRef<unsigned> LiveUses) {
557 for (unsigned LUIdx = 0, LUEnd = LiveUses.size(); LUIdx != LUEnd; ++LUIdx) {
558 /// FIXME: Currently assuming single-use physregs.
559 unsigned Reg = LiveUses[LUIdx];
560 if (!TRI->isVirtualRegister(Reg))
561 continue;
562 // This may be called before CurrentBottom has been initialized. However,
563 // BotRPTracker must have a valid position. We want the value live into the
564 // instruction or live out of the block, so ask for the previous
565 // instruction's live-out.
566 const LiveInterval &LI = LIS->getInterval(Reg);
567 VNInfo *VNI;
568 if (BotRPTracker.getPos() == BB->end())
569 VNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
570 else {
571 LiveRangeQuery LRQ(LI, LIS->getInstructionIndex(BotRPTracker.getPos()));
572 VNI = LRQ.valueIn();
573 }
574 // RegisterPressureTracker guarantees that readsReg is true for LiveUses.
575 assert(VNI && "No live value at use.");
576 for (VReg2UseMap::iterator
577 UI = VRegUses.find(Reg); UI != VRegUses.end(); ++UI) {
578 SUnit *SU = UI->SU;
579 // If this use comes before the reaching def, it cannot be a last use, so
580 // descrease its pressure change.
581 if (!SU->isScheduled && SU != &ExitSU) {
582 LiveRangeQuery LRQ(LI, LIS->getInstructionIndex(SU->getInstr()));
583 if (LRQ.valueIn() == VNI)
584 getPressureDiff(SU).addPressureChange(Reg, true, &MRI);
585 }
586 }
587 }
588}
589
Andrew Trick17d35e52012-03-14 04:00:41 +0000590/// schedule - Called back from MachineScheduler::runOnMachineFunction
Andrew Trick006e1ab2012-04-24 17:56:43 +0000591/// after setting up the current scheduling region. [RegionBegin, RegionEnd)
592/// only includes instructions that have DAG nodes, not scheduling boundaries.
Andrew Trick78e5efe2012-09-11 00:39:15 +0000593///
594/// This is a skeletal driver, with all the functionality pushed into helpers,
595/// so that it can be easilly extended by experimental schedulers. Generally,
596/// implementing MachineSchedStrategy should be sufficient to implement a new
597/// scheduling algorithm. However, if a scheduler further subclasses
598/// ScheduleDAGMI then it will want to override this virtual method in order to
599/// update any specialized state.
Andrew Trick17d35e52012-03-14 04:00:41 +0000600void ScheduleDAGMI::schedule() {
Andrew Trick78e5efe2012-09-11 00:39:15 +0000601 buildDAGWithRegPressure();
602
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000603 Topo.InitDAGTopologicalSorting();
604
Andrew Trickd039b382012-09-14 17:22:42 +0000605 postprocessDAG();
606
Andrew Trick4e1fb182013-01-25 06:33:57 +0000607 SmallVector<SUnit*, 8> TopRoots, BotRoots;
608 findRootsAndBiasEdges(TopRoots, BotRoots);
609
610 // Initialize the strategy before modifying the DAG.
611 // This may initialize a DFSResult to be used for queue priority.
612 SchedImpl->initialize(this);
613
Andrew Trick78e5efe2012-09-11 00:39:15 +0000614 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
615 SUnits[su].dumpAll(this));
Andrew Trick4e1fb182013-01-25 06:33:57 +0000616 if (ViewMISchedDAGs) viewGraph();
Andrew Trick78e5efe2012-09-11 00:39:15 +0000617
Andrew Trick4e1fb182013-01-25 06:33:57 +0000618 // Initialize ready queues now that the DAG and priority data are finalized.
619 initQueues(TopRoots, BotRoots);
Andrew Trick78e5efe2012-09-11 00:39:15 +0000620
621 bool IsTopNode = false;
622 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
Andrew Trick30c6ec22012-10-08 18:53:53 +0000623 assert(!SU->isScheduled && "Node already scheduled");
Andrew Trick78e5efe2012-09-11 00:39:15 +0000624 if (!checkSchedLimit())
625 break;
626
627 scheduleMI(SU, IsTopNode);
628
629 updateQueues(SU, IsTopNode);
630 }
631 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
632
633 placeDebugValues();
Andrew Trick3b87f622012-11-07 07:05:09 +0000634
635 DEBUG({
Andrew Trickb4221042012-11-28 03:42:47 +0000636 unsigned BBNum = begin()->getParent()->getNumber();
Andrew Trick3b87f622012-11-07 07:05:09 +0000637 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
638 dumpSchedule();
639 dbgs() << '\n';
640 });
Andrew Trick78e5efe2012-09-11 00:39:15 +0000641}
642
643/// Build the DAG and setup three register pressure trackers.
644void ScheduleDAGMI::buildDAGWithRegPressure() {
Andrew Trick7f8ab782012-05-10 21:06:10 +0000645 // Initialize the register pressure tracker used by buildSchedGraph.
Andrew Trickd71efff2013-07-30 19:59:12 +0000646 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
647 /*TrackUntiedDefs=*/true);
Andrew Trick006e1ab2012-04-24 17:56:43 +0000648
Andrew Trick7f8ab782012-05-10 21:06:10 +0000649 // Account for liveness generate by the region boundary.
650 if (LiveRegionEnd != RegionEnd)
651 RPTracker.recede();
652
653 // Build the DAG, and compute current register pressure.
Andrew Trick4c60b8a2013-08-30 03:49:48 +0000654 buildSchedGraph(AA, &RPTracker, &SUPressureDiffs);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000655
Andrew Trick7f8ab782012-05-10 21:06:10 +0000656 // Initialize top/bottom trackers after computing region pressure.
657 initRegPressure();
Andrew Trick78e5efe2012-09-11 00:39:15 +0000658}
Andrew Trick7f8ab782012-05-10 21:06:10 +0000659
Andrew Trickd039b382012-09-14 17:22:42 +0000660/// Apply each ScheduleDAGMutation step in order.
661void ScheduleDAGMI::postprocessDAG() {
662 for (unsigned i = 0, e = Mutations.size(); i < e; ++i) {
663 Mutations[i]->apply(this);
664 }
665}
666
Andrew Trick4e1fb182013-01-25 06:33:57 +0000667void ScheduleDAGMI::computeDFSResult() {
Andrew Trick178f7d02013-01-25 04:01:04 +0000668 if (!DFSResult)
669 DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize);
670 DFSResult->clear();
Andrew Trick178f7d02013-01-25 04:01:04 +0000671 ScheduledTrees.clear();
Andrew Trick4e1fb182013-01-25 06:33:57 +0000672 DFSResult->resize(SUnits.size());
673 DFSResult->compute(SUnits);
Andrew Trick178f7d02013-01-25 04:01:04 +0000674 ScheduledTrees.resize(DFSResult->getNumSubtrees());
675}
676
Andrew Trick4e1fb182013-01-25 06:33:57 +0000677void ScheduleDAGMI::findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
678 SmallVectorImpl<SUnit*> &BotRoots) {
Andrew Trick1e94e982012-10-15 18:02:27 +0000679 for (std::vector<SUnit>::iterator
680 I = SUnits.begin(), E = SUnits.end(); I != E; ++I) {
Andrew Trickae692f22012-11-12 19:28:57 +0000681 SUnit *SU = &(*I);
Andrew Trick4c6a2ba2013-01-29 06:26:35 +0000682 assert(!SU->isBoundaryNode() && "Boundary node should not be in SUnits");
Andrew Trickdb417062013-01-24 02:09:57 +0000683
684 // Order predecessors so DFSResult follows the critical path.
685 SU->biasCriticalPath();
686
Andrew Trick1e94e982012-10-15 18:02:27 +0000687 // A SUnit is ready to top schedule if it has no predecessors.
Andrew Trick4c6a2ba2013-01-29 06:26:35 +0000688 if (!I->NumPredsLeft)
Andrew Trick4e1fb182013-01-25 06:33:57 +0000689 TopRoots.push_back(SU);
Andrew Trick1e94e982012-10-15 18:02:27 +0000690 // A SUnit is ready to bottom schedule if it has no successors.
Andrew Trick4c6a2ba2013-01-29 06:26:35 +0000691 if (!I->NumSuccsLeft)
Andrew Trickae692f22012-11-12 19:28:57 +0000692 BotRoots.push_back(SU);
Andrew Trick1e94e982012-10-15 18:02:27 +0000693 }
Andrew Trick4c6a2ba2013-01-29 06:26:35 +0000694 ExitSU.biasCriticalPath();
Andrew Trick1e94e982012-10-15 18:02:27 +0000695}
696
Andrew Trick851bb2c2013-08-29 18:04:49 +0000697/// Compute the max cyclic critical path through the DAG. The scheduling DAG
698/// only provides the critical path for single block loops. To handle loops that
699/// span blocks, we could use the vreg path latencies provided by
700/// MachineTraceMetrics instead. However, MachineTraceMetrics is not currently
701/// available for use in the scheduler.
702///
703/// The cyclic path estimation identifies a def-use pair that crosses the back
Andrew Trick6dc6a892013-08-30 02:02:12 +0000704/// edge and considers the depth and height of the nodes. For example, consider
Andrew Trick851bb2c2013-08-29 18:04:49 +0000705/// the following instruction sequence where each instruction has unit latency
706/// and defines an epomymous virtual register:
707///
708/// a->b(a,c)->c(b)->d(c)->exit
709///
710/// The cyclic critical path is a two cycles: b->c->b
711/// The acyclic critical path is four cycles: a->b->c->d->exit
712/// LiveOutHeight = height(c) = len(c->d->exit) = 2
713/// LiveOutDepth = depth(c) + 1 = len(a->b->c) + 1 = 3
714/// LiveInHeight = height(b) + 1 = len(b->c->d->exit) + 1 = 4
715/// LiveInDepth = depth(b) = len(a->b) = 1
716///
717/// LiveOutDepth - LiveInDepth = 3 - 1 = 2
718/// LiveInHeight - LiveOutHeight = 4 - 2 = 2
719/// CyclicCriticalPath = min(2, 2) = 2
720unsigned ScheduleDAGMI::computeCyclicCriticalPath() {
721 // This only applies to single block loop.
722 if (!BB->isSuccessor(BB))
723 return 0;
724
725 unsigned MaxCyclicLatency = 0;
726 // Visit each live out vreg def to find def/use pairs that cross iterations.
727 ArrayRef<unsigned> LiveOuts = RPTracker.getPressure().LiveOutRegs;
728 for (ArrayRef<unsigned>::iterator RI = LiveOuts.begin(), RE = LiveOuts.end();
729 RI != RE; ++RI) {
730 unsigned Reg = *RI;
731 if (!TRI->isVirtualRegister(Reg))
732 continue;
733 const LiveInterval &LI = LIS->getInterval(Reg);
734 const VNInfo *DefVNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
735 if (!DefVNI)
736 continue;
737
738 MachineInstr *DefMI = LIS->getInstructionFromIndex(DefVNI->def);
739 const SUnit *DefSU = getSUnit(DefMI);
740 if (!DefSU)
741 continue;
742
743 unsigned LiveOutHeight = DefSU->getHeight();
744 unsigned LiveOutDepth = DefSU->getDepth() + DefSU->Latency;
745 // Visit all local users of the vreg def.
746 for (VReg2UseMap::iterator
747 UI = VRegUses.find(Reg); UI != VRegUses.end(); ++UI) {
748 if (UI->SU == &ExitSU)
749 continue;
750
751 // Only consider uses of the phi.
752 LiveRangeQuery LRQ(LI, LIS->getInstructionIndex(UI->SU->getInstr()));
753 if (!LRQ.valueIn()->isPHIDef())
754 continue;
755
756 // Assume that a path spanning two iterations is a cycle, which could
757 // overestimate in strange cases. This allows cyclic latency to be
758 // estimated as the minimum slack of the vreg's depth or height.
759 unsigned CyclicLatency = 0;
760 if (LiveOutDepth > UI->SU->getDepth())
761 CyclicLatency = LiveOutDepth - UI->SU->getDepth();
762
763 unsigned LiveInHeight = UI->SU->getHeight() + DefSU->Latency;
764 if (LiveInHeight > LiveOutHeight) {
765 if (LiveInHeight - LiveOutHeight < CyclicLatency)
766 CyclicLatency = LiveInHeight - LiveOutHeight;
767 }
768 else
769 CyclicLatency = 0;
770
771 DEBUG(dbgs() << "Cyclic Path: SU(" << DefSU->NodeNum << ") -> SU("
772 << UI->SU->NodeNum << ") = " << CyclicLatency << "c\n");
773 if (CyclicLatency > MaxCyclicLatency)
774 MaxCyclicLatency = CyclicLatency;
775 }
776 }
777 DEBUG(dbgs() << "Cyclic Critical Path: " << MaxCyclicLatency << "c\n");
778 return MaxCyclicLatency;
779}
780
Andrew Trick78e5efe2012-09-11 00:39:15 +0000781/// Identify DAG roots and setup scheduler queues.
Andrew Trick4e1fb182013-01-25 06:33:57 +0000782void ScheduleDAGMI::initQueues(ArrayRef<SUnit*> TopRoots,
783 ArrayRef<SUnit*> BotRoots) {
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000784 NextClusterSucc = NULL;
785 NextClusterPred = NULL;
Andrew Trick1e94e982012-10-15 18:02:27 +0000786
Andrew Trickae692f22012-11-12 19:28:57 +0000787 // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
Andrew Trick4e1fb182013-01-25 06:33:57 +0000788 //
789 // Nodes with unreleased weak edges can still be roots.
790 // Release top roots in forward order.
791 for (SmallVectorImpl<SUnit*>::const_iterator
792 I = TopRoots.begin(), E = TopRoots.end(); I != E; ++I) {
793 SchedImpl->releaseTopNode(*I);
794 }
795 // Release bottom roots in reverse order so the higher priority nodes appear
796 // first. This is more natural and slightly more efficient.
797 for (SmallVectorImpl<SUnit*>::const_reverse_iterator
798 I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I) {
799 SchedImpl->releaseBottomNode(*I);
800 }
Andrew Trickae692f22012-11-12 19:28:57 +0000801
Andrew Trickc174eaf2012-03-08 01:41:12 +0000802 releaseSuccessors(&EntrySU);
Andrew Trick17d35e52012-03-14 04:00:41 +0000803 releasePredecessors(&ExitSU);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000804
Andrew Trick1e94e982012-10-15 18:02:27 +0000805 SchedImpl->registerRoots();
806
Andrew Trick657b75b2012-12-01 01:22:49 +0000807 // Advance past initial DebugValues.
808 assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000809 CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
Andrew Trick657b75b2012-12-01 01:22:49 +0000810 TopRPTracker.setPos(CurrentTop);
811
Andrew Trick17d35e52012-03-14 04:00:41 +0000812 CurrentBottom = RegionEnd;
Andrew Trick78e5efe2012-09-11 00:39:15 +0000813}
Andrew Trickc174eaf2012-03-08 01:41:12 +0000814
Andrew Trick78e5efe2012-09-11 00:39:15 +0000815/// Move an instruction and update register pressure.
816void ScheduleDAGMI::scheduleMI(SUnit *SU, bool IsTopNode) {
817 // Move the instruction to its new location in the instruction stream.
818 MachineInstr *MI = SU->getInstr();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000819
Andrew Trick78e5efe2012-09-11 00:39:15 +0000820 if (IsTopNode) {
821 assert(SU->isTopReady() && "node still has unscheduled dependencies");
822 if (&*CurrentTop == MI)
823 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
Andrew Trick17d35e52012-03-14 04:00:41 +0000824 else {
Andrew Trick78e5efe2012-09-11 00:39:15 +0000825 moveInstruction(MI, CurrentTop);
826 TopRPTracker.setPos(MI);
Andrew Trick17d35e52012-03-14 04:00:41 +0000827 }
Andrew Trick000b2502012-04-24 18:04:37 +0000828
Andrew Trick78e5efe2012-09-11 00:39:15 +0000829 // Update top scheduled pressure.
830 TopRPTracker.advance();
831 assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
832 updateScheduledPressure(TopRPTracker.getPressure().MaxSetPressure);
833 }
834 else {
835 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
836 MachineBasicBlock::iterator priorII =
837 priorNonDebug(CurrentBottom, CurrentTop);
838 if (&*priorII == MI)
839 CurrentBottom = priorII;
840 else {
841 if (&*CurrentTop == MI) {
842 CurrentTop = nextIfDebug(++CurrentTop, priorII);
843 TopRPTracker.setPos(CurrentTop);
844 }
845 moveInstruction(MI, CurrentBottom);
846 CurrentBottom = MI;
847 }
848 // Update bottom scheduled pressure.
Andrew Trick663bd992013-08-30 04:36:57 +0000849 SmallVector<unsigned, 8> LiveUses;
850 BotRPTracker.recede(&LiveUses);
Andrew Trick78e5efe2012-09-11 00:39:15 +0000851 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
Andrew Trick663bd992013-08-30 04:36:57 +0000852 updatePressureDiffs(LiveUses);
Andrew Trick78e5efe2012-09-11 00:39:15 +0000853 updateScheduledPressure(BotRPTracker.getPressure().MaxSetPressure);
854 }
855}
856
857/// Update scheduler queues after scheduling an instruction.
858void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
859 // Release dependent instructions for scheduling.
860 if (IsTopNode)
861 releaseSuccessors(SU);
862 else
863 releasePredecessors(SU);
864
865 SU->isScheduled = true;
866
Andrew Trick178f7d02013-01-25 04:01:04 +0000867 if (DFSResult) {
868 unsigned SubtreeID = DFSResult->getSubtreeID(SU);
869 if (!ScheduledTrees.test(SubtreeID)) {
870 ScheduledTrees.set(SubtreeID);
871 DFSResult->scheduleTree(SubtreeID);
872 SchedImpl->scheduleTree(SubtreeID);
873 }
874 }
875
Andrew Trick78e5efe2012-09-11 00:39:15 +0000876 // Notify the scheduling strategy after updating the DAG.
877 SchedImpl->schedNode(SU, IsTopNode);
Andrew Trick000b2502012-04-24 18:04:37 +0000878}
879
880/// Reinsert any remaining debug_values, just like the PostRA scheduler.
881void ScheduleDAGMI::placeDebugValues() {
882 // If first instruction was a DBG_VALUE then put it back.
883 if (FirstDbgValue) {
884 BB->splice(RegionBegin, BB, FirstDbgValue);
885 RegionBegin = FirstDbgValue;
886 }
887
888 for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
889 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
890 std::pair<MachineInstr *, MachineInstr *> P = *prior(DI);
891 MachineInstr *DbgValue = P.first;
892 MachineBasicBlock::iterator OrigPrevMI = P.second;
Andrew Trick67bdd422012-12-01 01:22:38 +0000893 if (&*RegionBegin == DbgValue)
894 ++RegionBegin;
Andrew Trick000b2502012-04-24 18:04:37 +0000895 BB->splice(++OrigPrevMI, BB, DbgValue);
896 if (OrigPrevMI == llvm::prior(RegionEnd))
897 RegionEnd = DbgValue;
898 }
899 DbgValues.clear();
900 FirstDbgValue = NULL;
Andrew Trickc174eaf2012-03-08 01:41:12 +0000901}
902
Andrew Trick3b87f622012-11-07 07:05:09 +0000903#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
904void ScheduleDAGMI::dumpSchedule() const {
905 for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
906 if (SUnit *SU = getSUnit(&(*MI)))
907 SU->dump(this);
908 else
909 dbgs() << "Missing SUnit\n";
910 }
911}
912#endif
913
Andrew Trick6996fd02012-11-12 19:52:20 +0000914//===----------------------------------------------------------------------===//
915// LoadClusterMutation - DAG post-processing to cluster loads.
916//===----------------------------------------------------------------------===//
917
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000918namespace {
919/// \brief Post-process the DAG to create cluster edges between neighboring
920/// loads.
921class LoadClusterMutation : public ScheduleDAGMutation {
922 struct LoadInfo {
923 SUnit *SU;
924 unsigned BaseReg;
925 unsigned Offset;
926 LoadInfo(SUnit *su, unsigned reg, unsigned ofs)
927 : SU(su), BaseReg(reg), Offset(ofs) {}
928 };
929 static bool LoadInfoLess(const LoadClusterMutation::LoadInfo &LHS,
930 const LoadClusterMutation::LoadInfo &RHS);
931
932 const TargetInstrInfo *TII;
933 const TargetRegisterInfo *TRI;
934public:
935 LoadClusterMutation(const TargetInstrInfo *tii,
936 const TargetRegisterInfo *tri)
937 : TII(tii), TRI(tri) {}
938
939 virtual void apply(ScheduleDAGMI *DAG);
940protected:
941 void clusterNeighboringLoads(ArrayRef<SUnit*> Loads, ScheduleDAGMI *DAG);
942};
943} // anonymous
944
945bool LoadClusterMutation::LoadInfoLess(
946 const LoadClusterMutation::LoadInfo &LHS,
947 const LoadClusterMutation::LoadInfo &RHS) {
948 if (LHS.BaseReg != RHS.BaseReg)
949 return LHS.BaseReg < RHS.BaseReg;
950 return LHS.Offset < RHS.Offset;
951}
952
953void LoadClusterMutation::clusterNeighboringLoads(ArrayRef<SUnit*> Loads,
954 ScheduleDAGMI *DAG) {
955 SmallVector<LoadClusterMutation::LoadInfo,32> LoadRecords;
956 for (unsigned Idx = 0, End = Loads.size(); Idx != End; ++Idx) {
957 SUnit *SU = Loads[Idx];
958 unsigned BaseReg;
959 unsigned Offset;
960 if (TII->getLdStBaseRegImmOfs(SU->getInstr(), BaseReg, Offset, TRI))
961 LoadRecords.push_back(LoadInfo(SU, BaseReg, Offset));
962 }
963 if (LoadRecords.size() < 2)
964 return;
965 std::sort(LoadRecords.begin(), LoadRecords.end(), LoadInfoLess);
966 unsigned ClusterLength = 1;
967 for (unsigned Idx = 0, End = LoadRecords.size(); Idx < (End - 1); ++Idx) {
968 if (LoadRecords[Idx].BaseReg != LoadRecords[Idx+1].BaseReg) {
969 ClusterLength = 1;
970 continue;
971 }
972
973 SUnit *SUa = LoadRecords[Idx].SU;
974 SUnit *SUb = LoadRecords[Idx+1].SU;
Andrew Tricka7d2d562012-11-12 21:28:10 +0000975 if (TII->shouldClusterLoads(SUa->getInstr(), SUb->getInstr(), ClusterLength)
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000976 && DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
977
978 DEBUG(dbgs() << "Cluster loads SU(" << SUa->NodeNum << ") - SU("
979 << SUb->NodeNum << ")\n");
980 // Copy successor edges from SUa to SUb. Interleaving computation
981 // dependent on SUa can prevent load combining due to register reuse.
982 // Predecessor edges do not need to be copied from SUb to SUa since nearby
983 // loads should have effectively the same inputs.
984 for (SUnit::const_succ_iterator
985 SI = SUa->Succs.begin(), SE = SUa->Succs.end(); SI != SE; ++SI) {
986 if (SI->getSUnit() == SUb)
987 continue;
988 DEBUG(dbgs() << " Copy Succ SU(" << SI->getSUnit()->NodeNum << ")\n");
989 DAG->addEdge(SI->getSUnit(), SDep(SUb, SDep::Artificial));
990 }
991 ++ClusterLength;
992 }
993 else
994 ClusterLength = 1;
995 }
996}
997
998/// \brief Callback from DAG postProcessing to create cluster edges for loads.
999void LoadClusterMutation::apply(ScheduleDAGMI *DAG) {
1000 // Map DAG NodeNum to store chain ID.
1001 DenseMap<unsigned, unsigned> StoreChainIDs;
1002 // Map each store chain to a set of dependent loads.
1003 SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
1004 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
1005 SUnit *SU = &DAG->SUnits[Idx];
1006 if (!SU->getInstr()->mayLoad())
1007 continue;
1008 unsigned ChainPredID = DAG->SUnits.size();
1009 for (SUnit::const_pred_iterator
1010 PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
1011 if (PI->isCtrl()) {
1012 ChainPredID = PI->getSUnit()->NodeNum;
1013 break;
1014 }
1015 }
1016 // Check if this chain-like pred has been seen
1017 // before. ChainPredID==MaxNodeID for loads at the top of the schedule.
1018 unsigned NumChains = StoreChainDependents.size();
1019 std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
1020 StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
1021 if (Result.second)
1022 StoreChainDependents.resize(NumChains + 1);
1023 StoreChainDependents[Result.first->second].push_back(SU);
1024 }
1025 // Iterate over the store chains.
1026 for (unsigned Idx = 0, End = StoreChainDependents.size(); Idx != End; ++Idx)
1027 clusterNeighboringLoads(StoreChainDependents[Idx], DAG);
1028}
1029
Andrew Trickc174eaf2012-03-08 01:41:12 +00001030//===----------------------------------------------------------------------===//
Andrew Trick6996fd02012-11-12 19:52:20 +00001031// MacroFusion - DAG post-processing to encourage fusion of macro ops.
1032//===----------------------------------------------------------------------===//
1033
1034namespace {
1035/// \brief Post-process the DAG to create cluster edges between instructions
1036/// that may be fused by the processor into a single operation.
1037class MacroFusion : public ScheduleDAGMutation {
1038 const TargetInstrInfo *TII;
1039public:
1040 MacroFusion(const TargetInstrInfo *tii): TII(tii) {}
1041
1042 virtual void apply(ScheduleDAGMI *DAG);
1043};
1044} // anonymous
1045
1046/// \brief Callback from DAG postProcessing to create cluster edges to encourage
1047/// fused operations.
1048void MacroFusion::apply(ScheduleDAGMI *DAG) {
1049 // For now, assume targets can only fuse with the branch.
1050 MachineInstr *Branch = DAG->ExitSU.getInstr();
1051 if (!Branch)
1052 return;
1053
1054 for (unsigned Idx = DAG->SUnits.size(); Idx > 0;) {
1055 SUnit *SU = &DAG->SUnits[--Idx];
1056 if (!TII->shouldScheduleAdjacent(SU->getInstr(), Branch))
1057 continue;
1058
1059 // Create a single weak edge from SU to ExitSU. The only effect is to cause
1060 // bottom-up scheduling to heavily prioritize the clustered SU. There is no
1061 // need to copy predecessor edges from ExitSU to SU, since top-down
1062 // scheduling cannot prioritize ExitSU anyway. To defer top-down scheduling
1063 // of SU, we could create an artificial edge from the deepest root, but it
1064 // hasn't been needed yet.
1065 bool Success = DAG->addEdge(&DAG->ExitSU, SDep(SU, SDep::Cluster));
1066 (void)Success;
1067 assert(Success && "No DAG nodes should be reachable from ExitSU");
1068
1069 DEBUG(dbgs() << "Macro Fuse SU(" << SU->NodeNum << ")\n");
1070 break;
1071 }
1072}
1073
1074//===----------------------------------------------------------------------===//
Andrew Tricke38afe12013-04-24 15:54:43 +00001075// CopyConstrain - DAG post-processing to encourage copy elimination.
1076//===----------------------------------------------------------------------===//
1077
1078namespace {
1079/// \brief Post-process the DAG to create weak edges from all uses of a copy to
1080/// the one use that defines the copy's source vreg, most likely an induction
1081/// variable increment.
1082class CopyConstrain : public ScheduleDAGMutation {
1083 // Transient state.
1084 SlotIndex RegionBeginIdx;
Andrew Tricka264a202013-04-24 23:19:56 +00001085 // RegionEndIdx is the slot index of the last non-debug instruction in the
1086 // scheduling region. So we may have RegionBeginIdx == RegionEndIdx.
Andrew Tricke38afe12013-04-24 15:54:43 +00001087 SlotIndex RegionEndIdx;
1088public:
1089 CopyConstrain(const TargetInstrInfo *, const TargetRegisterInfo *) {}
1090
1091 virtual void apply(ScheduleDAGMI *DAG);
1092
1093protected:
1094 void constrainLocalCopy(SUnit *CopySU, ScheduleDAGMI *DAG);
1095};
1096} // anonymous
1097
1098/// constrainLocalCopy handles two possibilities:
1099/// 1) Local src:
1100/// I0: = dst
1101/// I1: src = ...
1102/// I2: = dst
1103/// I3: dst = src (copy)
1104/// (create pred->succ edges I0->I1, I2->I1)
1105///
1106/// 2) Local copy:
1107/// I0: dst = src (copy)
1108/// I1: = dst
1109/// I2: src = ...
1110/// I3: = dst
1111/// (create pred->succ edges I1->I2, I3->I2)
1112///
1113/// Although the MachineScheduler is currently constrained to single blocks,
1114/// this algorithm should handle extended blocks. An EBB is a set of
1115/// contiguously numbered blocks such that the previous block in the EBB is
1116/// always the single predecessor.
1117void CopyConstrain::constrainLocalCopy(SUnit *CopySU, ScheduleDAGMI *DAG) {
1118 LiveIntervals *LIS = DAG->getLIS();
1119 MachineInstr *Copy = CopySU->getInstr();
1120
1121 // Check for pure vreg copies.
1122 unsigned SrcReg = Copy->getOperand(1).getReg();
1123 if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
1124 return;
1125
1126 unsigned DstReg = Copy->getOperand(0).getReg();
1127 if (!TargetRegisterInfo::isVirtualRegister(DstReg))
1128 return;
1129
1130 // Check if either the dest or source is local. If it's live across a back
1131 // edge, it's not local. Note that if both vregs are live across the back
1132 // edge, we cannot successfully contrain the copy without cyclic scheduling.
1133 unsigned LocalReg = DstReg;
1134 unsigned GlobalReg = SrcReg;
1135 LiveInterval *LocalLI = &LIS->getInterval(LocalReg);
1136 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx)) {
1137 LocalReg = SrcReg;
1138 GlobalReg = DstReg;
1139 LocalLI = &LIS->getInterval(LocalReg);
1140 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx))
1141 return;
1142 }
1143 LiveInterval *GlobalLI = &LIS->getInterval(GlobalReg);
1144
1145 // Find the global segment after the start of the local LI.
1146 LiveInterval::iterator GlobalSegment = GlobalLI->find(LocalLI->beginIndex());
1147 // If GlobalLI does not overlap LocalLI->start, then a copy directly feeds a
1148 // local live range. We could create edges from other global uses to the local
1149 // start, but the coalescer should have already eliminated these cases, so
1150 // don't bother dealing with it.
1151 if (GlobalSegment == GlobalLI->end())
1152 return;
1153
1154 // If GlobalSegment is killed at the LocalLI->start, the call to find()
1155 // returned the next global segment. But if GlobalSegment overlaps with
1156 // LocalLI->start, then advance to the next segement. If a hole in GlobalLI
1157 // exists in LocalLI's vicinity, GlobalSegment will be the end of the hole.
1158 if (GlobalSegment->contains(LocalLI->beginIndex()))
1159 ++GlobalSegment;
1160
1161 if (GlobalSegment == GlobalLI->end())
1162 return;
1163
1164 // Check if GlobalLI contains a hole in the vicinity of LocalLI.
1165 if (GlobalSegment != GlobalLI->begin()) {
1166 // Two address defs have no hole.
1167 if (SlotIndex::isSameInstr(llvm::prior(GlobalSegment)->end,
1168 GlobalSegment->start)) {
1169 return;
1170 }
Andrew Trick1e46fcd2013-07-30 19:59:08 +00001171 // If the prior global segment may be defined by the same two-address
1172 // instruction that also defines LocalLI, then can't make a hole here.
1173 if (SlotIndex::isSameInstr(llvm::prior(GlobalSegment)->start,
1174 LocalLI->beginIndex())) {
1175 return;
1176 }
Andrew Tricke38afe12013-04-24 15:54:43 +00001177 // If GlobalLI has a prior segment, it must be live into the EBB. Otherwise
1178 // it would be a disconnected component in the live range.
1179 assert(llvm::prior(GlobalSegment)->start < LocalLI->beginIndex() &&
1180 "Disconnected LRG within the scheduling region.");
1181 }
1182 MachineInstr *GlobalDef = LIS->getInstructionFromIndex(GlobalSegment->start);
1183 if (!GlobalDef)
1184 return;
1185
1186 SUnit *GlobalSU = DAG->getSUnit(GlobalDef);
1187 if (!GlobalSU)
1188 return;
1189
1190 // GlobalDef is the bottom of the GlobalLI hole. Open the hole by
1191 // constraining the uses of the last local def to precede GlobalDef.
1192 SmallVector<SUnit*,8> LocalUses;
1193 const VNInfo *LastLocalVN = LocalLI->getVNInfoBefore(LocalLI->endIndex());
1194 MachineInstr *LastLocalDef = LIS->getInstructionFromIndex(LastLocalVN->def);
1195 SUnit *LastLocalSU = DAG->getSUnit(LastLocalDef);
1196 for (SUnit::const_succ_iterator
1197 I = LastLocalSU->Succs.begin(), E = LastLocalSU->Succs.end();
1198 I != E; ++I) {
1199 if (I->getKind() != SDep::Data || I->getReg() != LocalReg)
1200 continue;
1201 if (I->getSUnit() == GlobalSU)
1202 continue;
1203 if (!DAG->canAddEdge(GlobalSU, I->getSUnit()))
1204 return;
1205 LocalUses.push_back(I->getSUnit());
1206 }
1207 // Open the top of the GlobalLI hole by constraining any earlier global uses
1208 // to precede the start of LocalLI.
1209 SmallVector<SUnit*,8> GlobalUses;
1210 MachineInstr *FirstLocalDef =
1211 LIS->getInstructionFromIndex(LocalLI->beginIndex());
1212 SUnit *FirstLocalSU = DAG->getSUnit(FirstLocalDef);
1213 for (SUnit::const_pred_iterator
1214 I = GlobalSU->Preds.begin(), E = GlobalSU->Preds.end(); I != E; ++I) {
1215 if (I->getKind() != SDep::Anti || I->getReg() != GlobalReg)
1216 continue;
1217 if (I->getSUnit() == FirstLocalSU)
1218 continue;
1219 if (!DAG->canAddEdge(FirstLocalSU, I->getSUnit()))
1220 return;
1221 GlobalUses.push_back(I->getSUnit());
1222 }
1223 DEBUG(dbgs() << "Constraining copy SU(" << CopySU->NodeNum << ")\n");
1224 // Add the weak edges.
1225 for (SmallVectorImpl<SUnit*>::const_iterator
1226 I = LocalUses.begin(), E = LocalUses.end(); I != E; ++I) {
1227 DEBUG(dbgs() << " Local use SU(" << (*I)->NodeNum << ") -> SU("
1228 << GlobalSU->NodeNum << ")\n");
1229 DAG->addEdge(GlobalSU, SDep(*I, SDep::Weak));
1230 }
1231 for (SmallVectorImpl<SUnit*>::const_iterator
1232 I = GlobalUses.begin(), E = GlobalUses.end(); I != E; ++I) {
1233 DEBUG(dbgs() << " Global use SU(" << (*I)->NodeNum << ") -> SU("
1234 << FirstLocalSU->NodeNum << ")\n");
1235 DAG->addEdge(FirstLocalSU, SDep(*I, SDep::Weak));
1236 }
1237}
1238
1239/// \brief Callback from DAG postProcessing to create weak edges to encourage
1240/// copy elimination.
1241void CopyConstrain::apply(ScheduleDAGMI *DAG) {
Andrew Tricka264a202013-04-24 23:19:56 +00001242 MachineBasicBlock::iterator FirstPos = nextIfDebug(DAG->begin(), DAG->end());
1243 if (FirstPos == DAG->end())
1244 return;
1245 RegionBeginIdx = DAG->getLIS()->getInstructionIndex(&*FirstPos);
Andrew Tricke38afe12013-04-24 15:54:43 +00001246 RegionEndIdx = DAG->getLIS()->getInstructionIndex(
1247 &*priorNonDebug(DAG->end(), DAG->begin()));
1248
1249 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
1250 SUnit *SU = &DAG->SUnits[Idx];
1251 if (!SU->getInstr()->isCopy())
1252 continue;
1253
1254 constrainLocalCopy(SU, DAG);
1255 }
1256}
1257
1258//===----------------------------------------------------------------------===//
Andrew Trickfa989e72013-06-15 05:39:19 +00001259// ConvergingScheduler - Implementation of the generic MachineSchedStrategy.
Andrew Trick42b7a712012-01-17 06:55:03 +00001260//===----------------------------------------------------------------------===//
1261
1262namespace {
Andrew Trick17d35e52012-03-14 04:00:41 +00001263/// ConvergingScheduler shrinks the unscheduled zone using heuristics to balance
1264/// the schedule.
1265class ConvergingScheduler : public MachineSchedStrategy {
Andrew Trick3b87f622012-11-07 07:05:09 +00001266public:
1267 /// Represent the type of SchedCandidate found within a single queue.
1268 /// pickNodeBidirectional depends on these listed by decreasing priority.
1269 enum CandReason {
Andrew Tricka626f502013-06-17 21:45:13 +00001270 NoCand, PhysRegCopy, RegExcess, RegCritical, Cluster, Weak, RegMax,
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001271 ResourceReduce, ResourceDemand, BotHeightReduce, BotPathReduce,
Andrew Tricka626f502013-06-17 21:45:13 +00001272 TopDepthReduce, TopPathReduce, NextDefUse, NodeOrder};
Andrew Trick3b87f622012-11-07 07:05:09 +00001273
1274#ifndef NDEBUG
1275 static const char *getReasonStr(ConvergingScheduler::CandReason Reason);
1276#endif
1277
1278 /// Policy for scheduling the next instruction in the candidate's zone.
1279 struct CandPolicy {
1280 bool ReduceLatency;
1281 unsigned ReduceResIdx;
1282 unsigned DemandResIdx;
1283
1284 CandPolicy(): ReduceLatency(false), ReduceResIdx(0), DemandResIdx(0) {}
1285 };
1286
1287 /// Status of an instruction's critical resource consumption.
1288 struct SchedResourceDelta {
1289 // Count critical resources in the scheduled region required by SU.
1290 unsigned CritResources;
1291
1292 // Count critical resources from another region consumed by SU.
1293 unsigned DemandedResources;
1294
1295 SchedResourceDelta(): CritResources(0), DemandedResources(0) {}
1296
1297 bool operator==(const SchedResourceDelta &RHS) const {
1298 return CritResources == RHS.CritResources
1299 && DemandedResources == RHS.DemandedResources;
1300 }
1301 bool operator!=(const SchedResourceDelta &RHS) const {
1302 return !operator==(RHS);
1303 }
1304 };
Andrew Trick7196a8f2012-05-10 21:06:16 +00001305
1306 /// Store the state used by ConvergingScheduler heuristics, required for the
1307 /// lifetime of one invocation of pickNode().
1308 struct SchedCandidate {
Andrew Trick3b87f622012-11-07 07:05:09 +00001309 CandPolicy Policy;
1310
Andrew Trick7196a8f2012-05-10 21:06:16 +00001311 // The best SUnit candidate.
1312 SUnit *SU;
1313
Andrew Trick3b87f622012-11-07 07:05:09 +00001314 // The reason for this candidate.
1315 CandReason Reason;
1316
Andrew Tricke52d5022013-06-17 21:45:05 +00001317 // Set of reasons that apply to multiple candidates.
1318 uint32_t RepeatReasonSet;
1319
Andrew Trick7196a8f2012-05-10 21:06:16 +00001320 // Register pressure values for the best candidate.
1321 RegPressureDelta RPDelta;
1322
Andrew Trick3b87f622012-11-07 07:05:09 +00001323 // Critical resource consumption of the best candidate.
1324 SchedResourceDelta ResDelta;
1325
1326 SchedCandidate(const CandPolicy &policy)
Andrew Tricke52d5022013-06-17 21:45:05 +00001327 : Policy(policy), SU(NULL), Reason(NoCand), RepeatReasonSet(0) {}
Andrew Trick3b87f622012-11-07 07:05:09 +00001328
1329 bool isValid() const { return SU; }
1330
1331 // Copy the status of another candidate without changing policy.
1332 void setBest(SchedCandidate &Best) {
1333 assert(Best.Reason != NoCand && "uninitialized Sched candidate");
1334 SU = Best.SU;
1335 Reason = Best.Reason;
1336 RPDelta = Best.RPDelta;
1337 ResDelta = Best.ResDelta;
1338 }
1339
Andrew Tricke52d5022013-06-17 21:45:05 +00001340 bool isRepeat(CandReason R) { return RepeatReasonSet & (1 << R); }
1341 void setRepeat(CandReason R) { RepeatReasonSet |= (1 << R); }
1342
Andrew Trick3b87f622012-11-07 07:05:09 +00001343 void initResourceDelta(const ScheduleDAGMI *DAG,
1344 const TargetSchedModel *SchedModel);
Andrew Trick7196a8f2012-05-10 21:06:16 +00001345 };
Andrew Trick3b87f622012-11-07 07:05:09 +00001346
1347 /// Summarize the unscheduled region.
1348 struct SchedRemainder {
1349 // Critical path through the DAG in expected latency.
1350 unsigned CriticalPath;
Andrew Trickea574332013-08-23 17:48:43 +00001351 unsigned CyclicCritPath;
Andrew Trick3b87f622012-11-07 07:05:09 +00001352
Andrew Trickfa989e72013-06-15 05:39:19 +00001353 // Scaled count of micro-ops left to schedule.
1354 unsigned RemIssueCount;
1355
Andrew Trickea574332013-08-23 17:48:43 +00001356 bool IsAcyclicLatencyLimited;
1357
Andrew Trick3b87f622012-11-07 07:05:09 +00001358 // Unscheduled resources
1359 SmallVector<unsigned, 16> RemainingCounts;
Andrew Trick3b87f622012-11-07 07:05:09 +00001360
Andrew Trick3b87f622012-11-07 07:05:09 +00001361 void reset() {
1362 CriticalPath = 0;
Andrew Trickea574332013-08-23 17:48:43 +00001363 CyclicCritPath = 0;
Andrew Trickfa989e72013-06-15 05:39:19 +00001364 RemIssueCount = 0;
Andrew Trickea574332013-08-23 17:48:43 +00001365 IsAcyclicLatencyLimited = false;
Andrew Trick3b87f622012-11-07 07:05:09 +00001366 RemainingCounts.clear();
Andrew Trick3b87f622012-11-07 07:05:09 +00001367 }
1368
1369 SchedRemainder() { reset(); }
1370
1371 void init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel);
1372 };
Andrew Trick7196a8f2012-05-10 21:06:16 +00001373
Andrew Trickf3234242012-05-24 22:11:12 +00001374 /// Each Scheduling boundary is associated with ready queues. It tracks the
Andrew Trick3b87f622012-11-07 07:05:09 +00001375 /// current cycle in the direction of movement, and maintains the state
Andrew Trickf3234242012-05-24 22:11:12 +00001376 /// of "hazards" and other interlocks at the current cycle.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001377 struct SchedBoundary {
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001378 ScheduleDAGMI *DAG;
Andrew Trick412cd2f2012-10-10 05:43:09 +00001379 const TargetSchedModel *SchedModel;
Andrew Trick3b87f622012-11-07 07:05:09 +00001380 SchedRemainder *Rem;
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001381
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001382 ReadyQueue Available;
1383 ReadyQueue Pending;
1384 bool CheckPending;
1385
Andrew Trick3b87f622012-11-07 07:05:09 +00001386 // For heuristics, keep a list of the nodes that immediately depend on the
1387 // most recently scheduled node.
1388 SmallPtrSet<const SUnit*, 8> NextSUs;
1389
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001390 ScheduleHazardRecognizer *HazardRec;
1391
Andrew Trickfa989e72013-06-15 05:39:19 +00001392 /// Number of cycles it takes to issue the instructions scheduled in this
1393 /// zone. It is defined as: scheduled-micro-ops / issue-width + stalls.
1394 /// See getStalls().
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001395 unsigned CurrCycle;
Andrew Trickfa989e72013-06-15 05:39:19 +00001396
1397 /// Micro-ops issued in the current cycle
Andrew Trickbacb2492013-06-15 04:49:49 +00001398 unsigned CurrMOps;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001399
1400 /// MinReadyCycle - Cycle of the soonest available instruction.
1401 unsigned MinReadyCycle;
1402
Andrew Trick3b87f622012-11-07 07:05:09 +00001403 // The expected latency of the critical path in this scheduled zone.
1404 unsigned ExpectedLatency;
1405
Andrew Trick2c465a32013-06-15 04:49:44 +00001406 // The latency of dependence chains leading into this zone.
Andrew Trickcc47c122013-08-07 17:20:32 +00001407 // For each node scheduled bottom-up: DLat = max DLat, N.Depth.
Andrew Trick2c465a32013-06-15 04:49:44 +00001408 // For each cycle scheduled: DLat -= 1.
1409 unsigned DependentLatency;
1410
Andrew Trickfa989e72013-06-15 05:39:19 +00001411 /// Count the scheduled (issued) micro-ops that can be retired by
1412 /// time=CurrCycle assuming the first scheduled instr is retired at time=0.
1413 unsigned RetiredMOps;
1414
1415 // Count scheduled resources that have been executed. Resources are
1416 // considered executed if they become ready in the time that it takes to
1417 // saturate any resource including the one in question. Counts are scaled
Andrew Trick4e389802013-07-19 00:20:07 +00001418 // for direct comparison with other resources. Counts can be compared with
Andrew Trickfa989e72013-06-15 05:39:19 +00001419 // MOps * getMicroOpFactor and Latency * getLatencyFactor.
1420 SmallVector<unsigned, 16> ExecutedResCounts;
1421
1422 /// Cache the max count for a single resource.
1423 unsigned MaxExecutedResCount;
Andrew Trick3b87f622012-11-07 07:05:09 +00001424
1425 // Cache the critical resources ID in this scheduled zone.
Andrew Trickfa989e72013-06-15 05:39:19 +00001426 unsigned ZoneCritResIdx;
Andrew Trick3b87f622012-11-07 07:05:09 +00001427
1428 // Is the scheduled region resource limited vs. latency limited.
1429 bool IsResourceLimited;
1430
Andrew Trick3b87f622012-11-07 07:05:09 +00001431#ifndef NDEBUG
Andrew Trickb86a0cd2013-06-15 04:49:57 +00001432 // Remember the greatest operand latency as an upper bound on the number of
1433 // times we should retry the pending queue because of a hazard.
1434 unsigned MaxObservedLatency;
Andrew Trick3b87f622012-11-07 07:05:09 +00001435#endif
1436
1437 void reset() {
Andrew Trickecb8c2b2013-02-13 19:22:27 +00001438 // A new HazardRec is created for each DAG and owned by SchedBoundary.
1439 delete HazardRec;
1440
Andrew Trick3b87f622012-11-07 07:05:09 +00001441 Available.clear();
1442 Pending.clear();
1443 CheckPending = false;
1444 NextSUs.clear();
1445 HazardRec = 0;
1446 CurrCycle = 0;
Andrew Trickbacb2492013-06-15 04:49:49 +00001447 CurrMOps = 0;
Andrew Trick3b87f622012-11-07 07:05:09 +00001448 MinReadyCycle = UINT_MAX;
1449 ExpectedLatency = 0;
Andrew Trick2c465a32013-06-15 04:49:44 +00001450 DependentLatency = 0;
Andrew Trickfa989e72013-06-15 05:39:19 +00001451 RetiredMOps = 0;
1452 MaxExecutedResCount = 0;
1453 ZoneCritResIdx = 0;
Andrew Trick3b87f622012-11-07 07:05:09 +00001454 IsResourceLimited = false;
Andrew Trick3b87f622012-11-07 07:05:09 +00001455#ifndef NDEBUG
Andrew Trickb86a0cd2013-06-15 04:49:57 +00001456 MaxObservedLatency = 0;
Andrew Trick3b87f622012-11-07 07:05:09 +00001457#endif
1458 // Reserve a zero-count for invalid CritResIdx.
Andrew Trickfa989e72013-06-15 05:39:19 +00001459 ExecutedResCounts.resize(1);
1460 assert(!ExecutedResCounts[0] && "nonzero count for bad resource");
Andrew Trick3b87f622012-11-07 07:05:09 +00001461 }
Andrew Trickb7e02892012-06-05 21:11:27 +00001462
Andrew Trickf3234242012-05-24 22:11:12 +00001463 /// Pending queues extend the ready queues with the same ID and the
1464 /// PendingFlag set.
1465 SchedBoundary(unsigned ID, const Twine &Name):
Andrew Trick3b87f622012-11-07 07:05:09 +00001466 DAG(0), SchedModel(0), Rem(0), Available(ID, Name+".A"),
Andrew Trickecb8c2b2013-02-13 19:22:27 +00001467 Pending(ID << ConvergingScheduler::LogMaxQID, Name+".P"),
1468 HazardRec(0) {
Andrew Trick3b87f622012-11-07 07:05:09 +00001469 reset();
1470 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001471
1472 ~SchedBoundary() { delete HazardRec; }
1473
Andrew Trick3b87f622012-11-07 07:05:09 +00001474 void init(ScheduleDAGMI *dag, const TargetSchedModel *smodel,
1475 SchedRemainder *rem);
Andrew Trick412cd2f2012-10-10 05:43:09 +00001476
Andrew Trickf3234242012-05-24 22:11:12 +00001477 bool isTop() const {
1478 return Available.getID() == ConvergingScheduler::TopQID;
1479 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001480
Andrew Trickaaaae512013-06-15 05:46:47 +00001481#ifndef NDEBUG
Andrew Trickfa989e72013-06-15 05:39:19 +00001482 const char *getResourceName(unsigned PIdx) {
1483 if (!PIdx)
1484 return "MOps";
1485 return SchedModel->getProcResource(PIdx)->Name;
Andrew Trick3b87f622012-11-07 07:05:09 +00001486 }
Andrew Trickaaaae512013-06-15 05:46:47 +00001487#endif
Andrew Trick3b87f622012-11-07 07:05:09 +00001488
Andrew Trickfa989e72013-06-15 05:39:19 +00001489 /// Get the number of latency cycles "covered" by the scheduled
1490 /// instructions. This is the larger of the critical path within the zone
1491 /// and the number of cycles required to issue the instructions.
1492 unsigned getScheduledLatency() const {
1493 return std::max(ExpectedLatency, CurrCycle);
1494 }
1495
1496 unsigned getUnscheduledLatency(SUnit *SU) const {
1497 return isTop() ? SU->getHeight() : SU->getDepth();
1498 }
1499
1500 unsigned getResourceCount(unsigned ResIdx) const {
1501 return ExecutedResCounts[ResIdx];
1502 }
1503
1504 /// Get the scaled count of scheduled micro-ops and resources, including
1505 /// executed resources.
Andrew Trick3b87f622012-11-07 07:05:09 +00001506 unsigned getCriticalCount() const {
Andrew Trickfa989e72013-06-15 05:39:19 +00001507 if (!ZoneCritResIdx)
1508 return RetiredMOps * SchedModel->getMicroOpFactor();
1509 return getResourceCount(ZoneCritResIdx);
1510 }
1511
1512 /// Get a scaled count for the minimum execution time of the scheduled
1513 /// micro-ops that are ready to execute by getExecutedCount. Notice the
1514 /// feedback loop.
1515 unsigned getExecutedCount() const {
1516 return std::max(CurrCycle * SchedModel->getLatencyFactor(),
1517 MaxExecutedResCount);
Andrew Trick3b87f622012-11-07 07:05:09 +00001518 }
1519
Andrew Trick5559ffa2012-06-29 03:23:24 +00001520 bool checkHazard(SUnit *SU);
1521
Andrew Trickfa989e72013-06-15 05:39:19 +00001522 unsigned findMaxLatency(ArrayRef<SUnit*> ReadySUs);
1523
1524 unsigned getOtherResourceCount(unsigned &OtherCritIdx);
1525
1526 void setPolicy(CandPolicy &Policy, SchedBoundary &OtherZone);
Andrew Trick3b87f622012-11-07 07:05:09 +00001527
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001528 void releaseNode(SUnit *SU, unsigned ReadyCycle);
1529
Andrew Trickfa989e72013-06-15 05:39:19 +00001530 void bumpCycle(unsigned NextCycle);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001531
Andrew Trickfa989e72013-06-15 05:39:19 +00001532 void incExecutedResources(unsigned PIdx, unsigned Count);
1533
1534 unsigned countResource(unsigned PIdx, unsigned Cycles, unsigned ReadyCycle);
Andrew Trick3b87f622012-11-07 07:05:09 +00001535
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001536 void bumpNode(SUnit *SU);
Andrew Trickb7e02892012-06-05 21:11:27 +00001537
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001538 void releasePending();
1539
1540 void removeReady(SUnit *SU);
1541
1542 SUnit *pickOnlyChoice();
Andrew Trickfa989e72013-06-15 05:39:19 +00001543
Andrew Trickaaaae512013-06-15 05:46:47 +00001544#ifndef NDEBUG
Andrew Trickfa989e72013-06-15 05:39:19 +00001545 void dumpScheduledState();
Andrew Trickaaaae512013-06-15 05:46:47 +00001546#endif
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001547 };
1548
Andrew Trick3b87f622012-11-07 07:05:09 +00001549private:
Andrew Trick17d35e52012-03-14 04:00:41 +00001550 ScheduleDAGMI *DAG;
Andrew Trick412cd2f2012-10-10 05:43:09 +00001551 const TargetSchedModel *SchedModel;
Andrew Trick7196a8f2012-05-10 21:06:16 +00001552 const TargetRegisterInfo *TRI;
Andrew Trick42b7a712012-01-17 06:55:03 +00001553
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001554 // State of the top and bottom scheduled instruction boundaries.
Andrew Trick3b87f622012-11-07 07:05:09 +00001555 SchedRemainder Rem;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001556 SchedBoundary Top;
1557 SchedBoundary Bot;
Andrew Trick17d35e52012-03-14 04:00:41 +00001558
1559public:
Andrew Trickf3234242012-05-24 22:11:12 +00001560 /// SUnit::NodeQueueId: 0 (none), 1 (top), 2 (bot), 3 (both)
Andrew Trick7196a8f2012-05-10 21:06:16 +00001561 enum {
1562 TopQID = 1,
Andrew Trickf3234242012-05-24 22:11:12 +00001563 BotQID = 2,
1564 LogMaxQID = 2
Andrew Trick7196a8f2012-05-10 21:06:16 +00001565 };
1566
Andrew Trickf3234242012-05-24 22:11:12 +00001567 ConvergingScheduler():
Andrew Trick412cd2f2012-10-10 05:43:09 +00001568 DAG(0), SchedModel(0), TRI(0), Top(TopQID, "TopQ"), Bot(BotQID, "BotQ") {}
Andrew Trickd38f87e2012-05-10 21:06:12 +00001569
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001570 virtual void initialize(ScheduleDAGMI *dag);
Andrew Trick17d35e52012-03-14 04:00:41 +00001571
Andrew Trick7196a8f2012-05-10 21:06:16 +00001572 virtual SUnit *pickNode(bool &IsTopNode);
Andrew Trick17d35e52012-03-14 04:00:41 +00001573
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001574 virtual void schedNode(SUnit *SU, bool IsTopNode);
1575
1576 virtual void releaseTopNode(SUnit *SU);
1577
1578 virtual void releaseBottomNode(SUnit *SU);
1579
Andrew Trick3b87f622012-11-07 07:05:09 +00001580 virtual void registerRoots();
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001581
Andrew Trick3b87f622012-11-07 07:05:09 +00001582protected:
Andrew Trickea574332013-08-23 17:48:43 +00001583 void checkAcyclicLatency();
1584
Andrew Trick3b87f622012-11-07 07:05:09 +00001585 void tryCandidate(SchedCandidate &Cand,
1586 SchedCandidate &TryCand,
1587 SchedBoundary &Zone,
1588 const RegPressureTracker &RPTracker,
1589 RegPressureTracker &TempTracker);
1590
1591 SUnit *pickNodeBidirectional(bool &IsTopNode);
1592
1593 void pickNodeFromQueue(SchedBoundary &Zone,
1594 const RegPressureTracker &RPTracker,
1595 SchedCandidate &Candidate);
1596
Andrew Trick4392f0f2013-04-13 06:07:40 +00001597 void reschedulePhysRegCopies(SUnit *SU, bool isTop);
1598
Andrew Trick28ebc892012-05-10 21:06:19 +00001599#ifndef NDEBUG
Andrew Trick11189f72013-04-05 00:31:29 +00001600 void traceCandidate(const SchedCandidate &Cand);
Andrew Trick28ebc892012-05-10 21:06:19 +00001601#endif
Andrew Trick42b7a712012-01-17 06:55:03 +00001602};
1603} // namespace
1604
Andrew Trick3b87f622012-11-07 07:05:09 +00001605void ConvergingScheduler::SchedRemainder::
1606init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
1607 reset();
1608 if (!SchedModel->hasInstrSchedModel())
1609 return;
1610 RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
1611 for (std::vector<SUnit>::iterator
1612 I = DAG->SUnits.begin(), E = DAG->SUnits.end(); I != E; ++I) {
1613 const MCSchedClassDesc *SC = DAG->getSchedClass(&*I);
Andrew Trickfa989e72013-06-15 05:39:19 +00001614 RemIssueCount += SchedModel->getNumMicroOps(I->getInstr(), SC)
1615 * SchedModel->getMicroOpFactor();
Andrew Trick3b87f622012-11-07 07:05:09 +00001616 for (TargetSchedModel::ProcResIter
1617 PI = SchedModel->getWriteProcResBegin(SC),
1618 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1619 unsigned PIdx = PI->ProcResourceIdx;
1620 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1621 RemainingCounts[PIdx] += (Factor * PI->Cycles);
1622 }
1623 }
1624}
1625
1626void ConvergingScheduler::SchedBoundary::
1627init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
1628 reset();
1629 DAG = dag;
1630 SchedModel = smodel;
1631 Rem = rem;
1632 if (SchedModel->hasInstrSchedModel())
Andrew Trickfa989e72013-06-15 05:39:19 +00001633 ExecutedResCounts.resize(SchedModel->getNumProcResourceKinds());
Andrew Trick3b87f622012-11-07 07:05:09 +00001634}
1635
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001636void ConvergingScheduler::initialize(ScheduleDAGMI *dag) {
1637 DAG = dag;
Andrew Trick412cd2f2012-10-10 05:43:09 +00001638 SchedModel = DAG->getSchedModel();
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001639 TRI = DAG->TRI;
Andrew Trickecb8c2b2013-02-13 19:22:27 +00001640
Andrew Trick3b87f622012-11-07 07:05:09 +00001641 Rem.init(DAG, SchedModel);
1642 Top.init(DAG, SchedModel, &Rem);
1643 Bot.init(DAG, SchedModel, &Rem);
1644
1645 // Initialize resource counts.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001646
Andrew Trick412cd2f2012-10-10 05:43:09 +00001647 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
1648 // are disabled, then these HazardRecs will be disabled.
1649 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001650 const TargetMachine &TM = DAG->MF.getTarget();
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001651 Top.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
1652 Bot.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
1653
1654 assert((!ForceTopDown || !ForceBottomUp) &&
1655 "-misched-topdown incompatible with -misched-bottomup");
1656}
1657
1658void ConvergingScheduler::releaseTopNode(SUnit *SU) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001659 if (SU->isScheduled)
1660 return;
1661
Andrew Trickd4539602012-12-18 20:52:52 +00001662 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
Andrew Trickb7e02892012-06-05 21:11:27 +00001663 I != E; ++I) {
Andrew Trickb86a0cd2013-06-15 04:49:57 +00001664 if (I->isWeak())
1665 continue;
Andrew Trickb7e02892012-06-05 21:11:27 +00001666 unsigned PredReadyCycle = I->getSUnit()->TopReadyCycle;
Andrew Trickb86a0cd2013-06-15 04:49:57 +00001667 unsigned Latency = I->getLatency();
Andrew Trickb7e02892012-06-05 21:11:27 +00001668#ifndef NDEBUG
Andrew Trickb86a0cd2013-06-15 04:49:57 +00001669 Top.MaxObservedLatency = std::max(Latency, Top.MaxObservedLatency);
Andrew Trickb7e02892012-06-05 21:11:27 +00001670#endif
Andrew Trickb86a0cd2013-06-15 04:49:57 +00001671 if (SU->TopReadyCycle < PredReadyCycle + Latency)
1672 SU->TopReadyCycle = PredReadyCycle + Latency;
Andrew Trickb7e02892012-06-05 21:11:27 +00001673 }
1674 Top.releaseNode(SU, SU->TopReadyCycle);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001675}
1676
1677void ConvergingScheduler::releaseBottomNode(SUnit *SU) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001678 if (SU->isScheduled)
1679 return;
1680
1681 assert(SU->getInstr() && "Scheduled SUnit must have instr");
1682
1683 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1684 I != E; ++I) {
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001685 if (I->isWeak())
1686 continue;
Andrew Trickb7e02892012-06-05 21:11:27 +00001687 unsigned SuccReadyCycle = I->getSUnit()->BotReadyCycle;
Andrew Trickb86a0cd2013-06-15 04:49:57 +00001688 unsigned Latency = I->getLatency();
Andrew Trickb7e02892012-06-05 21:11:27 +00001689#ifndef NDEBUG
Andrew Trickb86a0cd2013-06-15 04:49:57 +00001690 Bot.MaxObservedLatency = std::max(Latency, Bot.MaxObservedLatency);
Andrew Trickb7e02892012-06-05 21:11:27 +00001691#endif
Andrew Trickb86a0cd2013-06-15 04:49:57 +00001692 if (SU->BotReadyCycle < SuccReadyCycle + Latency)
1693 SU->BotReadyCycle = SuccReadyCycle + Latency;
Andrew Trickb7e02892012-06-05 21:11:27 +00001694 }
1695 Bot.releaseNode(SU, SU->BotReadyCycle);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001696}
1697
Andrew Trick851bb2c2013-08-29 18:04:49 +00001698/// Set IsAcyclicLatencyLimited if the acyclic path is longer than the cyclic
1699/// critical path by more cycles than it takes to drain the instruction buffer.
1700/// We estimate an upper bounds on in-flight instructions as:
1701///
1702/// CyclesPerIteration = max( CyclicPath, Loop-Resource-Height )
1703/// InFlightIterations = AcyclicPath / CyclesPerIteration
1704/// InFlightResources = InFlightIterations * LoopResources
1705///
1706/// TODO: Check execution resources in addition to IssueCount.
Andrew Trickea574332013-08-23 17:48:43 +00001707void ConvergingScheduler::checkAcyclicLatency() {
1708 if (Rem.CyclicCritPath == 0 || Rem.CyclicCritPath >= Rem.CriticalPath)
1709 return;
1710
Andrew Trick851bb2c2013-08-29 18:04:49 +00001711 // Scaled number of cycles per loop iteration.
1712 unsigned IterCount =
1713 std::max(Rem.CyclicCritPath * SchedModel->getLatencyFactor(),
1714 Rem.RemIssueCount);
1715 // Scaled acyclic critical path.
1716 unsigned AcyclicCount = Rem.CriticalPath * SchedModel->getLatencyFactor();
1717 // InFlightCount = (AcyclicPath / IterCycles) * InstrPerLoop
1718 unsigned InFlightCount =
1719 (AcyclicCount * Rem.RemIssueCount + IterCount-1) / IterCount;
Andrew Trickea574332013-08-23 17:48:43 +00001720 unsigned BufferLimit =
1721 SchedModel->getMicroOpBufferSize() * SchedModel->getMicroOpFactor();
Andrew Trickea574332013-08-23 17:48:43 +00001722
Andrew Trick851bb2c2013-08-29 18:04:49 +00001723 Rem.IsAcyclicLatencyLimited = InFlightCount > BufferLimit;
1724
1725 DEBUG(dbgs() << "IssueCycles="
1726 << Rem.RemIssueCount / SchedModel->getLatencyFactor() << "c "
1727 << "IterCycles=" << IterCount / SchedModel->getLatencyFactor()
1728 << "c NumIters=" << (AcyclicCount + IterCount-1) / IterCount
1729 << " InFlight=" << InFlightCount / SchedModel->getMicroOpFactor()
1730 << "m BufferLim=" << SchedModel->getMicroOpBufferSize() << "m\n";
Andrew Trickea574332013-08-23 17:48:43 +00001731 if (Rem.IsAcyclicLatencyLimited)
1732 dbgs() << " ACYCLIC LATENCY LIMIT\n");
1733}
1734
Andrew Trick3b87f622012-11-07 07:05:09 +00001735void ConvergingScheduler::registerRoots() {
1736 Rem.CriticalPath = DAG->ExitSU.getDepth();
Andrew Trickea574332013-08-23 17:48:43 +00001737
Andrew Trick3b87f622012-11-07 07:05:09 +00001738 // Some roots may not feed into ExitSU. Check all of them in case.
1739 for (std::vector<SUnit*>::const_iterator
1740 I = Bot.Available.begin(), E = Bot.Available.end(); I != E; ++I) {
1741 if ((*I)->getDepth() > Rem.CriticalPath)
1742 Rem.CriticalPath = (*I)->getDepth();
1743 }
1744 DEBUG(dbgs() << "Critical Path: " << Rem.CriticalPath << '\n');
Andrew Trick851bb2c2013-08-29 18:04:49 +00001745
1746 if (EnableCyclicPath) {
1747 Rem.CyclicCritPath = DAG->computeCyclicCriticalPath();
1748 checkAcyclicLatency();
1749 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001750}
1751
Andrew Trick5559ffa2012-06-29 03:23:24 +00001752/// Does this SU have a hazard within the current instruction group.
1753///
1754/// The scheduler supports two modes of hazard recognition. The first is the
1755/// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
1756/// supports highly complicated in-order reservation tables
1757/// (ScoreboardHazardRecognizer) and arbitraty target-specific logic.
1758///
1759/// The second is a streamlined mechanism that checks for hazards based on
1760/// simple counters that the scheduler itself maintains. It explicitly checks
1761/// for instruction dispatch limitations, including the number of micro-ops that
1762/// can dispatch per cycle.
1763///
1764/// TODO: Also check whether the SU must start a new group.
1765bool ConvergingScheduler::SchedBoundary::checkHazard(SUnit *SU) {
1766 if (HazardRec->isEnabled())
1767 return HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard;
1768
Andrew Trick412cd2f2012-10-10 05:43:09 +00001769 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
Andrew Trickbacb2492013-06-15 04:49:49 +00001770 if ((CurrMOps > 0) && (CurrMOps + uops > SchedModel->getIssueWidth())) {
Andrew Trick3b87f622012-11-07 07:05:09 +00001771 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") uops="
1772 << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
Andrew Trick5559ffa2012-06-29 03:23:24 +00001773 return true;
Andrew Trick3b87f622012-11-07 07:05:09 +00001774 }
Andrew Trick5559ffa2012-06-29 03:23:24 +00001775 return false;
1776}
1777
Andrew Trickfa989e72013-06-15 05:39:19 +00001778// Find the unscheduled node in ReadySUs with the highest latency.
1779unsigned ConvergingScheduler::SchedBoundary::
1780findMaxLatency(ArrayRef<SUnit*> ReadySUs) {
1781 SUnit *LateSU = 0;
1782 unsigned RemLatency = 0;
1783 for (ArrayRef<SUnit*>::iterator I = ReadySUs.begin(), E = ReadySUs.end();
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001784 I != E; ++I) {
1785 unsigned L = getUnscheduledLatency(*I);
Andrew Trick2c465a32013-06-15 04:49:44 +00001786 if (L > RemLatency) {
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001787 RemLatency = L;
Andrew Trickfa989e72013-06-15 05:39:19 +00001788 LateSU = *I;
Andrew Trick2c465a32013-06-15 04:49:44 +00001789 }
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001790 }
Andrew Trickfa989e72013-06-15 05:39:19 +00001791 if (LateSU) {
1792 DEBUG(dbgs() << Available.getName() << " RemLatency SU("
1793 << LateSU->NodeNum << ") " << RemLatency << "c\n");
Andrew Trick44fd0bc2012-12-18 20:52:56 +00001794 }
Andrew Trickfa989e72013-06-15 05:39:19 +00001795 return RemLatency;
1796}
Andrew Trick2c465a32013-06-15 04:49:44 +00001797
Andrew Trickfa989e72013-06-15 05:39:19 +00001798// Count resources in this zone and the remaining unscheduled
1799// instruction. Return the max count, scaled. Set OtherCritIdx to the critical
1800// resource index, or zero if the zone is issue limited.
1801unsigned ConvergingScheduler::SchedBoundary::
1802getOtherResourceCount(unsigned &OtherCritIdx) {
Alexey Samsonov86dc6f92013-07-19 08:55:18 +00001803 OtherCritIdx = 0;
Andrew Trickfa989e72013-06-15 05:39:19 +00001804 if (!SchedModel->hasInstrSchedModel())
1805 return 0;
1806
1807 unsigned OtherCritCount = Rem->RemIssueCount
1808 + (RetiredMOps * SchedModel->getMicroOpFactor());
1809 DEBUG(dbgs() << " " << Available.getName() << " + Remain MOps: "
1810 << OtherCritCount / SchedModel->getMicroOpFactor() << '\n');
Andrew Trickfa989e72013-06-15 05:39:19 +00001811 for (unsigned PIdx = 1, PEnd = SchedModel->getNumProcResourceKinds();
1812 PIdx != PEnd; ++PIdx) {
1813 unsigned OtherCount = getResourceCount(PIdx) + Rem->RemainingCounts[PIdx];
1814 if (OtherCount > OtherCritCount) {
1815 OtherCritCount = OtherCount;
1816 OtherCritIdx = PIdx;
1817 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001818 }
Andrew Trickfa989e72013-06-15 05:39:19 +00001819 if (OtherCritIdx) {
1820 DEBUG(dbgs() << " " << Available.getName() << " + Remain CritRes: "
1821 << OtherCritCount / SchedModel->getResourceFactor(OtherCritIdx)
1822 << " " << getResourceName(OtherCritIdx) << "\n");
1823 }
1824 return OtherCritCount;
1825}
1826
1827/// Set the CandPolicy for this zone given the current resources and latencies
1828/// inside and outside the zone.
1829void ConvergingScheduler::SchedBoundary::setPolicy(CandPolicy &Policy,
1830 SchedBoundary &OtherZone) {
1831 // Now that potential stalls have been considered, apply preemptive heuristics
1832 // based on the the total latency and resources inside and outside this
1833 // zone.
1834
1835 // Compute remaining latency. We need this both to determine whether the
1836 // overall schedule has become latency-limited and whether the instructions
1837 // outside this zone are resource or latency limited.
1838 //
1839 // The "dependent" latency is updated incrementally during scheduling as the
1840 // max height/depth of scheduled nodes minus the cycles since it was
1841 // scheduled:
1842 // DLat = max (N.depth - (CurrCycle - N.ReadyCycle) for N in Zone
1843 //
1844 // The "independent" latency is the max ready queue depth:
1845 // ILat = max N.depth for N in Available|Pending
1846 //
1847 // RemainingLatency is the greater of independent and dependent latency.
1848 unsigned RemLatency = DependentLatency;
1849 RemLatency = std::max(RemLatency, findMaxLatency(Available.elements()));
1850 RemLatency = std::max(RemLatency, findMaxLatency(Pending.elements()));
1851
1852 // Compute the critical resource outside the zone.
1853 unsigned OtherCritIdx;
1854 unsigned OtherCount = OtherZone.getOtherResourceCount(OtherCritIdx);
1855
1856 bool OtherResLimited = false;
1857 if (SchedModel->hasInstrSchedModel()) {
1858 unsigned LFactor = SchedModel->getLatencyFactor();
1859 OtherResLimited = (int)(OtherCount - (RemLatency * LFactor)) > (int)LFactor;
1860 }
1861 if (!OtherResLimited && (RemLatency + CurrCycle > Rem->CriticalPath)) {
1862 Policy.ReduceLatency |= true;
1863 DEBUG(dbgs() << " " << Available.getName() << " RemainingLatency "
1864 << RemLatency << " + " << CurrCycle << "c > CritPath "
1865 << Rem->CriticalPath << "\n");
1866 }
1867 // If the same resource is limiting inside and outside the zone, do nothing.
Andrew Trick4e389802013-07-19 00:20:07 +00001868 if (ZoneCritResIdx == OtherCritIdx)
Andrew Trickfa989e72013-06-15 05:39:19 +00001869 return;
1870
1871 DEBUG(
1872 if (IsResourceLimited) {
1873 dbgs() << " " << Available.getName() << " ResourceLimited: "
1874 << getResourceName(ZoneCritResIdx) << "\n";
1875 }
1876 if (OtherResLimited)
Andrew Trick3bf23302013-06-21 18:33:01 +00001877 dbgs() << " RemainingLimit: " << getResourceName(OtherCritIdx) << "\n";
Andrew Trickfa989e72013-06-15 05:39:19 +00001878 if (!IsResourceLimited && !OtherResLimited)
1879 dbgs() << " Latency limited both directions.\n");
1880
1881 if (IsResourceLimited && !Policy.ReduceResIdx)
1882 Policy.ReduceResIdx = ZoneCritResIdx;
1883
1884 if (OtherResLimited)
1885 Policy.DemandResIdx = OtherCritIdx;
Andrew Trick3b87f622012-11-07 07:05:09 +00001886}
1887
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001888void ConvergingScheduler::SchedBoundary::releaseNode(SUnit *SU,
1889 unsigned ReadyCycle) {
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001890 if (ReadyCycle < MinReadyCycle)
1891 MinReadyCycle = ReadyCycle;
1892
1893 // Check for interlocks first. For the purpose of other heuristics, an
1894 // instruction that cannot issue appears as if it's not in the ReadyQueue.
Andrew Trickfa989e72013-06-15 05:39:19 +00001895 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
1896 if ((!IsBuffered && ReadyCycle > CurrCycle) || checkHazard(SU))
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001897 Pending.push(SU);
1898 else
1899 Available.push(SU);
Andrew Trick3b87f622012-11-07 07:05:09 +00001900
1901 // Record this node as an immediate dependent of the scheduled node.
1902 NextSUs.insert(SU);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001903}
1904
1905/// Move the boundary of scheduled code by one cycle.
Andrew Trickfa989e72013-06-15 05:39:19 +00001906void ConvergingScheduler::SchedBoundary::bumpCycle(unsigned NextCycle) {
1907 if (SchedModel->getMicroOpBufferSize() == 0) {
1908 assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
1909 if (MinReadyCycle > NextCycle)
1910 NextCycle = MinReadyCycle;
Andrew Trick3b87f622012-11-07 07:05:09 +00001911 }
Andrew Trickfa989e72013-06-15 05:39:19 +00001912 // Update the current micro-ops, which will issue in the next cycle.
1913 unsigned DecMOps = SchedModel->getIssueWidth() * (NextCycle - CurrCycle);
1914 CurrMOps = (CurrMOps <= DecMOps) ? 0 : CurrMOps - DecMOps;
1915
1916 // Decrement DependentLatency based on the next cycle.
Andrew Trick2c465a32013-06-15 04:49:44 +00001917 if ((NextCycle - CurrCycle) > DependentLatency)
1918 DependentLatency = 0;
1919 else
1920 DependentLatency -= (NextCycle - CurrCycle);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001921
1922 if (!HazardRec->isEnabled()) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001923 // Bypass HazardRec virtual calls.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001924 CurrCycle = NextCycle;
1925 }
1926 else {
Andrew Trickb7e02892012-06-05 21:11:27 +00001927 // Bypass getHazardType calls in case of long latency.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001928 for (; CurrCycle != NextCycle; ++CurrCycle) {
1929 if (isTop())
1930 HazardRec->AdvanceCycle();
1931 else
1932 HazardRec->RecedeCycle();
1933 }
1934 }
1935 CheckPending = true;
Andrew Trickfa989e72013-06-15 05:39:19 +00001936 unsigned LFactor = SchedModel->getLatencyFactor();
1937 IsResourceLimited =
1938 (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
1939 > (int)LFactor;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001940
Andrew Trickfa989e72013-06-15 05:39:19 +00001941 DEBUG(dbgs() << "Cycle: " << CurrCycle << ' ' << Available.getName() << '\n');
1942}
1943
1944void ConvergingScheduler::SchedBoundary::incExecutedResources(unsigned PIdx,
1945 unsigned Count) {
1946 ExecutedResCounts[PIdx] += Count;
1947 if (ExecutedResCounts[PIdx] > MaxExecutedResCount)
1948 MaxExecutedResCount = ExecutedResCounts[PIdx];
Andrew Trick0a39d4e2012-05-24 22:11:09 +00001949}
1950
Andrew Trick3b87f622012-11-07 07:05:09 +00001951/// Add the given processor resource to this scheduled zone.
Andrew Trickfa989e72013-06-15 05:39:19 +00001952///
1953/// \param Cycles indicates the number of consecutive (non-pipelined) cycles
1954/// during which this resource is consumed.
1955///
1956/// \return the next cycle at which the instruction may execute without
1957/// oversubscribing resources.
1958unsigned ConvergingScheduler::SchedBoundary::
1959countResource(unsigned PIdx, unsigned Cycles, unsigned ReadyCycle) {
Andrew Trick3b87f622012-11-07 07:05:09 +00001960 unsigned Factor = SchedModel->getResourceFactor(PIdx);
Andrew Trick3b87f622012-11-07 07:05:09 +00001961 unsigned Count = Factor * Cycles;
Andrew Trickfa989e72013-06-15 05:39:19 +00001962 DEBUG(dbgs() << " " << getResourceName(PIdx)
1963 << " +" << Cycles << "x" << Factor << "u\n");
1964
1965 // Update Executed resources counts.
1966 incExecutedResources(PIdx, Count);
Andrew Trick3b87f622012-11-07 07:05:09 +00001967 assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
1968 Rem->RemainingCounts[PIdx] -= Count;
1969
Andrew Trick4e389802013-07-19 00:20:07 +00001970 // Check if this resource exceeds the current critical resource. If so, it
1971 // becomes the critical resource.
1972 if (ZoneCritResIdx != PIdx && (getResourceCount(PIdx) > getCriticalCount())) {
Andrew Trickfa989e72013-06-15 05:39:19 +00001973 ZoneCritResIdx = PIdx;
Andrew Trick3b87f622012-11-07 07:05:09 +00001974 DEBUG(dbgs() << " *** Critical resource "
Andrew Trickfa989e72013-06-15 05:39:19 +00001975 << getResourceName(PIdx) << ": "
1976 << getResourceCount(PIdx) / SchedModel->getLatencyFactor() << "c\n");
Andrew Trick3b87f622012-11-07 07:05:09 +00001977 }
Andrew Trickfa989e72013-06-15 05:39:19 +00001978 // TODO: We don't yet model reserved resources. It's not hard though.
1979 return CurrCycle;
Andrew Trick3b87f622012-11-07 07:05:09 +00001980}
1981
Andrew Trickb7e02892012-06-05 21:11:27 +00001982/// Move the boundary of scheduled code by one SUnit.
Andrew Trick7f8c74c2012-06-29 03:23:22 +00001983void ConvergingScheduler::SchedBoundary::bumpNode(SUnit *SU) {
Andrew Trickb7e02892012-06-05 21:11:27 +00001984 // Update the reservation table.
1985 if (HazardRec->isEnabled()) {
1986 if (!isTop() && SU->isCall) {
1987 // Calls are scheduled with their preceding instructions. For bottom-up
1988 // scheduling, clear the pipeline state before emitting.
1989 HazardRec->Reset();
1990 }
1991 HazardRec->EmitInstruction(SU);
1992 }
Andrew Trickfa989e72013-06-15 05:39:19 +00001993 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1994 unsigned IncMOps = SchedModel->getNumMicroOps(SU->getInstr());
1995 CurrMOps += IncMOps;
Andrew Trick3b87f622012-11-07 07:05:09 +00001996 // checkHazard prevents scheduling multiple instructions per cycle that exceed
1997 // issue width. However, we commonly reach the maximum. In this case
1998 // opportunistically bump the cycle to avoid uselessly checking everything in
1999 // the readyQ. Furthermore, a single instruction may produce more than one
2000 // cycle's worth of micro-ops.
Andrew Trickfa989e72013-06-15 05:39:19 +00002001 //
2002 // TODO: Also check if this SU must end a dispatch group.
2003 unsigned NextCycle = CurrCycle;
Andrew Trickbacb2492013-06-15 04:49:49 +00002004 if (CurrMOps >= SchedModel->getIssueWidth()) {
Andrew Trickfa989e72013-06-15 05:39:19 +00002005 ++NextCycle;
2006 DEBUG(dbgs() << " *** Max MOps " << CurrMOps
2007 << " at cycle " << CurrCycle << '\n');
Andrew Trickb7e02892012-06-05 21:11:27 +00002008 }
Andrew Trickfa989e72013-06-15 05:39:19 +00002009 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
2010 DEBUG(dbgs() << " Ready @" << ReadyCycle << "c\n");
2011
2012 switch (SchedModel->getMicroOpBufferSize()) {
2013 case 0:
2014 assert(ReadyCycle <= CurrCycle && "Broken PendingQueue");
2015 break;
2016 case 1:
2017 if (ReadyCycle > NextCycle) {
2018 NextCycle = ReadyCycle;
2019 DEBUG(dbgs() << " *** Stall until: " << ReadyCycle << "\n");
2020 }
2021 break;
2022 default:
2023 // We don't currently model the OOO reorder buffer, so consider all
2024 // scheduled MOps to be "retired".
2025 break;
2026 }
2027 RetiredMOps += IncMOps;
2028
2029 // Update resource counts and critical resource.
2030 if (SchedModel->hasInstrSchedModel()) {
2031 unsigned DecRemIssue = IncMOps * SchedModel->getMicroOpFactor();
2032 assert(Rem->RemIssueCount >= DecRemIssue && "MOps double counted");
2033 Rem->RemIssueCount -= DecRemIssue;
2034 if (ZoneCritResIdx) {
2035 // Scale scheduled micro-ops for comparing with the critical resource.
2036 unsigned ScaledMOps =
2037 RetiredMOps * SchedModel->getMicroOpFactor();
2038
2039 // If scaled micro-ops are now more than the previous critical resource by
2040 // a full cycle, then micro-ops issue becomes critical.
2041 if ((int)(ScaledMOps - getResourceCount(ZoneCritResIdx))
2042 >= (int)SchedModel->getLatencyFactor()) {
2043 ZoneCritResIdx = 0;
2044 DEBUG(dbgs() << " *** Critical resource NumMicroOps: "
2045 << ScaledMOps / SchedModel->getLatencyFactor() << "c\n");
2046 }
2047 }
2048 for (TargetSchedModel::ProcResIter
2049 PI = SchedModel->getWriteProcResBegin(SC),
2050 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2051 unsigned RCycle =
2052 countResource(PI->ProcResourceIdx, PI->Cycles, ReadyCycle);
2053 if (RCycle > NextCycle)
2054 NextCycle = RCycle;
2055 }
2056 }
2057 // Update ExpectedLatency and DependentLatency.
2058 unsigned &TopLatency = isTop() ? ExpectedLatency : DependentLatency;
2059 unsigned &BotLatency = isTop() ? DependentLatency : ExpectedLatency;
2060 if (SU->getDepth() > TopLatency) {
2061 TopLatency = SU->getDepth();
2062 DEBUG(dbgs() << " " << Available.getName()
2063 << " TopLatency SU(" << SU->NodeNum << ") " << TopLatency << "c\n");
2064 }
2065 if (SU->getHeight() > BotLatency) {
2066 BotLatency = SU->getHeight();
2067 DEBUG(dbgs() << " " << Available.getName()
2068 << " BotLatency SU(" << SU->NodeNum << ") " << BotLatency << "c\n");
2069 }
2070 // If we stall for any reason, bump the cycle.
2071 if (NextCycle > CurrCycle) {
2072 bumpCycle(NextCycle);
2073 }
2074 else {
2075 // After updating ZoneCritResIdx and ExpectedLatency, check if we're
2076 // resource limited. If a stall occured, bumpCycle does this.
2077 unsigned LFactor = SchedModel->getLatencyFactor();
2078 IsResourceLimited =
2079 (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
2080 > (int)LFactor;
2081 }
2082 DEBUG(dumpScheduledState());
Andrew Trickb7e02892012-06-05 21:11:27 +00002083}
2084
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002085/// Release pending ready nodes in to the available queue. This makes them
2086/// visible to heuristics.
2087void ConvergingScheduler::SchedBoundary::releasePending() {
2088 // If the available queue is empty, it is safe to reset MinReadyCycle.
2089 if (Available.empty())
2090 MinReadyCycle = UINT_MAX;
2091
2092 // Check to see if any of the pending instructions are ready to issue. If
2093 // so, add them to the available queue.
Andrew Trickfa989e72013-06-15 05:39:19 +00002094 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002095 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
2096 SUnit *SU = *(Pending.begin()+i);
Andrew Trickb7e02892012-06-05 21:11:27 +00002097 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002098
2099 if (ReadyCycle < MinReadyCycle)
2100 MinReadyCycle = ReadyCycle;
2101
Andrew Trickfa989e72013-06-15 05:39:19 +00002102 if (!IsBuffered && ReadyCycle > CurrCycle)
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002103 continue;
2104
Andrew Trick5559ffa2012-06-29 03:23:24 +00002105 if (checkHazard(SU))
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002106 continue;
2107
2108 Available.push(SU);
2109 Pending.remove(Pending.begin()+i);
2110 --i; --e;
2111 }
Andrew Trick3b87f622012-11-07 07:05:09 +00002112 DEBUG(if (!Pending.empty()) Pending.dump());
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002113 CheckPending = false;
2114}
2115
2116/// Remove SU from the ready set for this boundary.
2117void ConvergingScheduler::SchedBoundary::removeReady(SUnit *SU) {
2118 if (Available.isInQueue(SU))
2119 Available.remove(Available.find(SU));
2120 else {
2121 assert(Pending.isInQueue(SU) && "bad ready count");
2122 Pending.remove(Pending.find(SU));
2123 }
2124}
2125
2126/// If this queue only has one ready candidate, return it. As a side effect,
Andrew Trick3b87f622012-11-07 07:05:09 +00002127/// defer any nodes that now hit a hazard, and advance the cycle until at least
2128/// one node is ready. If multiple instructions are ready, return NULL.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002129SUnit *ConvergingScheduler::SchedBoundary::pickOnlyChoice() {
2130 if (CheckPending)
2131 releasePending();
2132
Andrew Trickbacb2492013-06-15 04:49:49 +00002133 if (CurrMOps > 0) {
Andrew Trick3b87f622012-11-07 07:05:09 +00002134 // Defer any ready instrs that now have a hazard.
2135 for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
2136 if (checkHazard(*I)) {
2137 Pending.push(*I);
2138 I = Available.remove(I);
2139 continue;
2140 }
2141 ++I;
2142 }
2143 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002144 for (unsigned i = 0; Available.empty(); ++i) {
Andrew Trickb86a0cd2013-06-15 04:49:57 +00002145 assert(i <= (HazardRec->getMaxLookAhead() + MaxObservedLatency) &&
Andrew Trickb7e02892012-06-05 21:11:27 +00002146 "permanent hazard"); (void)i;
Andrew Trickfa989e72013-06-15 05:39:19 +00002147 bumpCycle(CurrCycle + 1);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002148 releasePending();
2149 }
2150 if (Available.size() == 1)
2151 return *Available.begin();
2152 return NULL;
2153}
2154
Andrew Trickaaaae512013-06-15 05:46:47 +00002155#ifndef NDEBUG
Andrew Trickfa989e72013-06-15 05:39:19 +00002156// This is useful information to dump after bumpNode.
2157// Note that the Queue contents are more useful before pickNodeFromQueue.
2158void ConvergingScheduler::SchedBoundary::dumpScheduledState() {
2159 unsigned ResFactor;
2160 unsigned ResCount;
2161 if (ZoneCritResIdx) {
2162 ResFactor = SchedModel->getResourceFactor(ZoneCritResIdx);
2163 ResCount = getResourceCount(ZoneCritResIdx);
Andrew Trick3b87f622012-11-07 07:05:09 +00002164 }
Andrew Trickfa989e72013-06-15 05:39:19 +00002165 else {
2166 ResFactor = SchedModel->getMicroOpFactor();
2167 ResCount = RetiredMOps * SchedModel->getMicroOpFactor();
Andrew Trick3b87f622012-11-07 07:05:09 +00002168 }
Andrew Trickfa989e72013-06-15 05:39:19 +00002169 unsigned LFactor = SchedModel->getLatencyFactor();
2170 dbgs() << Available.getName() << " @" << CurrCycle << "c\n"
2171 << " Retired: " << RetiredMOps;
2172 dbgs() << "\n Executed: " << getExecutedCount() / LFactor << "c";
2173 dbgs() << "\n Critical: " << ResCount / LFactor << "c, "
2174 << ResCount / ResFactor << " " << getResourceName(ZoneCritResIdx)
2175 << "\n ExpectedLatency: " << ExpectedLatency << "c\n"
2176 << (IsResourceLimited ? " - Resource" : " - Latency")
2177 << " limited.\n";
Andrew Trick3b87f622012-11-07 07:05:09 +00002178}
Andrew Trickaaaae512013-06-15 05:46:47 +00002179#endif
Andrew Trick3b87f622012-11-07 07:05:09 +00002180
2181void ConvergingScheduler::SchedCandidate::
2182initResourceDelta(const ScheduleDAGMI *DAG,
2183 const TargetSchedModel *SchedModel) {
2184 if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
2185 return;
2186
2187 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
2188 for (TargetSchedModel::ProcResIter
2189 PI = SchedModel->getWriteProcResBegin(SC),
2190 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2191 if (PI->ProcResourceIdx == Policy.ReduceResIdx)
2192 ResDelta.CritResources += PI->Cycles;
2193 if (PI->ProcResourceIdx == Policy.DemandResIdx)
2194 ResDelta.DemandedResources += PI->Cycles;
2195 }
2196}
2197
Andrew Tricke52d5022013-06-17 21:45:05 +00002198
Andrew Trick3b87f622012-11-07 07:05:09 +00002199/// Return true if this heuristic determines order.
Andrew Trick614dacc2013-04-05 00:31:34 +00002200static bool tryLess(int TryVal, int CandVal,
Andrew Trick3b87f622012-11-07 07:05:09 +00002201 ConvergingScheduler::SchedCandidate &TryCand,
2202 ConvergingScheduler::SchedCandidate &Cand,
2203 ConvergingScheduler::CandReason Reason) {
2204 if (TryVal < CandVal) {
2205 TryCand.Reason = Reason;
2206 return true;
2207 }
2208 if (TryVal > CandVal) {
2209 if (Cand.Reason > Reason)
2210 Cand.Reason = Reason;
2211 return true;
2212 }
Andrew Tricke52d5022013-06-17 21:45:05 +00002213 Cand.setRepeat(Reason);
Andrew Trick3b87f622012-11-07 07:05:09 +00002214 return false;
2215}
Andrew Trick9b5caaa2012-11-12 19:40:10 +00002216
Andrew Trick614dacc2013-04-05 00:31:34 +00002217static bool tryGreater(int TryVal, int CandVal,
Andrew Trick3b87f622012-11-07 07:05:09 +00002218 ConvergingScheduler::SchedCandidate &TryCand,
2219 ConvergingScheduler::SchedCandidate &Cand,
2220 ConvergingScheduler::CandReason Reason) {
2221 if (TryVal > CandVal) {
2222 TryCand.Reason = Reason;
2223 return true;
2224 }
2225 if (TryVal < CandVal) {
2226 if (Cand.Reason > Reason)
2227 Cand.Reason = Reason;
2228 return true;
2229 }
Andrew Tricke52d5022013-06-17 21:45:05 +00002230 Cand.setRepeat(Reason);
Andrew Trick3b87f622012-11-07 07:05:09 +00002231 return false;
2232}
2233
Andrew Trick4c60b8a2013-08-30 03:49:48 +00002234static bool tryPressure(const PressureChange &TryP,
2235 const PressureChange &CandP,
Andrew Trick13372882013-07-25 07:26:35 +00002236 ConvergingScheduler::SchedCandidate &TryCand,
2237 ConvergingScheduler::SchedCandidate &Cand,
2238 ConvergingScheduler::CandReason Reason) {
Andrew Trickda6fc152013-08-30 04:27:29 +00002239 int TryRank = TryP.getPSetOrMax();
2240 int CandRank = CandP.getPSetOrMax();
2241 // If both candidates affect the same set, go with the smallest increase.
2242 if (TryRank == CandRank) {
2243 return tryLess(TryP.getUnitInc(), CandP.getUnitInc(), TryCand, Cand,
2244 Reason);
Andrew Trick13372882013-07-25 07:26:35 +00002245 }
Andrew Trickda6fc152013-08-30 04:27:29 +00002246 // If one candidate decreases and the other increases, go with it.
2247 // Invalid candidates have UnitInc==0.
2248 if (tryLess(TryP.getUnitInc() < 0, CandP.getUnitInc() < 0, TryCand, Cand,
2249 Reason)) {
2250 return true;
2251 }
Andrew Trick13372882013-07-25 07:26:35 +00002252 // If the candidates are decreasing pressure, reverse priority.
Andrew Trick4c60b8a2013-08-30 03:49:48 +00002253 if (TryP.getUnitInc() < 0)
Andrew Trick13372882013-07-25 07:26:35 +00002254 std::swap(TryRank, CandRank);
2255 return tryGreater(TryRank, CandRank, TryCand, Cand, Reason);
2256}
2257
Andrew Trick9b5caaa2012-11-12 19:40:10 +00002258static unsigned getWeakLeft(const SUnit *SU, bool isTop) {
2259 return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
2260}
2261
Andrew Trick4392f0f2013-04-13 06:07:40 +00002262/// Minimize physical register live ranges. Regalloc wants them adjacent to
2263/// their physreg def/use.
2264///
2265/// FIXME: This is an unnecessary check on the critical path. Most are root/leaf
2266/// copies which can be prescheduled. The rest (e.g. x86 MUL) could be bundled
2267/// with the operation that produces or consumes the physreg. We'll do this when
2268/// regalloc has support for parallel copies.
2269static int biasPhysRegCopy(const SUnit *SU, bool isTop) {
2270 const MachineInstr *MI = SU->getInstr();
2271 if (!MI->isCopy())
2272 return 0;
2273
2274 unsigned ScheduledOper = isTop ? 1 : 0;
2275 unsigned UnscheduledOper = isTop ? 0 : 1;
2276 // If we have already scheduled the physreg produce/consumer, immediately
2277 // schedule the copy.
2278 if (TargetRegisterInfo::isPhysicalRegister(
2279 MI->getOperand(ScheduledOper).getReg()))
2280 return 1;
2281 // If the physreg is at the boundary, defer it. Otherwise schedule it
2282 // immediately to free the dependent. We can hoist the copy later.
2283 bool AtBoundary = isTop ? !SU->NumSuccsLeft : !SU->NumPredsLeft;
2284 if (TargetRegisterInfo::isPhysicalRegister(
2285 MI->getOperand(UnscheduledOper).getReg()))
2286 return AtBoundary ? -1 : 1;
2287 return 0;
2288}
2289
Andrew Trickea574332013-08-23 17:48:43 +00002290static bool tryLatency(ConvergingScheduler::SchedCandidate &TryCand,
2291 ConvergingScheduler::SchedCandidate &Cand,
2292 ConvergingScheduler::SchedBoundary &Zone) {
2293 if (Zone.isTop()) {
2294 if (Cand.SU->getDepth() > Zone.getScheduledLatency()) {
2295 if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2296 TryCand, Cand, ConvergingScheduler::TopDepthReduce))
2297 return true;
2298 }
2299 if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2300 TryCand, Cand, ConvergingScheduler::TopPathReduce))
2301 return true;
2302 }
2303 else {
2304 if (Cand.SU->getHeight() > Zone.getScheduledLatency()) {
2305 if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2306 TryCand, Cand, ConvergingScheduler::BotHeightReduce))
2307 return true;
2308 }
2309 if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2310 TryCand, Cand, ConvergingScheduler::BotPathReduce))
2311 return true;
2312 }
2313 return false;
2314}
2315
Andrew Trick3b87f622012-11-07 07:05:09 +00002316/// Apply a set of heursitics to a new candidate. Heuristics are currently
2317/// hierarchical. This may be more efficient than a graduated cost model because
2318/// we don't need to evaluate all aspects of the model for each node in the
2319/// queue. But it's really done to make the heuristics easier to debug and
2320/// statistically analyze.
2321///
2322/// \param Cand provides the policy and current best candidate.
2323/// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
2324/// \param Zone describes the scheduled zone that we are extending.
2325/// \param RPTracker describes reg pressure within the scheduled zone.
2326/// \param TempTracker is a scratch pressure tracker to reuse in queries.
2327void ConvergingScheduler::tryCandidate(SchedCandidate &Cand,
2328 SchedCandidate &TryCand,
2329 SchedBoundary &Zone,
2330 const RegPressureTracker &RPTracker,
2331 RegPressureTracker &TempTracker) {
2332
2333 // Always initialize TryCand's RPDelta.
Andrew Trick4c60b8a2013-08-30 03:49:48 +00002334 if (Zone.isTop()) {
2335 TempTracker.getMaxDownwardPressureDelta(
2336 TryCand.SU->getInstr(),
2337 TryCand.RPDelta,
2338 DAG->getRegionCriticalPSets(),
2339 DAG->getRegPressure().MaxSetPressure);
2340 }
2341 else {
2342 if (VerifyScheduling) {
2343 TempTracker.getMaxUpwardPressureDelta(
2344 TryCand.SU->getInstr(),
2345 &DAG->getPressureDiff(TryCand.SU),
2346 TryCand.RPDelta,
2347 DAG->getRegionCriticalPSets(),
2348 DAG->getRegPressure().MaxSetPressure);
2349 }
2350 else {
2351 RPTracker.getUpwardPressureDelta(
2352 TryCand.SU->getInstr(),
2353 DAG->getPressureDiff(TryCand.SU),
2354 TryCand.RPDelta,
2355 DAG->getRegionCriticalPSets(),
2356 DAG->getRegPressure().MaxSetPressure);
2357 }
2358 }
Andrew Trick3b87f622012-11-07 07:05:09 +00002359
2360 // Initialize the candidate if needed.
2361 if (!Cand.isValid()) {
2362 TryCand.Reason = NodeOrder;
2363 return;
2364 }
Andrew Trick4392f0f2013-04-13 06:07:40 +00002365
2366 if (tryGreater(biasPhysRegCopy(TryCand.SU, Zone.isTop()),
2367 biasPhysRegCopy(Cand.SU, Zone.isTop()),
2368 TryCand, Cand, PhysRegCopy))
2369 return;
2370
Andrew Trick13372882013-07-25 07:26:35 +00002371 // Avoid exceeding the target's limit. If signed PSetID is negative, it is
2372 // invalid; convert it to INT_MAX to give it lowest priority.
2373 if (tryPressure(TryCand.RPDelta.Excess, Cand.RPDelta.Excess, TryCand, Cand,
2374 RegExcess))
Andrew Trick3b87f622012-11-07 07:05:09 +00002375 return;
Andrew Trick3b87f622012-11-07 07:05:09 +00002376
Andrew Trickea574332013-08-23 17:48:43 +00002377 // For loops that are acyclic path limited, aggressively schedule for latency.
2378 if (Rem.IsAcyclicLatencyLimited && tryLatency(TryCand, Cand, Zone))
2379 return;
2380
Andrew Trick3b87f622012-11-07 07:05:09 +00002381 // Avoid increasing the max critical pressure in the scheduled region.
Andrew Trick13372882013-07-25 07:26:35 +00002382 if (tryPressure(TryCand.RPDelta.CriticalMax, Cand.RPDelta.CriticalMax,
2383 TryCand, Cand, RegCritical))
Andrew Trick3b87f622012-11-07 07:05:09 +00002384 return;
Andrew Trick3b87f622012-11-07 07:05:09 +00002385
Andrew Trick9b5caaa2012-11-12 19:40:10 +00002386 // Keep clustered nodes together to encourage downstream peephole
2387 // optimizations which may reduce resource requirements.
2388 //
2389 // This is a best effort to set things up for a post-RA pass. Optimizations
2390 // like generating loads of multiple registers should ideally be done within
2391 // the scheduler pass by combining the loads during DAG postprocessing.
2392 const SUnit *NextClusterSU =
2393 Zone.isTop() ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
2394 if (tryGreater(TryCand.SU == NextClusterSU, Cand.SU == NextClusterSU,
2395 TryCand, Cand, Cluster))
2396 return;
Andrew Tricke38afe12013-04-24 15:54:43 +00002397
2398 // Weak edges are for clustering and other constraints.
Andrew Trick9b5caaa2012-11-12 19:40:10 +00002399 if (tryLess(getWeakLeft(TryCand.SU, Zone.isTop()),
2400 getWeakLeft(Cand.SU, Zone.isTop()),
Andrew Tricke38afe12013-04-24 15:54:43 +00002401 TryCand, Cand, Weak)) {
Andrew Trick9b5caaa2012-11-12 19:40:10 +00002402 return;
2403 }
Andrew Tricka626f502013-06-17 21:45:13 +00002404 // Avoid increasing the max pressure of the entire region.
Andrew Trick13372882013-07-25 07:26:35 +00002405 if (tryPressure(TryCand.RPDelta.CurrentMax, Cand.RPDelta.CurrentMax,
2406 TryCand, Cand, RegMax))
Andrew Tricka626f502013-06-17 21:45:13 +00002407 return;
2408
Andrew Trick3b87f622012-11-07 07:05:09 +00002409 // Avoid critical resource consumption and balance the schedule.
2410 TryCand.initResourceDelta(DAG, SchedModel);
2411 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
2412 TryCand, Cand, ResourceReduce))
2413 return;
2414 if (tryGreater(TryCand.ResDelta.DemandedResources,
2415 Cand.ResDelta.DemandedResources,
2416 TryCand, Cand, ResourceDemand))
2417 return;
2418
2419 // Avoid serializing long latency dependence chains.
Andrew Trickea574332013-08-23 17:48:43 +00002420 // For acyclic path limited loops, latency was already checked above.
2421 if (Cand.Policy.ReduceLatency && !Rem.IsAcyclicLatencyLimited
2422 && tryLatency(TryCand, Cand, Zone)) {
2423 return;
Andrew Trick3b87f622012-11-07 07:05:09 +00002424 }
2425
Andrew Trick3b87f622012-11-07 07:05:09 +00002426 // Prefer immediate defs/users of the last scheduled instruction. This is a
Andrew Trickfa989e72013-06-15 05:39:19 +00002427 // local pressure avoidance strategy that also makes the machine code
2428 // readable.
Andrew Trick9b5caaa2012-11-12 19:40:10 +00002429 if (tryGreater(Zone.NextSUs.count(TryCand.SU), Zone.NextSUs.count(Cand.SU),
2430 TryCand, Cand, NextDefUse))
Andrew Trick3b87f622012-11-07 07:05:09 +00002431 return;
Andrew Trick9b5caaa2012-11-12 19:40:10 +00002432
Andrew Trick3b87f622012-11-07 07:05:09 +00002433 // Fall through to original instruction order.
2434 if ((Zone.isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
2435 || (!Zone.isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
2436 TryCand.Reason = NodeOrder;
2437 }
2438}
Andrew Trick28ebc892012-05-10 21:06:19 +00002439
Andrew Trick3b87f622012-11-07 07:05:09 +00002440#ifndef NDEBUG
2441const char *ConvergingScheduler::getReasonStr(
2442 ConvergingScheduler::CandReason Reason) {
2443 switch (Reason) {
2444 case NoCand: return "NOCAND ";
Andrew Trick4392f0f2013-04-13 06:07:40 +00002445 case PhysRegCopy: return "PREG-COPY";
Andrew Tricke52d5022013-06-17 21:45:05 +00002446 case RegExcess: return "REG-EXCESS";
2447 case RegCritical: return "REG-CRIT ";
Andrew Trick9b5caaa2012-11-12 19:40:10 +00002448 case Cluster: return "CLUSTER ";
Andrew Tricke38afe12013-04-24 15:54:43 +00002449 case Weak: return "WEAK ";
Andrew Tricka626f502013-06-17 21:45:13 +00002450 case RegMax: return "REG-MAX ";
Andrew Trick3b87f622012-11-07 07:05:09 +00002451 case ResourceReduce: return "RES-REDUCE";
2452 case ResourceDemand: return "RES-DEMAND";
2453 case TopDepthReduce: return "TOP-DEPTH ";
2454 case TopPathReduce: return "TOP-PATH ";
2455 case BotHeightReduce:return "BOT-HEIGHT";
2456 case BotPathReduce: return "BOT-PATH ";
2457 case NextDefUse: return "DEF-USE ";
2458 case NodeOrder: return "ORDER ";
2459 };
Benjamin Kramerb7546872012-11-09 15:45:22 +00002460 llvm_unreachable("Unknown reason!");
Andrew Trick3b87f622012-11-07 07:05:09 +00002461}
2462
Andrew Trick11189f72013-04-05 00:31:29 +00002463void ConvergingScheduler::traceCandidate(const SchedCandidate &Cand) {
Andrew Trick4c60b8a2013-08-30 03:49:48 +00002464 PressureChange P;
Andrew Trick3b87f622012-11-07 07:05:09 +00002465 unsigned ResIdx = 0;
2466 unsigned Latency = 0;
2467 switch (Cand.Reason) {
2468 default:
2469 break;
Andrew Tricke52d5022013-06-17 21:45:05 +00002470 case RegExcess:
Andrew Trick3b87f622012-11-07 07:05:09 +00002471 P = Cand.RPDelta.Excess;
2472 break;
Andrew Tricke52d5022013-06-17 21:45:05 +00002473 case RegCritical:
Andrew Trick3b87f622012-11-07 07:05:09 +00002474 P = Cand.RPDelta.CriticalMax;
2475 break;
Andrew Tricka626f502013-06-17 21:45:13 +00002476 case RegMax:
Andrew Trick3b87f622012-11-07 07:05:09 +00002477 P = Cand.RPDelta.CurrentMax;
2478 break;
2479 case ResourceReduce:
2480 ResIdx = Cand.Policy.ReduceResIdx;
2481 break;
2482 case ResourceDemand:
2483 ResIdx = Cand.Policy.DemandResIdx;
2484 break;
2485 case TopDepthReduce:
2486 Latency = Cand.SU->getDepth();
2487 break;
2488 case TopPathReduce:
2489 Latency = Cand.SU->getHeight();
2490 break;
2491 case BotHeightReduce:
2492 Latency = Cand.SU->getHeight();
2493 break;
2494 case BotPathReduce:
2495 Latency = Cand.SU->getDepth();
2496 break;
2497 }
Andrew Trick11189f72013-04-05 00:31:29 +00002498 dbgs() << " SU(" << Cand.SU->NodeNum << ") " << getReasonStr(Cand.Reason);
Andrew Trick3b87f622012-11-07 07:05:09 +00002499 if (P.isValid())
Andrew Trick4c60b8a2013-08-30 03:49:48 +00002500 dbgs() << " " << TRI->getRegPressureSetName(P.getPSet())
2501 << ":" << P.getUnitInc() << " ";
Andrew Trick3b87f622012-11-07 07:05:09 +00002502 else
Andrew Trick11189f72013-04-05 00:31:29 +00002503 dbgs() << " ";
Andrew Trick3b87f622012-11-07 07:05:09 +00002504 if (ResIdx)
Andrew Trick11189f72013-04-05 00:31:29 +00002505 dbgs() << " " << SchedModel->getProcResource(ResIdx)->Name << " ";
Andrew Trick3b87f622012-11-07 07:05:09 +00002506 else
2507 dbgs() << " ";
Andrew Trick11189f72013-04-05 00:31:29 +00002508 if (Latency)
2509 dbgs() << " " << Latency << " cycles ";
2510 else
2511 dbgs() << " ";
2512 dbgs() << '\n';
Andrew Trick3b87f622012-11-07 07:05:09 +00002513}
2514#endif
2515
Andrew Trick7196a8f2012-05-10 21:06:16 +00002516/// Pick the best candidate from the top queue.
2517///
2518/// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
2519/// DAG building. To adjust for the current scheduling location we need to
2520/// maintain the number of vreg uses remaining to be top-scheduled.
Andrew Trick3b87f622012-11-07 07:05:09 +00002521void ConvergingScheduler::pickNodeFromQueue(SchedBoundary &Zone,
2522 const RegPressureTracker &RPTracker,
2523 SchedCandidate &Cand) {
2524 ReadyQueue &Q = Zone.Available;
2525
Andrew Trickf3234242012-05-24 22:11:12 +00002526 DEBUG(Q.dump());
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002527
Andrew Trick7196a8f2012-05-10 21:06:16 +00002528 // getMaxPressureDelta temporarily modifies the tracker.
2529 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
2530
Andrew Trick8c2d9212012-05-24 22:11:03 +00002531 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
Andrew Trick7196a8f2012-05-10 21:06:16 +00002532
Andrew Trick3b87f622012-11-07 07:05:09 +00002533 SchedCandidate TryCand(Cand.Policy);
2534 TryCand.SU = *I;
2535 tryCandidate(Cand, TryCand, Zone, RPTracker, TempTracker);
2536 if (TryCand.Reason != NoCand) {
2537 // Initialize resource delta if needed in case future heuristics query it.
2538 if (TryCand.ResDelta == SchedResourceDelta())
2539 TryCand.initResourceDelta(DAG, SchedModel);
2540 Cand.setBest(TryCand);
Andrew Trick11189f72013-04-05 00:31:29 +00002541 DEBUG(traceCandidate(Cand));
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002542 }
Andrew Trick7196a8f2012-05-10 21:06:16 +00002543 }
Andrew Trick3b87f622012-11-07 07:05:09 +00002544}
2545
2546static void tracePick(const ConvergingScheduler::SchedCandidate &Cand,
2547 bool IsTop) {
Andrew Trickbaedcd72013-04-13 06:07:49 +00002548 DEBUG(dbgs() << "Pick " << (IsTop ? "Top " : "Bot ")
Andrew Trick3b87f622012-11-07 07:05:09 +00002549 << ConvergingScheduler::getReasonStr(Cand.Reason) << '\n');
Andrew Trick7196a8f2012-05-10 21:06:16 +00002550}
2551
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002552/// Pick the best candidate node from either the top or bottom queue.
Andrew Trick3b87f622012-11-07 07:05:09 +00002553SUnit *ConvergingScheduler::pickNodeBidirectional(bool &IsTopNode) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002554 // Schedule as far as possible in the direction of no choice. This is most
2555 // efficient, but also provides the best heuristics for CriticalPSets.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002556 if (SUnit *SU = Bot.pickOnlyChoice()) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002557 IsTopNode = false;
Andrew Trickfa989e72013-06-15 05:39:19 +00002558 DEBUG(dbgs() << "Pick Bot NOCAND\n");
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002559 return SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002560 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002561 if (SUnit *SU = Top.pickOnlyChoice()) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002562 IsTopNode = true;
Andrew Trickfa989e72013-06-15 05:39:19 +00002563 DEBUG(dbgs() << "Pick Top NOCAND\n");
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002564 return SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002565 }
Andrew Trick3b87f622012-11-07 07:05:09 +00002566 CandPolicy NoPolicy;
2567 SchedCandidate BotCand(NoPolicy);
2568 SchedCandidate TopCand(NoPolicy);
Andrew Trickfa989e72013-06-15 05:39:19 +00002569 Bot.setPolicy(BotCand.Policy, Top);
2570 Top.setPolicy(TopCand.Policy, Bot);
Andrew Trick3b87f622012-11-07 07:05:09 +00002571
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002572 // Prefer bottom scheduling when heuristics are silent.
Andrew Trick3b87f622012-11-07 07:05:09 +00002573 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
2574 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002575
2576 // If either Q has a single candidate that provides the least increase in
2577 // Excess pressure, we can immediately schedule from that Q.
2578 //
2579 // RegionCriticalPSets summarizes the pressure within the scheduled region and
2580 // affects picking from either Q. If scheduling in one direction must
2581 // increase pressure for one of the excess PSets, then schedule in that
2582 // direction first to provide more freedom in the other direction.
Andrew Tricke52d5022013-06-17 21:45:05 +00002583 if ((BotCand.Reason == RegExcess && !BotCand.isRepeat(RegExcess))
2584 || (BotCand.Reason == RegCritical
2585 && !BotCand.isRepeat(RegCritical)))
2586 {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002587 IsTopNode = false;
Andrew Trick3b87f622012-11-07 07:05:09 +00002588 tracePick(BotCand, IsTopNode);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002589 return BotCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002590 }
2591 // Check if the top Q has a better candidate.
Andrew Trick3b87f622012-11-07 07:05:09 +00002592 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
2593 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002594
Andrew Tricke52d5022013-06-17 21:45:05 +00002595 // Choose the queue with the most important (lowest enum) reason.
Andrew Trick3b87f622012-11-07 07:05:09 +00002596 if (TopCand.Reason < BotCand.Reason) {
2597 IsTopNode = true;
2598 tracePick(TopCand, IsTopNode);
2599 return TopCand.SU;
2600 }
Andrew Tricke52d5022013-06-17 21:45:05 +00002601 // Otherwise prefer the bottom candidate, in node order if all else failed.
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002602 IsTopNode = false;
Andrew Trick3b87f622012-11-07 07:05:09 +00002603 tracePick(BotCand, IsTopNode);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002604 return BotCand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00002605}
2606
2607/// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
Andrew Trick7196a8f2012-05-10 21:06:16 +00002608SUnit *ConvergingScheduler::pickNode(bool &IsTopNode) {
2609 if (DAG->top() == DAG->bottom()) {
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002610 assert(Top.Available.empty() && Top.Pending.empty() &&
2611 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
Andrew Trick7196a8f2012-05-10 21:06:16 +00002612 return NULL;
2613 }
Andrew Trick7196a8f2012-05-10 21:06:16 +00002614 SUnit *SU;
Andrew Trick30c6ec22012-10-08 18:53:53 +00002615 do {
2616 if (ForceTopDown) {
2617 SU = Top.pickOnlyChoice();
2618 if (!SU) {
Andrew Trick3b87f622012-11-07 07:05:09 +00002619 CandPolicy NoPolicy;
2620 SchedCandidate TopCand(NoPolicy);
2621 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
2622 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick30c6ec22012-10-08 18:53:53 +00002623 SU = TopCand.SU;
2624 }
2625 IsTopNode = true;
Andrew Trick8ddd9d52012-05-24 23:11:17 +00002626 }
Andrew Trick30c6ec22012-10-08 18:53:53 +00002627 else if (ForceBottomUp) {
2628 SU = Bot.pickOnlyChoice();
2629 if (!SU) {
Andrew Trick3b87f622012-11-07 07:05:09 +00002630 CandPolicy NoPolicy;
2631 SchedCandidate BotCand(NoPolicy);
2632 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
2633 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick30c6ec22012-10-08 18:53:53 +00002634 SU = BotCand.SU;
2635 }
2636 IsTopNode = false;
Andrew Trick8ddd9d52012-05-24 23:11:17 +00002637 }
Andrew Trick30c6ec22012-10-08 18:53:53 +00002638 else {
Andrew Trick3b87f622012-11-07 07:05:09 +00002639 SU = pickNodeBidirectional(IsTopNode);
Andrew Trick30c6ec22012-10-08 18:53:53 +00002640 }
2641 } while (SU->isScheduled);
2642
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002643 if (SU->isTopReady())
2644 Top.removeReady(SU);
2645 if (SU->isBottomReady())
2646 Bot.removeReady(SU);
Andrew Trickc7a098f2012-05-25 02:02:39 +00002647
Andrew Trickbaedcd72013-04-13 06:07:49 +00002648 DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " << *SU->getInstr());
Andrew Trick7196a8f2012-05-10 21:06:16 +00002649 return SU;
2650}
2651
Andrew Trick4392f0f2013-04-13 06:07:40 +00002652void ConvergingScheduler::reschedulePhysRegCopies(SUnit *SU, bool isTop) {
2653
2654 MachineBasicBlock::iterator InsertPos = SU->getInstr();
2655 if (!isTop)
2656 ++InsertPos;
2657 SmallVectorImpl<SDep> &Deps = isTop ? SU->Preds : SU->Succs;
2658
2659 // Find already scheduled copies with a single physreg dependence and move
2660 // them just above the scheduled instruction.
2661 for (SmallVectorImpl<SDep>::iterator I = Deps.begin(), E = Deps.end();
2662 I != E; ++I) {
2663 if (I->getKind() != SDep::Data || !TRI->isPhysicalRegister(I->getReg()))
2664 continue;
2665 SUnit *DepSU = I->getSUnit();
2666 if (isTop ? DepSU->Succs.size() > 1 : DepSU->Preds.size() > 1)
2667 continue;
2668 MachineInstr *Copy = DepSU->getInstr();
2669 if (!Copy->isCopy())
2670 continue;
2671 DEBUG(dbgs() << " Rescheduling physreg copy ";
2672 I->getSUnit()->dump(DAG));
2673 DAG->moveInstruction(Copy, InsertPos);
2674 }
2675}
2676
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002677/// Update the scheduler's state after scheduling a node. This is the same node
2678/// that was just returned by pickNode(). However, ScheduleDAGMI needs to update
Andrew Trickb7e02892012-06-05 21:11:27 +00002679/// it's state based on the current cycle before MachineSchedStrategy does.
Andrew Trick4392f0f2013-04-13 06:07:40 +00002680///
2681/// FIXME: Eventually, we may bundle physreg copies rather than rescheduling
2682/// them here. See comments in biasPhysRegCopy.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002683void ConvergingScheduler::schedNode(SUnit *SU, bool IsTopNode) {
Andrew Trickb7e02892012-06-05 21:11:27 +00002684 if (IsTopNode) {
Andrew Trickfa989e72013-06-15 05:39:19 +00002685 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.CurrCycle);
Andrew Trick7f8c74c2012-06-29 03:23:22 +00002686 Top.bumpNode(SU);
Andrew Trick4392f0f2013-04-13 06:07:40 +00002687 if (SU->hasPhysRegUses)
2688 reschedulePhysRegCopies(SU, true);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002689 }
Andrew Trickb7e02892012-06-05 21:11:27 +00002690 else {
Andrew Trickfa989e72013-06-15 05:39:19 +00002691 SU->BotReadyCycle = std::max(SU->BotReadyCycle, Bot.CurrCycle);
Andrew Trick7f8c74c2012-06-29 03:23:22 +00002692 Bot.bumpNode(SU);
Andrew Trick4392f0f2013-04-13 06:07:40 +00002693 if (SU->hasPhysRegDefs)
2694 reschedulePhysRegCopies(SU, false);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002695 }
2696}
2697
Andrew Trick17d35e52012-03-14 04:00:41 +00002698/// Create the standard converging machine scheduler. This will be used as the
2699/// default scheduler if the target does not set a default.
2700static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C) {
Benjamin Kramer689e0b42012-03-14 11:26:37 +00002701 assert((!ForceTopDown || !ForceBottomUp) &&
Andrew Trick17d35e52012-03-14 04:00:41 +00002702 "-misched-topdown incompatible with -misched-bottomup");
Andrew Trick9b5caaa2012-11-12 19:40:10 +00002703 ScheduleDAGMI *DAG = new ScheduleDAGMI(C, new ConvergingScheduler());
2704 // Register DAG post-processors.
Andrew Tricke38afe12013-04-24 15:54:43 +00002705 //
2706 // FIXME: extend the mutation API to allow earlier mutations to instantiate
2707 // data and pass it to later mutations. Have a single mutation that gathers
2708 // the interesting nodes in one pass.
Andrew Trick63a8d822013-06-15 04:49:46 +00002709 DAG->addMutation(new CopyConstrain(DAG->TII, DAG->TRI));
Andrew Trick9b5caaa2012-11-12 19:40:10 +00002710 if (EnableLoadCluster)
2711 DAG->addMutation(new LoadClusterMutation(DAG->TII, DAG->TRI));
Andrew Trick6996fd02012-11-12 19:52:20 +00002712 if (EnableMacroFusion)
2713 DAG->addMutation(new MacroFusion(DAG->TII));
Andrew Trick9b5caaa2012-11-12 19:40:10 +00002714 return DAG;
Andrew Trick42b7a712012-01-17 06:55:03 +00002715}
2716static MachineSchedRegistry
Andrew Trick17d35e52012-03-14 04:00:41 +00002717ConvergingSchedRegistry("converge", "Standard converging scheduler.",
2718 createConvergingSched);
Andrew Trick42b7a712012-01-17 06:55:03 +00002719
2720//===----------------------------------------------------------------------===//
Andrew Trick1e94e982012-10-15 18:02:27 +00002721// ILP Scheduler. Currently for experimental analysis of heuristics.
2722//===----------------------------------------------------------------------===//
2723
2724namespace {
2725/// \brief Order nodes by the ILP metric.
2726struct ILPOrder {
Andrew Trick178f7d02013-01-25 04:01:04 +00002727 const SchedDFSResult *DFSResult;
2728 const BitVector *ScheduledTrees;
Andrew Trick1e94e982012-10-15 18:02:27 +00002729 bool MaximizeILP;
2730
Andrew Trick178f7d02013-01-25 04:01:04 +00002731 ILPOrder(bool MaxILP): DFSResult(0), ScheduledTrees(0), MaximizeILP(MaxILP) {}
Andrew Trick1e94e982012-10-15 18:02:27 +00002732
2733 /// \brief Apply a less-than relation on node priority.
Andrew Trick8b1496c2012-11-28 05:13:28 +00002734 ///
2735 /// (Return true if A comes after B in the Q.)
Andrew Trick1e94e982012-10-15 18:02:27 +00002736 bool operator()(const SUnit *A, const SUnit *B) const {
Andrew Trick8b1496c2012-11-28 05:13:28 +00002737 unsigned SchedTreeA = DFSResult->getSubtreeID(A);
2738 unsigned SchedTreeB = DFSResult->getSubtreeID(B);
2739 if (SchedTreeA != SchedTreeB) {
2740 // Unscheduled trees have lower priority.
2741 if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
2742 return ScheduledTrees->test(SchedTreeB);
2743
2744 // Trees with shallower connections have have lower priority.
2745 if (DFSResult->getSubtreeLevel(SchedTreeA)
2746 != DFSResult->getSubtreeLevel(SchedTreeB)) {
2747 return DFSResult->getSubtreeLevel(SchedTreeA)
2748 < DFSResult->getSubtreeLevel(SchedTreeB);
2749 }
2750 }
Andrew Trick1e94e982012-10-15 18:02:27 +00002751 if (MaximizeILP)
Andrew Trick8b1496c2012-11-28 05:13:28 +00002752 return DFSResult->getILP(A) < DFSResult->getILP(B);
Andrew Trick1e94e982012-10-15 18:02:27 +00002753 else
Andrew Trick8b1496c2012-11-28 05:13:28 +00002754 return DFSResult->getILP(A) > DFSResult->getILP(B);
Andrew Trick1e94e982012-10-15 18:02:27 +00002755 }
2756};
2757
2758/// \brief Schedule based on the ILP metric.
2759class ILPScheduler : public MachineSchedStrategy {
Andrew Trick8b1496c2012-11-28 05:13:28 +00002760 /// In case all subtrees are eventually connected to a common root through
2761 /// data dependence (e.g. reduction), place an upper limit on their size.
2762 ///
2763 /// FIXME: A subtree limit is generally good, but in the situation commented
2764 /// above, where multiple similar subtrees feed a common root, we should
2765 /// only split at a point where the resulting subtrees will be balanced.
2766 /// (a motivating test case must be found).
2767 static const unsigned SubtreeLimit = 16;
2768
Andrew Trick178f7d02013-01-25 04:01:04 +00002769 ScheduleDAGMI *DAG;
Andrew Trick1e94e982012-10-15 18:02:27 +00002770 ILPOrder Cmp;
2771
2772 std::vector<SUnit*> ReadyQ;
2773public:
Andrew Trick178f7d02013-01-25 04:01:04 +00002774 ILPScheduler(bool MaximizeILP): DAG(0), Cmp(MaximizeILP) {}
Andrew Trick1e94e982012-10-15 18:02:27 +00002775
Andrew Trick178f7d02013-01-25 04:01:04 +00002776 virtual void initialize(ScheduleDAGMI *dag) {
2777 DAG = dag;
Andrew Trick4e1fb182013-01-25 06:33:57 +00002778 DAG->computeDFSResult();
Andrew Trick178f7d02013-01-25 04:01:04 +00002779 Cmp.DFSResult = DAG->getDFSResult();
2780 Cmp.ScheduledTrees = &DAG->getScheduledTrees();
Andrew Trick1e94e982012-10-15 18:02:27 +00002781 ReadyQ.clear();
Andrew Trick1e94e982012-10-15 18:02:27 +00002782 }
2783
2784 virtual void registerRoots() {
Benjamin Kramer5175fd92012-11-29 14:36:26 +00002785 // Restore the heap in ReadyQ with the updated DFS results.
2786 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
Andrew Trick1e94e982012-10-15 18:02:27 +00002787 }
2788
2789 /// Implement MachineSchedStrategy interface.
2790 /// -----------------------------------------
2791
Andrew Trick8b1496c2012-11-28 05:13:28 +00002792 /// Callback to select the highest priority node from the ready Q.
Andrew Trick1e94e982012-10-15 18:02:27 +00002793 virtual SUnit *pickNode(bool &IsTopNode) {
2794 if (ReadyQ.empty()) return NULL;
Matt Arsenault26c417b2013-03-21 00:57:21 +00002795 std::pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
Andrew Trick1e94e982012-10-15 18:02:27 +00002796 SUnit *SU = ReadyQ.back();
2797 ReadyQ.pop_back();
2798 IsTopNode = false;
Andrew Trickbaedcd72013-04-13 06:07:49 +00002799 DEBUG(dbgs() << "Pick node " << "SU(" << SU->NodeNum << ") "
Andrew Trick178f7d02013-01-25 04:01:04 +00002800 << " ILP: " << DAG->getDFSResult()->getILP(SU)
2801 << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU) << " @"
2802 << DAG->getDFSResult()->getSubtreeLevel(
Andrew Trickbaedcd72013-04-13 06:07:49 +00002803 DAG->getDFSResult()->getSubtreeID(SU)) << '\n'
2804 << "Scheduling " << *SU->getInstr());
Andrew Trick1e94e982012-10-15 18:02:27 +00002805 return SU;
2806 }
2807
Andrew Trick178f7d02013-01-25 04:01:04 +00002808 /// \brief Scheduler callback to notify that a new subtree is scheduled.
2809 virtual void scheduleTree(unsigned SubtreeID) {
2810 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2811 }
2812
Andrew Trick8b1496c2012-11-28 05:13:28 +00002813 /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
2814 /// DFSResults, and resort the priority Q.
2815 virtual void schedNode(SUnit *SU, bool IsTopNode) {
2816 assert(!IsTopNode && "SchedDFSResult needs bottom-up");
Andrew Trick8b1496c2012-11-28 05:13:28 +00002817 }
Andrew Trick1e94e982012-10-15 18:02:27 +00002818
2819 virtual void releaseTopNode(SUnit *) { /*only called for top roots*/ }
2820
2821 virtual void releaseBottomNode(SUnit *SU) {
2822 ReadyQ.push_back(SU);
2823 std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2824 }
2825};
2826} // namespace
2827
2828static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
2829 return new ScheduleDAGMI(C, new ILPScheduler(true));
2830}
2831static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
2832 return new ScheduleDAGMI(C, new ILPScheduler(false));
2833}
2834static MachineSchedRegistry ILPMaxRegistry(
2835 "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
2836static MachineSchedRegistry ILPMinRegistry(
2837 "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
2838
2839//===----------------------------------------------------------------------===//
Andrew Trick5edf2f02012-01-14 02:17:06 +00002840// Machine Instruction Shuffler for Correctness Testing
2841//===----------------------------------------------------------------------===//
2842
Andrew Trick96f678f2012-01-13 06:30:30 +00002843#ifndef NDEBUG
2844namespace {
Andrew Trick17d35e52012-03-14 04:00:41 +00002845/// Apply a less-than relation on the node order, which corresponds to the
2846/// instruction order prior to scheduling. IsReverse implements greater-than.
2847template<bool IsReverse>
2848struct SUnitOrder {
Andrew Trickc6cf11b2012-01-17 06:55:07 +00002849 bool operator()(SUnit *A, SUnit *B) const {
Andrew Trick17d35e52012-03-14 04:00:41 +00002850 if (IsReverse)
2851 return A->NodeNum > B->NodeNum;
2852 else
2853 return A->NodeNum < B->NodeNum;
Andrew Trickc6cf11b2012-01-17 06:55:07 +00002854 }
2855};
2856
Andrew Trick96f678f2012-01-13 06:30:30 +00002857/// Reorder instructions as much as possible.
Andrew Trick17d35e52012-03-14 04:00:41 +00002858class InstructionShuffler : public MachineSchedStrategy {
2859 bool IsAlternating;
2860 bool IsTopDown;
2861
2862 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
2863 // gives nodes with a higher number higher priority causing the latest
2864 // instructions to be scheduled first.
2865 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
2866 TopQ;
2867 // When scheduling bottom-up, use greater-than as the queue priority.
2868 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
2869 BottomQ;
Andrew Trick96f678f2012-01-13 06:30:30 +00002870public:
Andrew Trick17d35e52012-03-14 04:00:41 +00002871 InstructionShuffler(bool alternate, bool topdown)
2872 : IsAlternating(alternate), IsTopDown(topdown) {}
Andrew Trick96f678f2012-01-13 06:30:30 +00002873
Andrew Trick17d35e52012-03-14 04:00:41 +00002874 virtual void initialize(ScheduleDAGMI *) {
2875 TopQ.clear();
2876 BottomQ.clear();
2877 }
Andrew Trickc6cf11b2012-01-17 06:55:07 +00002878
Andrew Trick17d35e52012-03-14 04:00:41 +00002879 /// Implement MachineSchedStrategy interface.
2880 /// -----------------------------------------
2881
2882 virtual SUnit *pickNode(bool &IsTopNode) {
2883 SUnit *SU;
2884 if (IsTopDown) {
2885 do {
2886 if (TopQ.empty()) return NULL;
2887 SU = TopQ.top();
2888 TopQ.pop();
2889 } while (SU->isScheduled);
2890 IsTopNode = true;
2891 }
2892 else {
2893 do {
2894 if (BottomQ.empty()) return NULL;
2895 SU = BottomQ.top();
2896 BottomQ.pop();
2897 } while (SU->isScheduled);
2898 IsTopNode = false;
2899 }
2900 if (IsAlternating)
2901 IsTopDown = !IsTopDown;
Andrew Trickc6cf11b2012-01-17 06:55:07 +00002902 return SU;
2903 }
2904
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002905 virtual void schedNode(SUnit *SU, bool IsTopNode) {}
2906
Andrew Trick17d35e52012-03-14 04:00:41 +00002907 virtual void releaseTopNode(SUnit *SU) {
2908 TopQ.push(SU);
2909 }
2910 virtual void releaseBottomNode(SUnit *SU) {
2911 BottomQ.push(SU);
Andrew Trick96f678f2012-01-13 06:30:30 +00002912 }
2913};
2914} // namespace
2915
Andrew Trickc174eaf2012-03-08 01:41:12 +00002916static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
Andrew Trick17d35e52012-03-14 04:00:41 +00002917 bool Alternate = !ForceTopDown && !ForceBottomUp;
2918 bool TopDown = !ForceBottomUp;
Benjamin Kramer689e0b42012-03-14 11:26:37 +00002919 assert((TopDown || !ForceTopDown) &&
Andrew Trick17d35e52012-03-14 04:00:41 +00002920 "-misched-topdown incompatible with -misched-bottomup");
2921 return new ScheduleDAGMI(C, new InstructionShuffler(Alternate, TopDown));
Andrew Trick96f678f2012-01-13 06:30:30 +00002922}
Andrew Trick17d35e52012-03-14 04:00:41 +00002923static MachineSchedRegistry ShufflerRegistry(
2924 "shuffle", "Shuffle machine instructions alternating directions",
2925 createInstructionShuffler);
Andrew Trick96f678f2012-01-13 06:30:30 +00002926#endif // !NDEBUG
Andrew Trick30849792013-01-25 07:45:29 +00002927
2928//===----------------------------------------------------------------------===//
2929// GraphWriter support for ScheduleDAGMI.
2930//===----------------------------------------------------------------------===//
2931
2932#ifndef NDEBUG
2933namespace llvm {
2934
2935template<> struct GraphTraits<
2936 ScheduleDAGMI*> : public GraphTraits<ScheduleDAG*> {};
2937
2938template<>
2939struct DOTGraphTraits<ScheduleDAGMI*> : public DefaultDOTGraphTraits {
2940
2941 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
2942
2943 static std::string getGraphName(const ScheduleDAG *G) {
2944 return G->MF.getName();
2945 }
2946
2947 static bool renderGraphFromBottomUp() {
2948 return true;
2949 }
2950
2951 static bool isNodeHidden(const SUnit *Node) {
2952 return (Node->NumPreds > 10 || Node->NumSuccs > 10);
2953 }
2954
2955 static bool hasNodeAddressLabel(const SUnit *Node,
2956 const ScheduleDAG *Graph) {
2957 return false;
2958 }
2959
2960 /// If you want to override the dot attributes printed for a particular
2961 /// edge, override this method.
2962 static std::string getEdgeAttributes(const SUnit *Node,
2963 SUnitIterator EI,
2964 const ScheduleDAG *Graph) {
2965 if (EI.isArtificialDep())
2966 return "color=cyan,style=dashed";
2967 if (EI.isCtrlDep())
2968 return "color=blue,style=dashed";
2969 return "";
2970 }
2971
2972 static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) {
2973 std::string Str;
2974 raw_string_ostream SS(Str);
2975 SS << "SU(" << SU->NodeNum << ')';
2976 return SS.str();
2977 }
2978 static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G) {
2979 return G->getGraphNodeLabel(SU);
2980 }
2981
2982 static std::string getNodeAttributes(const SUnit *N,
2983 const ScheduleDAG *Graph) {
2984 std::string Str("shape=Mrecord");
2985 const SchedDFSResult *DFS =
2986 static_cast<const ScheduleDAGMI*>(Graph)->getDFSResult();
2987 if (DFS) {
2988 Str += ",style=filled,fillcolor=\"#";
2989 Str += DOT::getColorString(DFS->getSubtreeID(N));
2990 Str += '"';
2991 }
2992 return Str;
2993 }
2994};
2995} // namespace llvm
2996#endif // NDEBUG
2997
2998/// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
2999/// rendered using 'dot'.
3000///
3001void ScheduleDAGMI::viewGraph(const Twine &Name, const Twine &Title) {
3002#ifndef NDEBUG
3003 ViewGraph(this, Name, false, Title);
3004#else
3005 errs() << "ScheduleDAGMI::viewGraph is only available in debug builds on "
3006 << "systems with Graphviz or gv!\n";
3007#endif // NDEBUG
3008}
3009
3010/// Out-of-line implementation with no arguments is handy for gdb.
3011void ScheduleDAGMI::viewGraph() {
3012 viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName());
3013}