blob: f99fc72e75b74064224c6eb7cdf1147b0f59c9b3 [file] [log] [blame]
Andrew Trick6a50baa2012-05-17 22:37:09 +00001//===- MachineScheduler.cpp - Machine Instruction Scheduler ---------------===//
Andrew Tricke77e84e2012-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 Trick02a80da2012-03-08 01:41:12 +000017#include "llvm/CodeGen/MachineScheduler.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/PriorityQueue.h"
19#include "llvm/Analysis/AliasAnalysis.h"
20#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Jakub Staszakdf17ddd2013-03-10 13:11:23 +000021#include "llvm/CodeGen/MachineDominators.h"
22#include "llvm/CodeGen/MachineLoopInfo.h"
Andrew Trick736dd9a2013-06-21 18:32:58 +000023#include "llvm/CodeGen/MachineRegisterInfo.h"
Andrew Tricke77e84e2012-01-13 06:30:30 +000024#include "llvm/CodeGen/Passes.h"
Andrew Trick05ff4662012-06-06 20:29:31 +000025#include "llvm/CodeGen/RegisterClassInfo.h"
Andrew Trickcd1c2f92012-11-28 05:13:24 +000026#include "llvm/CodeGen/ScheduleDFS.h"
Andrew Trick61f1a272012-05-24 22:11:09 +000027#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
Andrew Tricke77e84e2012-01-13 06:30:30 +000028#include "llvm/Support/CommandLine.h"
29#include "llvm/Support/Debug.h"
30#include "llvm/Support/ErrorHandling.h"
Andrew Trickea9fd952013-01-25 07:45:29 +000031#include "llvm/Support/GraphWriter.h"
Andrew Tricke77e84e2012-01-13 06:30:30 +000032#include "llvm/Support/raw_ostream.h"
Jakub Staszak80df8b82013-06-14 00:00:13 +000033#include "llvm/Target/TargetInstrInfo.h"
Andrew Trick7ccdc5c2012-01-17 06:55:07 +000034#include <queue>
35
Andrew Tricke77e84e2012-01-13 06:30:30 +000036using namespace llvm;
37
Andrew Trick7a8e1002012-09-11 00:39:15 +000038namespace llvm {
39cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
40 cl::desc("Force top-down list scheduling"));
41cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
42 cl::desc("Force bottom-up list scheduling"));
43}
Andrew Trick8823dec2012-03-14 04:00:41 +000044
Andrew Tricka5f19562012-03-07 00:18:25 +000045#ifndef NDEBUG
46static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
47 cl::desc("Pop up a window to show MISched dags after they are processed"));
Lang Hamesdd98c492012-03-19 18:38:38 +000048
49static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
50 cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
Andrew Trick33e05d72013-12-28 21:57:02 +000051
52static cl::opt<std::string> SchedOnlyFunc("misched-only-func", cl::Hidden,
53 cl::desc("Only schedule this function"));
54static cl::opt<unsigned> SchedOnlyBlock("misched-only-block", cl::Hidden,
55 cl::desc("Only schedule this MBB#"));
Andrew Tricka5f19562012-03-07 00:18:25 +000056#else
57static bool ViewMISchedDAGs = false;
58#endif // NDEBUG
59
Andrew Trickb6e74712013-09-04 20:59:59 +000060static cl::opt<bool> EnableRegPressure("misched-regpressure", cl::Hidden,
61 cl::desc("Enable register pressure scheduling."), cl::init(true));
62
Andrew Trickc01b0042013-08-23 17:48:43 +000063static cl::opt<bool> EnableCyclicPath("misched-cyclicpath", cl::Hidden,
Andrew Trick6c88b352013-09-09 23:31:14 +000064 cl::desc("Enable cyclic critical path analysis."), cl::init(true));
Andrew Trickc01b0042013-08-23 17:48:43 +000065
Andrew Tricka7714a02012-11-12 19:40:10 +000066static cl::opt<bool> EnableLoadCluster("misched-cluster", cl::Hidden,
Andrew Trick108c88c2012-11-13 08:47:29 +000067 cl::desc("Enable load clustering."), cl::init(true));
Andrew Tricka7714a02012-11-12 19:40:10 +000068
Andrew Trick263280242012-11-12 19:52:20 +000069// Experimental heuristics
70static cl::opt<bool> EnableMacroFusion("misched-fusion", cl::Hidden,
Andrew Trick108c88c2012-11-13 08:47:29 +000071 cl::desc("Enable scheduling for macro fusion."), cl::init(true));
Andrew Trick263280242012-11-12 19:52:20 +000072
Andrew Trick48f2a722013-03-08 05:40:34 +000073static cl::opt<bool> VerifyScheduling("verify-misched", cl::Hidden,
74 cl::desc("Verify machine instrs before and after machine scheduling"));
75
Andrew Trick44f750a2013-01-25 04:01:04 +000076// DAG subtrees must have at least this many nodes.
77static const unsigned MinSubtreeSize = 8;
78
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +000079// Pin the vtables to this file.
80void MachineSchedStrategy::anchor() {}
81void ScheduleDAGMutation::anchor() {}
82
Andrew Trick63440872012-01-14 02:17:06 +000083//===----------------------------------------------------------------------===//
84// Machine Instruction Scheduling Pass and Registry
85//===----------------------------------------------------------------------===//
86
Andrew Trick4d4b5462012-04-24 20:36:19 +000087MachineSchedContext::MachineSchedContext():
88 MF(0), MLI(0), MDT(0), PassConfig(0), AA(0), LIS(0) {
89 RegClassInfo = new RegisterClassInfo();
90}
91
92MachineSchedContext::~MachineSchedContext() {
93 delete RegClassInfo;
94}
95
Andrew Tricke77e84e2012-01-13 06:30:30 +000096namespace {
Andrew Trickd7f890e2013-12-28 21:56:47 +000097/// Base class for a machine scheduler class that can run at any point.
98class MachineSchedulerBase : public MachineSchedContext,
99 public MachineFunctionPass {
100public:
101 MachineSchedulerBase(char &ID): MachineFunctionPass(ID) {}
102
Craig Topper4584cd52014-03-07 09:26:03 +0000103 void print(raw_ostream &O, const Module* = 0) const override;
Andrew Trickd7f890e2013-12-28 21:56:47 +0000104
105protected:
106 void scheduleRegions(ScheduleDAGInstrs &Scheduler);
107};
108
Andrew Tricke1c034f2012-01-17 06:55:03 +0000109/// MachineScheduler runs after coalescing and before register allocation.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000110class MachineScheduler : public MachineSchedulerBase {
Andrew Tricke77e84e2012-01-13 06:30:30 +0000111public:
Andrew Tricke1c034f2012-01-17 06:55:03 +0000112 MachineScheduler();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000113
Craig Topper4584cd52014-03-07 09:26:03 +0000114 void getAnalysisUsage(AnalysisUsage &AU) const override;
Andrew Tricke77e84e2012-01-13 06:30:30 +0000115
Craig Topper4584cd52014-03-07 09:26:03 +0000116 bool runOnMachineFunction(MachineFunction&) override;
Andrew Tricke77e84e2012-01-13 06:30:30 +0000117
Andrew Tricke77e84e2012-01-13 06:30:30 +0000118 static char ID; // Class identification, replacement for typeinfo
Andrew Trick978674b2013-09-20 05:14:41 +0000119
120protected:
121 ScheduleDAGInstrs *createMachineScheduler();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000122};
Andrew Trick17080b92013-12-28 21:56:51 +0000123
124/// PostMachineScheduler runs after shortly before code emission.
125class PostMachineScheduler : public MachineSchedulerBase {
126public:
127 PostMachineScheduler();
128
Craig Topper4584cd52014-03-07 09:26:03 +0000129 void getAnalysisUsage(AnalysisUsage &AU) const override;
Andrew Trick17080b92013-12-28 21:56:51 +0000130
Craig Topper4584cd52014-03-07 09:26:03 +0000131 bool runOnMachineFunction(MachineFunction&) override;
Andrew Trick17080b92013-12-28 21:56:51 +0000132
133 static char ID; // Class identification, replacement for typeinfo
134
135protected:
136 ScheduleDAGInstrs *createPostMachineScheduler();
137};
Andrew Tricke77e84e2012-01-13 06:30:30 +0000138} // namespace
139
Andrew Tricke1c034f2012-01-17 06:55:03 +0000140char MachineScheduler::ID = 0;
Andrew Tricke77e84e2012-01-13 06:30:30 +0000141
Andrew Tricke1c034f2012-01-17 06:55:03 +0000142char &llvm::MachineSchedulerID = MachineScheduler::ID;
Andrew Tricke77e84e2012-01-13 06:30:30 +0000143
Andrew Tricke1c034f2012-01-17 06:55:03 +0000144INITIALIZE_PASS_BEGIN(MachineScheduler, "misched",
Andrew Tricke77e84e2012-01-13 06:30:30 +0000145 "Machine Instruction Scheduler", false, false)
146INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
147INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
148INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
Andrew Tricke1c034f2012-01-17 06:55:03 +0000149INITIALIZE_PASS_END(MachineScheduler, "misched",
Andrew Tricke77e84e2012-01-13 06:30:30 +0000150 "Machine Instruction Scheduler", false, false)
151
Andrew Tricke1c034f2012-01-17 06:55:03 +0000152MachineScheduler::MachineScheduler()
Andrew Trickd7f890e2013-12-28 21:56:47 +0000153: MachineSchedulerBase(ID) {
Andrew Tricke1c034f2012-01-17 06:55:03 +0000154 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Andrew Tricke77e84e2012-01-13 06:30:30 +0000155}
156
Andrew Tricke1c034f2012-01-17 06:55:03 +0000157void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
Andrew Tricke77e84e2012-01-13 06:30:30 +0000158 AU.setPreservesCFG();
159 AU.addRequiredID(MachineDominatorsID);
160 AU.addRequired<MachineLoopInfo>();
161 AU.addRequired<AliasAnalysis>();
Andrew Trick45300682012-03-09 00:52:20 +0000162 AU.addRequired<TargetPassConfig>();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000163 AU.addRequired<SlotIndexes>();
164 AU.addPreserved<SlotIndexes>();
165 AU.addRequired<LiveIntervals>();
166 AU.addPreserved<LiveIntervals>();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000167 MachineFunctionPass::getAnalysisUsage(AU);
168}
169
Andrew Trick17080b92013-12-28 21:56:51 +0000170char PostMachineScheduler::ID = 0;
171
172char &llvm::PostMachineSchedulerID = PostMachineScheduler::ID;
173
174INITIALIZE_PASS(PostMachineScheduler, "postmisched",
Saleem Abdulrasool7230b372013-12-28 22:47:55 +0000175 "PostRA Machine Instruction Scheduler", false, false)
Andrew Trick17080b92013-12-28 21:56:51 +0000176
177PostMachineScheduler::PostMachineScheduler()
178: MachineSchedulerBase(ID) {
179 initializePostMachineSchedulerPass(*PassRegistry::getPassRegistry());
180}
181
182void PostMachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
183 AU.setPreservesCFG();
184 AU.addRequiredID(MachineDominatorsID);
185 AU.addRequired<MachineLoopInfo>();
186 AU.addRequired<TargetPassConfig>();
187 MachineFunctionPass::getAnalysisUsage(AU);
188}
189
Andrew Tricke77e84e2012-01-13 06:30:30 +0000190MachinePassRegistry MachineSchedRegistry::Registry;
191
Andrew Trick45300682012-03-09 00:52:20 +0000192/// A dummy default scheduler factory indicates whether the scheduler
193/// is overridden on the command line.
194static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
195 return 0;
196}
Andrew Tricke77e84e2012-01-13 06:30:30 +0000197
198/// MachineSchedOpt allows command line selection of the scheduler.
199static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
200 RegisterPassParser<MachineSchedRegistry> >
201MachineSchedOpt("misched",
Andrew Trick45300682012-03-09 00:52:20 +0000202 cl::init(&useDefaultMachineSched), cl::Hidden,
Andrew Tricke77e84e2012-01-13 06:30:30 +0000203 cl::desc("Machine instruction scheduler to use"));
204
Andrew Trick45300682012-03-09 00:52:20 +0000205static MachineSchedRegistry
Andrew Trick8823dec2012-03-14 04:00:41 +0000206DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
Andrew Trick45300682012-03-09 00:52:20 +0000207 useDefaultMachineSched);
208
Andrew Trick8823dec2012-03-14 04:00:41 +0000209/// Forward declare the standard machine scheduler. This will be used as the
Andrew Trick45300682012-03-09 00:52:20 +0000210/// default scheduler if the target does not set a default.
Andrew Trickd14d7c22013-12-28 21:56:57 +0000211static ScheduleDAGInstrs *createGenericSchedLive(MachineSchedContext *C);
212static ScheduleDAGInstrs *createGenericSchedPostRA(MachineSchedContext *C);
Andrew Trickcc45a282012-04-24 18:04:34 +0000213
214/// Decrement this iterator until reaching the top or a non-debug instr.
Andrew Trick2bc74c22013-08-30 04:36:57 +0000215static MachineBasicBlock::const_iterator
216priorNonDebug(MachineBasicBlock::const_iterator I,
217 MachineBasicBlock::const_iterator Beg) {
Andrew Trickcc45a282012-04-24 18:04:34 +0000218 assert(I != Beg && "reached the top of the region, cannot decrement");
219 while (--I != Beg) {
220 if (!I->isDebugValue())
221 break;
222 }
223 return I;
224}
225
Andrew Trick2bc74c22013-08-30 04:36:57 +0000226/// Non-const version.
227static MachineBasicBlock::iterator
228priorNonDebug(MachineBasicBlock::iterator I,
229 MachineBasicBlock::const_iterator Beg) {
230 return const_cast<MachineInstr*>(
231 &*priorNonDebug(MachineBasicBlock::const_iterator(I), Beg));
232}
233
Andrew Trickcc45a282012-04-24 18:04:34 +0000234/// If this iterator is a debug value, increment until reaching the End or a
235/// non-debug instruction.
Andrew Trick2c4f8b72013-08-31 05:17:58 +0000236static MachineBasicBlock::const_iterator
237nextIfDebug(MachineBasicBlock::const_iterator I,
238 MachineBasicBlock::const_iterator End) {
Andrew Trick463b2f12012-05-17 18:35:03 +0000239 for(; I != End; ++I) {
Andrew Trickcc45a282012-04-24 18:04:34 +0000240 if (!I->isDebugValue())
241 break;
242 }
243 return I;
244}
245
Andrew Trick2c4f8b72013-08-31 05:17:58 +0000246/// Non-const version.
247static MachineBasicBlock::iterator
248nextIfDebug(MachineBasicBlock::iterator I,
249 MachineBasicBlock::const_iterator End) {
250 // Cast the return value to nonconst MachineInstr, then cast to an
251 // instr_iterator, which does not check for null, finally return a
252 // bundle_iterator.
253 return MachineBasicBlock::instr_iterator(
254 const_cast<MachineInstr*>(
255 &*nextIfDebug(MachineBasicBlock::const_iterator(I), End)));
256}
257
Andrew Trickdc4c1ad2013-09-24 17:11:19 +0000258/// Instantiate a ScheduleDAGInstrs that will be owned by the caller.
Andrew Trick978674b2013-09-20 05:14:41 +0000259ScheduleDAGInstrs *MachineScheduler::createMachineScheduler() {
260 // Select the scheduler, or set the default.
261 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
262 if (Ctor != useDefaultMachineSched)
263 return Ctor(this);
264
265 // Get the default scheduler set by the target for this function.
266 ScheduleDAGInstrs *Scheduler = PassConfig->createMachineScheduler(this);
267 if (Scheduler)
268 return Scheduler;
269
270 // Default to GenericScheduler.
Andrew Trickd14d7c22013-12-28 21:56:57 +0000271 return createGenericSchedLive(this);
Andrew Trick978674b2013-09-20 05:14:41 +0000272}
273
Andrew Trick17080b92013-12-28 21:56:51 +0000274/// Instantiate a ScheduleDAGInstrs for PostRA scheduling that will be owned by
275/// the caller. We don't have a command line option to override the postRA
276/// scheduler. The Target must configure it.
277ScheduleDAGInstrs *PostMachineScheduler::createPostMachineScheduler() {
278 // Get the postRA scheduler set by the target for this function.
279 ScheduleDAGInstrs *Scheduler = PassConfig->createPostMachineScheduler(this);
280 if (Scheduler)
281 return Scheduler;
282
283 // Default to GenericScheduler.
Andrew Trickd14d7c22013-12-28 21:56:57 +0000284 return createGenericSchedPostRA(this);
Andrew Trick17080b92013-12-28 21:56:51 +0000285}
286
Andrew Trick72515be2012-03-14 04:00:38 +0000287/// Top-level MachineScheduler pass driver.
288///
289/// Visit blocks in function order. Divide each block into scheduling regions
Andrew Trick8823dec2012-03-14 04:00:41 +0000290/// and visit them bottom-up. Visiting regions bottom-up is not required, but is
291/// consistent with the DAG builder, which traverses the interior of the
292/// scheduling regions bottom-up.
Andrew Trick72515be2012-03-14 04:00:38 +0000293///
294/// This design avoids exposing scheduling boundaries to the DAG builder,
Andrew Trick8823dec2012-03-14 04:00:41 +0000295/// simplifying the DAG builder's support for "special" target instructions.
296/// At the same time the design allows target schedulers to operate across
Andrew Trick72515be2012-03-14 04:00:38 +0000297/// scheduling boundaries, for example to bundle the boudary instructions
298/// without reordering them. This creates complexity, because the target
299/// scheduler must update the RegionBegin and RegionEnd positions cached by
300/// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
301/// design would be to split blocks at scheduling boundaries, but LLVM has a
302/// general bias against block splitting purely for implementation simplicity.
Andrew Tricke1c034f2012-01-17 06:55:03 +0000303bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
Andrew Trickc5d70082012-05-10 21:06:21 +0000304 DEBUG(dbgs() << "Before MISsched:\n"; mf.print(dbgs()));
305
Andrew Tricke77e84e2012-01-13 06:30:30 +0000306 // Initialize the context of the pass.
307 MF = &mf;
308 MLI = &getAnalysis<MachineLoopInfo>();
309 MDT = &getAnalysis<MachineDominatorTree>();
Andrew Trick45300682012-03-09 00:52:20 +0000310 PassConfig = &getAnalysis<TargetPassConfig>();
Andrew Trick02a80da2012-03-08 01:41:12 +0000311 AA = &getAnalysis<AliasAnalysis>();
312
Lang Hamesad33d5a2012-01-27 22:36:19 +0000313 LIS = &getAnalysis<LiveIntervals>();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000314
Andrew Trick48f2a722013-03-08 05:40:34 +0000315 if (VerifyScheduling) {
Andrew Trick97064962013-07-25 07:26:26 +0000316 DEBUG(LIS->dump());
Andrew Trick48f2a722013-03-08 05:40:34 +0000317 MF->verify(this, "Before machine scheduling.");
318 }
Andrew Trick4d4b5462012-04-24 20:36:19 +0000319 RegClassInfo->runOnMachineFunction(*MF);
Andrew Trick88639922012-04-24 17:56:43 +0000320
Andrew Trick978674b2013-09-20 05:14:41 +0000321 // Instantiate the selected scheduler for this target, function, and
322 // optimization level.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000323 std::unique_ptr<ScheduleDAGInstrs> Scheduler(createMachineScheduler());
Andrew Trickd7f890e2013-12-28 21:56:47 +0000324 scheduleRegions(*Scheduler);
325
326 DEBUG(LIS->dump());
327 if (VerifyScheduling)
328 MF->verify(this, "After machine scheduling.");
329 return true;
330}
331
Andrew Trick17080b92013-12-28 21:56:51 +0000332bool PostMachineScheduler::runOnMachineFunction(MachineFunction &mf) {
333 DEBUG(dbgs() << "Before post-MI-sched:\n"; mf.print(dbgs()));
334
335 // Initialize the context of the pass.
336 MF = &mf;
337 PassConfig = &getAnalysis<TargetPassConfig>();
338
339 if (VerifyScheduling)
340 MF->verify(this, "Before post machine scheduling.");
341
342 // Instantiate the selected scheduler for this target, function, and
343 // optimization level.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000344 std::unique_ptr<ScheduleDAGInstrs> Scheduler(createPostMachineScheduler());
Andrew Trick17080b92013-12-28 21:56:51 +0000345 scheduleRegions(*Scheduler);
346
347 if (VerifyScheduling)
348 MF->verify(this, "After post machine scheduling.");
349 return true;
350}
351
Andrew Trickd14d7c22013-12-28 21:56:57 +0000352/// Return true of the given instruction should not be included in a scheduling
353/// region.
354///
355/// MachineScheduler does not currently support scheduling across calls. To
356/// handle calls, the DAG builder needs to be modified to create register
357/// anti/output dependencies on the registers clobbered by the call's regmask
358/// operand. In PreRA scheduling, the stack pointer adjustment already prevents
359/// scheduling across calls. In PostRA scheduling, we need the isCall to enforce
360/// the boundary, but there would be no benefit to postRA scheduling across
361/// calls this late anyway.
362static bool isSchedBoundary(MachineBasicBlock::iterator MI,
363 MachineBasicBlock *MBB,
364 MachineFunction *MF,
365 const TargetInstrInfo *TII,
366 bool IsPostRA) {
367 return MI->isCall() || TII->isSchedulingBoundary(MI, MBB, *MF);
368}
369
Andrew Trickd7f890e2013-12-28 21:56:47 +0000370/// Main driver for both MachineScheduler and PostMachineScheduler.
371void MachineSchedulerBase::scheduleRegions(ScheduleDAGInstrs &Scheduler) {
372 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
Andrew Trickd14d7c22013-12-28 21:56:57 +0000373 bool IsPostRA = Scheduler.isPostRA();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000374
375 // Visit all machine basic blocks.
Andrew Trick88639922012-04-24 17:56:43 +0000376 //
377 // TODO: Visit blocks in global postorder or postorder within the bottom-up
378 // loop tree. Then we can optionally compute global RegPressure.
Andrew Tricke77e84e2012-01-13 06:30:30 +0000379 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
380 MBB != MBBEnd; ++MBB) {
381
Andrew Trickd7f890e2013-12-28 21:56:47 +0000382 Scheduler.startBlock(MBB);
Andrew Trickedfe2ec2012-03-09 08:02:51 +0000383
Andrew Trick33e05d72013-12-28 21:57:02 +0000384#ifndef NDEBUG
385 if (SchedOnlyFunc.getNumOccurrences() && SchedOnlyFunc != MF->getName())
386 continue;
387 if (SchedOnlyBlock.getNumOccurrences()
388 && (int)SchedOnlyBlock != MBB->getNumber())
389 continue;
390#endif
391
Andrew Trick7e120f42012-01-14 02:17:09 +0000392 // Break the block into scheduling regions [I, RegionEnd), and schedule each
Sylvestre Ledru35521e22012-07-23 08:51:15 +0000393 // region as soon as it is discovered. RegionEnd points the scheduling
Andrew Trickaf1bee72012-03-09 22:34:56 +0000394 // boundary at the bottom of the region. The DAG does not include RegionEnd,
395 // but the region does (i.e. the next RegionEnd is above the previous
396 // RegionBegin). If the current block has no terminator then RegionEnd ==
397 // MBB->end() for the bottom region.
398 //
399 // The Scheduler may insert instructions during either schedule() or
400 // exitRegion(), even for empty regions. So the local iterators 'I' and
401 // 'RegionEnd' are invalid across these calls.
Andrew Trickd14d7c22013-12-28 21:56:57 +0000402 //
403 // MBB::size() uses instr_iterator to count. Here we need a bundle to count
404 // as a single instruction.
405 unsigned RemainingInstrs = std::distance(MBB->begin(), MBB->end());
Andrew Tricka21daf72012-03-09 03:46:39 +0000406 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
Andrew Trickd7f890e2013-12-28 21:56:47 +0000407 RegionEnd != MBB->begin(); RegionEnd = Scheduler.begin()) {
Andrew Trick88639922012-04-24 17:56:43 +0000408
Andrew Trickedfe2ec2012-03-09 08:02:51 +0000409 // Avoid decrementing RegionEnd for blocks with no terminator.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000410 if (RegionEnd != MBB->end() ||
411 isSchedBoundary(std::prev(RegionEnd), MBB, MF, TII, IsPostRA)) {
Andrew Trickedfe2ec2012-03-09 08:02:51 +0000412 --RegionEnd;
413 // Count the boundary instruction.
Andrew Trick4d1fa712012-11-06 07:10:34 +0000414 --RemainingInstrs;
Andrew Trickedfe2ec2012-03-09 08:02:51 +0000415 }
416
Andrew Trick7e120f42012-01-14 02:17:09 +0000417 // The next region starts above the previous region. Look backward in the
418 // instruction stream until we find the nearest boundary.
Andrew Tricka53e1012013-08-23 17:48:33 +0000419 unsigned NumRegionInstrs = 0;
Andrew Trick7e120f42012-01-14 02:17:09 +0000420 MachineBasicBlock::iterator I = RegionEnd;
Andrew Tricka53e1012013-08-23 17:48:33 +0000421 for(;I != MBB->begin(); --I, --RemainingInstrs, ++NumRegionInstrs) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000422 if (isSchedBoundary(std::prev(I), MBB, MF, TII, IsPostRA))
Andrew Trick7e120f42012-01-14 02:17:09 +0000423 break;
424 }
Andrew Trick60cf03e2012-03-07 05:21:52 +0000425 // Notify the scheduler of the region, even if we may skip scheduling
426 // it. Perhaps it still needs to be bundled.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000427 Scheduler.enterRegion(MBB, I, RegionEnd, NumRegionInstrs);
Andrew Trick60cf03e2012-03-07 05:21:52 +0000428
429 // Skip empty scheduling regions (0 or 1 schedulable instructions).
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000430 if (I == RegionEnd || I == std::prev(RegionEnd)) {
Andrew Trick60cf03e2012-03-07 05:21:52 +0000431 // Close the current region. Bundle the terminator if needed.
Andrew Trickaf1bee72012-03-09 22:34:56 +0000432 // This invalidates 'RegionEnd' and 'I'.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000433 Scheduler.exitRegion();
Andrew Trick7ccdc5c2012-01-17 06:55:07 +0000434 continue;
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000435 }
Andrew Trickd14d7c22013-12-28 21:56:57 +0000436 DEBUG(dbgs() << "********** " << ((Scheduler.isPostRA()) ? "PostRA " : "")
437 << "MI Scheduling **********\n");
Craig Toppera538d832012-08-22 06:07:19 +0000438 DEBUG(dbgs() << MF->getName()
Andrew Trick54b2ce32013-01-25 07:45:31 +0000439 << ":BB#" << MBB->getNumber() << " " << MBB->getName()
440 << "\n From: " << *I << " To: ";
Andrew Tricke57583a2012-02-08 02:17:21 +0000441 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
442 else dbgs() << "End";
Andrew Tricka53e1012013-08-23 17:48:33 +0000443 dbgs() << " RegionInstrs: " << NumRegionInstrs
444 << " Remaining: " << RemainingInstrs << "\n");
Andrew Trick7ccdc5c2012-01-17 06:55:07 +0000445
Andrew Trick1c0ec452012-03-09 03:46:42 +0000446 // Schedule a region: possibly reorder instructions.
Andrew Trickaf1bee72012-03-09 22:34:56 +0000447 // This invalidates 'RegionEnd' and 'I'.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000448 Scheduler.schedule();
Andrew Trick1c0ec452012-03-09 03:46:42 +0000449
450 // Close the current region.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000451 Scheduler.exitRegion();
Andrew Trick60cf03e2012-03-07 05:21:52 +0000452
453 // Scheduling has invalidated the current iterator 'I'. Ask the
454 // scheduler for the top of it's scheduled region.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000455 RegionEnd = Scheduler.begin();
Andrew Trick7e120f42012-01-14 02:17:09 +0000456 }
Andrew Trick4d1fa712012-11-06 07:10:34 +0000457 assert(RemainingInstrs == 0 && "Instruction count mismatch!");
Andrew Trickd7f890e2013-12-28 21:56:47 +0000458 Scheduler.finishBlock();
Andrew Trickd14d7c22013-12-28 21:56:57 +0000459 if (Scheduler.isPostRA()) {
460 // FIXME: Ideally, no further passes should rely on kill flags. However,
461 // thumb2 size reduction is currently an exception.
462 Scheduler.fixupKills(MBB);
463 }
Andrew Tricke77e84e2012-01-13 06:30:30 +0000464 }
Andrew Trickd7f890e2013-12-28 21:56:47 +0000465 Scheduler.finalizeSchedule();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000466}
467
Andrew Trickd7f890e2013-12-28 21:56:47 +0000468void MachineSchedulerBase::print(raw_ostream &O, const Module* m) const {
Andrew Tricke77e84e2012-01-13 06:30:30 +0000469 // unimplemented
470}
471
Manman Ren19f49ac2012-09-11 22:23:19 +0000472#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Andrew Trick7a8e1002012-09-11 00:39:15 +0000473void ReadyQueue::dump() {
Andrew Trickd40d0f22013-06-17 21:45:05 +0000474 dbgs() << Name << ": ";
Andrew Trick7a8e1002012-09-11 00:39:15 +0000475 for (unsigned i = 0, e = Queue.size(); i < e; ++i)
476 dbgs() << Queue[i]->NodeNum << " ";
477 dbgs() << "\n";
478}
479#endif
Andrew Trick8823dec2012-03-14 04:00:41 +0000480
481//===----------------------------------------------------------------------===//
Andrew Trickd7f890e2013-12-28 21:56:47 +0000482// ScheduleDAGMI - Basic machine instruction scheduling. This is
483// independent of PreRA/PostRA scheduling and involves no extra book-keeping for
484// virtual registers.
485// ===----------------------------------------------------------------------===/
Andrew Trick8823dec2012-03-14 04:00:41 +0000486
Andrew Trick44f750a2013-01-25 04:01:04 +0000487ScheduleDAGMI::~ScheduleDAGMI() {
Andrew Trick44f750a2013-01-25 04:01:04 +0000488 DeleteContainerPointers(Mutations);
489 delete SchedImpl;
490}
491
Andrew Trick85a1d4c2013-04-24 15:54:43 +0000492bool ScheduleDAGMI::canAddEdge(SUnit *SuccSU, SUnit *PredSU) {
493 return SuccSU == &ExitSU || !Topo.IsReachable(PredSU, SuccSU);
494}
495
Andrew Tricka7714a02012-11-12 19:40:10 +0000496bool ScheduleDAGMI::addEdge(SUnit *SuccSU, const SDep &PredDep) {
Andrew Trick263280242012-11-12 19:52:20 +0000497 if (SuccSU != &ExitSU) {
498 // Do not use WillCreateCycle, it assumes SD scheduling.
499 // If Pred is reachable from Succ, then the edge creates a cycle.
500 if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
501 return false;
502 Topo.AddPred(SuccSU, PredDep.getSUnit());
503 }
Andrew Tricka7714a02012-11-12 19:40:10 +0000504 SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
505 // Return true regardless of whether a new edge needed to be inserted.
506 return true;
507}
508
Andrew Trick02a80da2012-03-08 01:41:12 +0000509/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
510/// NumPredsLeft reaches zero, release the successor node.
Andrew Trick61f1a272012-05-24 22:11:09 +0000511///
512/// FIXME: Adjust SuccSU height based on MinLatency.
Andrew Trick8823dec2012-03-14 04:00:41 +0000513void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
Andrew Trick02a80da2012-03-08 01:41:12 +0000514 SUnit *SuccSU = SuccEdge->getSUnit();
515
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000516 if (SuccEdge->isWeak()) {
517 --SuccSU->WeakPredsLeft;
Andrew Tricka7714a02012-11-12 19:40:10 +0000518 if (SuccEdge->isCluster())
519 NextClusterSucc = SuccSU;
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000520 return;
521 }
Andrew Trick02a80da2012-03-08 01:41:12 +0000522#ifndef NDEBUG
523 if (SuccSU->NumPredsLeft == 0) {
524 dbgs() << "*** Scheduling failed! ***\n";
525 SuccSU->dump(this);
526 dbgs() << " has been released too many times!\n";
527 llvm_unreachable(0);
528 }
529#endif
530 --SuccSU->NumPredsLeft;
531 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
Andrew Trick8823dec2012-03-14 04:00:41 +0000532 SchedImpl->releaseTopNode(SuccSU);
Andrew Trick02a80da2012-03-08 01:41:12 +0000533}
534
535/// releaseSuccessors - Call releaseSucc on each of SU's successors.
Andrew Trick8823dec2012-03-14 04:00:41 +0000536void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
Andrew Trick02a80da2012-03-08 01:41:12 +0000537 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
538 I != E; ++I) {
539 releaseSucc(SU, &*I);
540 }
541}
542
Andrew Trick8823dec2012-03-14 04:00:41 +0000543/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
544/// NumSuccsLeft reaches zero, release the predecessor node.
Andrew Trick61f1a272012-05-24 22:11:09 +0000545///
546/// FIXME: Adjust PredSU height based on MinLatency.
Andrew Trick8823dec2012-03-14 04:00:41 +0000547void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
548 SUnit *PredSU = PredEdge->getSUnit();
549
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000550 if (PredEdge->isWeak()) {
551 --PredSU->WeakSuccsLeft;
Andrew Tricka7714a02012-11-12 19:40:10 +0000552 if (PredEdge->isCluster())
553 NextClusterPred = PredSU;
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000554 return;
555 }
Andrew Trick8823dec2012-03-14 04:00:41 +0000556#ifndef NDEBUG
557 if (PredSU->NumSuccsLeft == 0) {
558 dbgs() << "*** Scheduling failed! ***\n";
559 PredSU->dump(this);
560 dbgs() << " has been released too many times!\n";
561 llvm_unreachable(0);
562 }
563#endif
564 --PredSU->NumSuccsLeft;
565 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
566 SchedImpl->releaseBottomNode(PredSU);
567}
568
569/// releasePredecessors - Call releasePred on each of SU's predecessors.
570void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
571 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
572 I != E; ++I) {
573 releasePred(SU, &*I);
574 }
575}
576
Andrew Trickd7f890e2013-12-28 21:56:47 +0000577/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
578/// crossing a scheduling boundary. [begin, end) includes all instructions in
579/// the region, including the boundary itself and single-instruction regions
580/// that don't get scheduled.
581void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
582 MachineBasicBlock::iterator begin,
583 MachineBasicBlock::iterator end,
584 unsigned regioninstrs)
585{
586 ScheduleDAGInstrs::enterRegion(bb, begin, end, regioninstrs);
587
588 SchedImpl->initPolicy(begin, end, regioninstrs);
589}
590
Andrew Tricke833e1c2013-04-13 06:07:40 +0000591/// This is normally called from the main scheduler loop but may also be invoked
592/// by the scheduling strategy to perform additional code motion.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000593void ScheduleDAGMI::moveInstruction(
594 MachineInstr *MI, MachineBasicBlock::iterator InsertPos) {
Andrew Trick463b2f12012-05-17 18:35:03 +0000595 // Advance RegionBegin if the first instruction moves down.
Andrew Trick54f7def2012-03-21 04:12:10 +0000596 if (&*RegionBegin == MI)
Andrew Trick463b2f12012-05-17 18:35:03 +0000597 ++RegionBegin;
598
599 // Update the instruction stream.
Andrew Trick8823dec2012-03-14 04:00:41 +0000600 BB->splice(InsertPos, BB, MI);
Andrew Trick463b2f12012-05-17 18:35:03 +0000601
602 // Update LiveIntervals
Andrew Trickd7f890e2013-12-28 21:56:47 +0000603 if (LIS)
604 LIS->handleMove(MI, /*UpdateFlags=*/true);
Andrew Trick463b2f12012-05-17 18:35:03 +0000605
606 // Recede RegionBegin if an instruction moves above the first.
Andrew Trick8823dec2012-03-14 04:00:41 +0000607 if (RegionBegin == InsertPos)
608 RegionBegin = MI;
609}
610
Andrew Trickde670c02012-03-21 04:12:07 +0000611bool ScheduleDAGMI::checkSchedLimit() {
612#ifndef NDEBUG
613 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
614 CurrentTop = CurrentBottom;
615 return false;
616 }
617 ++NumInstrsScheduled;
618#endif
619 return true;
620}
621
Andrew Trickd7f890e2013-12-28 21:56:47 +0000622/// Per-region scheduling driver, called back from
623/// MachineScheduler::runOnMachineFunction. This is a simplified driver that
624/// does not consider liveness or register pressure. It is useful for PostRA
625/// scheduling and potentially other custom schedulers.
626void ScheduleDAGMI::schedule() {
627 // Build the DAG.
628 buildSchedGraph(AA);
629
630 Topo.InitDAGTopologicalSorting();
631
632 postprocessDAG();
633
634 SmallVector<SUnit*, 8> TopRoots, BotRoots;
635 findRootsAndBiasEdges(TopRoots, BotRoots);
636
637 // Initialize the strategy before modifying the DAG.
638 // This may initialize a DFSResult to be used for queue priority.
639 SchedImpl->initialize(this);
640
641 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
642 SUnits[su].dumpAll(this));
643 if (ViewMISchedDAGs) viewGraph();
644
645 // Initialize ready queues now that the DAG and priority data are finalized.
646 initQueues(TopRoots, BotRoots);
647
648 bool IsTopNode = false;
649 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
650 assert(!SU->isScheduled && "Node already scheduled");
651 if (!checkSchedLimit())
652 break;
653
654 MachineInstr *MI = SU->getInstr();
655 if (IsTopNode) {
656 assert(SU->isTopReady() && "node still has unscheduled dependencies");
657 if (&*CurrentTop == MI)
658 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
659 else
660 moveInstruction(MI, CurrentTop);
661 }
662 else {
663 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
664 MachineBasicBlock::iterator priorII =
665 priorNonDebug(CurrentBottom, CurrentTop);
666 if (&*priorII == MI)
667 CurrentBottom = priorII;
668 else {
669 if (&*CurrentTop == MI)
670 CurrentTop = nextIfDebug(++CurrentTop, priorII);
671 moveInstruction(MI, CurrentBottom);
672 CurrentBottom = MI;
673 }
674 }
675 updateQueues(SU, IsTopNode);
676
677 // Notify the scheduling strategy after updating the DAG.
678 SchedImpl->schedNode(SU, IsTopNode);
679 }
680 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
681
682 placeDebugValues();
683
684 DEBUG({
685 unsigned BBNum = begin()->getParent()->getNumber();
686 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
687 dumpSchedule();
688 dbgs() << '\n';
689 });
690}
691
692/// Apply each ScheduleDAGMutation step in order.
693void ScheduleDAGMI::postprocessDAG() {
694 for (unsigned i = 0, e = Mutations.size(); i < e; ++i) {
695 Mutations[i]->apply(this);
696 }
697}
698
699void ScheduleDAGMI::
700findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
701 SmallVectorImpl<SUnit*> &BotRoots) {
702 for (std::vector<SUnit>::iterator
703 I = SUnits.begin(), E = SUnits.end(); I != E; ++I) {
704 SUnit *SU = &(*I);
705 assert(!SU->isBoundaryNode() && "Boundary node should not be in SUnits");
706
707 // Order predecessors so DFSResult follows the critical path.
708 SU->biasCriticalPath();
709
710 // A SUnit is ready to top schedule if it has no predecessors.
711 if (!I->NumPredsLeft)
712 TopRoots.push_back(SU);
713 // A SUnit is ready to bottom schedule if it has no successors.
714 if (!I->NumSuccsLeft)
715 BotRoots.push_back(SU);
716 }
717 ExitSU.biasCriticalPath();
718}
719
720/// Identify DAG roots and setup scheduler queues.
721void ScheduleDAGMI::initQueues(ArrayRef<SUnit*> TopRoots,
722 ArrayRef<SUnit*> BotRoots) {
723 NextClusterSucc = NULL;
724 NextClusterPred = NULL;
725
726 // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
727 //
728 // Nodes with unreleased weak edges can still be roots.
729 // Release top roots in forward order.
730 for (SmallVectorImpl<SUnit*>::const_iterator
731 I = TopRoots.begin(), E = TopRoots.end(); I != E; ++I) {
732 SchedImpl->releaseTopNode(*I);
733 }
734 // Release bottom roots in reverse order so the higher priority nodes appear
735 // first. This is more natural and slightly more efficient.
736 for (SmallVectorImpl<SUnit*>::const_reverse_iterator
737 I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I) {
738 SchedImpl->releaseBottomNode(*I);
739 }
740
741 releaseSuccessors(&EntrySU);
742 releasePredecessors(&ExitSU);
743
744 SchedImpl->registerRoots();
745
746 // Advance past initial DebugValues.
747 CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
748 CurrentBottom = RegionEnd;
749}
750
751/// Update scheduler queues after scheduling an instruction.
752void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
753 // Release dependent instructions for scheduling.
754 if (IsTopNode)
755 releaseSuccessors(SU);
756 else
757 releasePredecessors(SU);
758
759 SU->isScheduled = true;
760}
761
762/// Reinsert any remaining debug_values, just like the PostRA scheduler.
763void ScheduleDAGMI::placeDebugValues() {
764 // If first instruction was a DBG_VALUE then put it back.
765 if (FirstDbgValue) {
766 BB->splice(RegionBegin, BB, FirstDbgValue);
767 RegionBegin = FirstDbgValue;
768 }
769
770 for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
771 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000772 std::pair<MachineInstr *, MachineInstr *> P = *std::prev(DI);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000773 MachineInstr *DbgValue = P.first;
774 MachineBasicBlock::iterator OrigPrevMI = P.second;
775 if (&*RegionBegin == DbgValue)
776 ++RegionBegin;
777 BB->splice(++OrigPrevMI, BB, DbgValue);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000778 if (OrigPrevMI == std::prev(RegionEnd))
Andrew Trickd7f890e2013-12-28 21:56:47 +0000779 RegionEnd = DbgValue;
780 }
781 DbgValues.clear();
782 FirstDbgValue = NULL;
783}
784
785#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
786void ScheduleDAGMI::dumpSchedule() const {
787 for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
788 if (SUnit *SU = getSUnit(&(*MI)))
789 SU->dump(this);
790 else
791 dbgs() << "Missing SUnit\n";
792 }
793}
794#endif
795
796//===----------------------------------------------------------------------===//
797// ScheduleDAGMILive - Base class for MachineInstr scheduling with LiveIntervals
798// preservation.
799//===----------------------------------------------------------------------===//
800
801ScheduleDAGMILive::~ScheduleDAGMILive() {
802 delete DFSResult;
803}
804
Andrew Trick88639922012-04-24 17:56:43 +0000805/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
806/// crossing a scheduling boundary. [begin, end) includes all instructions in
807/// the region, including the boundary itself and single-instruction regions
808/// that don't get scheduled.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000809void ScheduleDAGMILive::enterRegion(MachineBasicBlock *bb,
Andrew Trick88639922012-04-24 17:56:43 +0000810 MachineBasicBlock::iterator begin,
811 MachineBasicBlock::iterator end,
Andrew Tricka53e1012013-08-23 17:48:33 +0000812 unsigned regioninstrs)
Andrew Trick88639922012-04-24 17:56:43 +0000813{
Andrew Trickd7f890e2013-12-28 21:56:47 +0000814 // ScheduleDAGMI initializes SchedImpl's per-region policy.
815 ScheduleDAGMI::enterRegion(bb, begin, end, regioninstrs);
Andrew Trick4add42f2012-05-10 21:06:10 +0000816
817 // For convenience remember the end of the liveness region.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000818 LiveRegionEnd = (RegionEnd == bb->end()) ? RegionEnd : std::next(RegionEnd);
Andrew Trick75e411c2013-09-06 17:32:34 +0000819
Andrew Trickb248b4a2013-09-06 17:32:47 +0000820 SUPressureDiffs.clear();
821
Andrew Trick75e411c2013-09-06 17:32:34 +0000822 ShouldTrackPressure = SchedImpl->shouldTrackPressure();
Andrew Trick4add42f2012-05-10 21:06:10 +0000823}
824
825// Setup the register pressure trackers for the top scheduled top and bottom
826// scheduled regions.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000827void ScheduleDAGMILive::initRegPressure() {
Andrew Trick4add42f2012-05-10 21:06:10 +0000828 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin);
829 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
830
831 // Close the RPTracker to finalize live ins.
832 RPTracker.closeRegion();
833
Andrew Trick9c17eab2013-07-30 19:59:12 +0000834 DEBUG(RPTracker.dump());
Andrew Trick79d3eec2012-05-24 22:11:14 +0000835
Andrew Trick4add42f2012-05-10 21:06:10 +0000836 // Initialize the live ins and live outs.
837 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
838 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
839
840 // Close one end of the tracker so we can call
841 // getMaxUpward/DownwardPressureDelta before advancing across any
842 // instructions. This converts currently live regs into live ins/outs.
843 TopRPTracker.closeTop();
844 BotRPTracker.closeBottom();
845
Andrew Trick9c17eab2013-07-30 19:59:12 +0000846 BotRPTracker.initLiveThru(RPTracker);
847 if (!BotRPTracker.getLiveThru().empty()) {
848 TopRPTracker.initLiveThru(BotRPTracker.getLiveThru());
849 DEBUG(dbgs() << "Live Thru: ";
850 dumpRegSetPressure(BotRPTracker.getLiveThru(), TRI));
851 };
852
Andrew Trick2bc74c22013-08-30 04:36:57 +0000853 // For each live out vreg reduce the pressure change associated with other
854 // uses of the same vreg below the live-out reaching def.
855 updatePressureDiffs(RPTracker.getPressure().LiveOutRegs);
856
Andrew Trick4add42f2012-05-10 21:06:10 +0000857 // Account for liveness generated by the region boundary.
Andrew Trick2bc74c22013-08-30 04:36:57 +0000858 if (LiveRegionEnd != RegionEnd) {
859 SmallVector<unsigned, 8> LiveUses;
860 BotRPTracker.recede(&LiveUses);
861 updatePressureDiffs(LiveUses);
862 }
Andrew Trick4add42f2012-05-10 21:06:10 +0000863
864 assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
Andrew Trick22025772012-05-17 18:35:10 +0000865
866 // Cache the list of excess pressure sets in this region. This will also track
867 // the max pressure in the scheduled code for these sets.
868 RegionCriticalPSets.clear();
Jakub Staszakc641ada2013-01-25 21:44:27 +0000869 const std::vector<unsigned> &RegionPressure =
870 RPTracker.getPressure().MaxSetPressure;
Andrew Trick22025772012-05-17 18:35:10 +0000871 for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
Andrew Trick736dd9a2013-06-21 18:32:58 +0000872 unsigned Limit = RegClassInfo->getRegPressureSetLimit(i);
Andrew Trickb55db582013-06-21 18:33:01 +0000873 if (RegionPressure[i] > Limit) {
874 DEBUG(dbgs() << TRI->getRegPressureSetName(i)
875 << " Limit " << Limit
876 << " Actual " << RegionPressure[i] << "\n");
Andrew Trick1a831342013-08-30 03:49:48 +0000877 RegionCriticalPSets.push_back(PressureChange(i));
Andrew Trickb55db582013-06-21 18:33:01 +0000878 }
Andrew Trick22025772012-05-17 18:35:10 +0000879 }
880 DEBUG(dbgs() << "Excess PSets: ";
881 for (unsigned i = 0, e = RegionCriticalPSets.size(); i != e; ++i)
882 dbgs() << TRI->getRegPressureSetName(
Andrew Trick1a831342013-08-30 03:49:48 +0000883 RegionCriticalPSets[i].getPSet()) << " ";
Andrew Trick22025772012-05-17 18:35:10 +0000884 dbgs() << "\n");
885}
886
Andrew Trickd7f890e2013-12-28 21:56:47 +0000887void ScheduleDAGMILive::
Andrew Trickb248b4a2013-09-06 17:32:47 +0000888updateScheduledPressure(const SUnit *SU,
889 const std::vector<unsigned> &NewMaxPressure) {
890 const PressureDiff &PDiff = getPressureDiff(SU);
891 unsigned CritIdx = 0, CritEnd = RegionCriticalPSets.size();
892 for (PressureDiff::const_iterator I = PDiff.begin(), E = PDiff.end();
893 I != E; ++I) {
894 if (!I->isValid())
895 break;
896 unsigned ID = I->getPSet();
897 while (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() < ID)
898 ++CritIdx;
899 if (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() == ID) {
900 if ((int)NewMaxPressure[ID] > RegionCriticalPSets[CritIdx].getUnitInc()
901 && NewMaxPressure[ID] <= INT16_MAX)
902 RegionCriticalPSets[CritIdx].setUnitInc(NewMaxPressure[ID]);
903 }
904 unsigned Limit = RegClassInfo->getRegPressureSetLimit(ID);
905 if (NewMaxPressure[ID] >= Limit - 2) {
906 DEBUG(dbgs() << " " << TRI->getRegPressureSetName(ID) << ": "
907 << NewMaxPressure[ID] << " > " << Limit << "(+ "
908 << BotRPTracker.getLiveThru()[ID] << " livethru)\n");
909 }
Andrew Trick22025772012-05-17 18:35:10 +0000910 }
Andrew Trick88639922012-04-24 17:56:43 +0000911}
912
Andrew Trick2bc74c22013-08-30 04:36:57 +0000913/// Update the PressureDiff array for liveness after scheduling this
914/// instruction.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000915void ScheduleDAGMILive::updatePressureDiffs(ArrayRef<unsigned> LiveUses) {
Andrew Trick2bc74c22013-08-30 04:36:57 +0000916 for (unsigned LUIdx = 0, LUEnd = LiveUses.size(); LUIdx != LUEnd; ++LUIdx) {
917 /// FIXME: Currently assuming single-use physregs.
918 unsigned Reg = LiveUses[LUIdx];
Andrew Trickffdbefb2013-09-06 17:32:39 +0000919 DEBUG(dbgs() << " LiveReg: " << PrintVRegOrUnit(Reg, TRI) << "\n");
Andrew Trick2bc74c22013-08-30 04:36:57 +0000920 if (!TRI->isVirtualRegister(Reg))
921 continue;
Andrew Trickffdbefb2013-09-06 17:32:39 +0000922
Andrew Trick2bc74c22013-08-30 04:36:57 +0000923 // This may be called before CurrentBottom has been initialized. However,
924 // BotRPTracker must have a valid position. We want the value live into the
925 // instruction or live out of the block, so ask for the previous
926 // instruction's live-out.
927 const LiveInterval &LI = LIS->getInterval(Reg);
928 VNInfo *VNI;
Andrew Trick2c4f8b72013-08-31 05:17:58 +0000929 MachineBasicBlock::const_iterator I =
930 nextIfDebug(BotRPTracker.getPos(), BB->end());
931 if (I == BB->end())
Andrew Trick2bc74c22013-08-30 04:36:57 +0000932 VNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
933 else {
Matthias Braun88dd0ab2013-10-10 21:28:52 +0000934 LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(I));
Andrew Trick2bc74c22013-08-30 04:36:57 +0000935 VNI = LRQ.valueIn();
936 }
937 // RegisterPressureTracker guarantees that readsReg is true for LiveUses.
938 assert(VNI && "No live value at use.");
939 for (VReg2UseMap::iterator
940 UI = VRegUses.find(Reg); UI != VRegUses.end(); ++UI) {
941 SUnit *SU = UI->SU;
Andrew Trickffdbefb2013-09-06 17:32:39 +0000942 DEBUG(dbgs() << " UpdateRegP: SU(" << SU->NodeNum << ") "
943 << *SU->getInstr());
Andrew Trick2bc74c22013-08-30 04:36:57 +0000944 // If this use comes before the reaching def, it cannot be a last use, so
945 // descrease its pressure change.
946 if (!SU->isScheduled && SU != &ExitSU) {
Matthias Braun88dd0ab2013-10-10 21:28:52 +0000947 LiveQueryResult LRQ
948 = LI.Query(LIS->getInstructionIndex(SU->getInstr()));
Andrew Trick2bc74c22013-08-30 04:36:57 +0000949 if (LRQ.valueIn() == VNI)
950 getPressureDiff(SU).addPressureChange(Reg, true, &MRI);
951 }
952 }
953 }
954}
955
Andrew Trick8823dec2012-03-14 04:00:41 +0000956/// schedule - Called back from MachineScheduler::runOnMachineFunction
Andrew Trick88639922012-04-24 17:56:43 +0000957/// after setting up the current scheduling region. [RegionBegin, RegionEnd)
958/// only includes instructions that have DAG nodes, not scheduling boundaries.
Andrew Trick7a8e1002012-09-11 00:39:15 +0000959///
960/// This is a skeletal driver, with all the functionality pushed into helpers,
961/// so that it can be easilly extended by experimental schedulers. Generally,
962/// implementing MachineSchedStrategy should be sufficient to implement a new
963/// scheduling algorithm. However, if a scheduler further subclasses
Andrew Trickd7f890e2013-12-28 21:56:47 +0000964/// ScheduleDAGMILive then it will want to override this virtual method in order
965/// to update any specialized state.
966void ScheduleDAGMILive::schedule() {
Andrew Trick7a8e1002012-09-11 00:39:15 +0000967 buildDAGWithRegPressure();
968
Andrew Tricka7714a02012-11-12 19:40:10 +0000969 Topo.InitDAGTopologicalSorting();
970
Andrew Tricka2733e92012-09-14 17:22:42 +0000971 postprocessDAG();
972
Andrew Tricke2c3f5c2013-01-25 06:33:57 +0000973 SmallVector<SUnit*, 8> TopRoots, BotRoots;
974 findRootsAndBiasEdges(TopRoots, BotRoots);
975
976 // Initialize the strategy before modifying the DAG.
977 // This may initialize a DFSResult to be used for queue priority.
978 SchedImpl->initialize(this);
979
Andrew Trick7a8e1002012-09-11 00:39:15 +0000980 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
981 SUnits[su].dumpAll(this));
Andrew Tricke2c3f5c2013-01-25 06:33:57 +0000982 if (ViewMISchedDAGs) viewGraph();
Andrew Trick7a8e1002012-09-11 00:39:15 +0000983
Andrew Tricke2c3f5c2013-01-25 06:33:57 +0000984 // Initialize ready queues now that the DAG and priority data are finalized.
985 initQueues(TopRoots, BotRoots);
Andrew Trick7a8e1002012-09-11 00:39:15 +0000986
Andrew Trickd7f890e2013-12-28 21:56:47 +0000987 if (ShouldTrackPressure) {
988 assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
989 TopRPTracker.setPos(CurrentTop);
990 }
991
Andrew Trick7a8e1002012-09-11 00:39:15 +0000992 bool IsTopNode = false;
993 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
Andrew Trick984d98b2012-10-08 18:53:53 +0000994 assert(!SU->isScheduled && "Node already scheduled");
Andrew Trick7a8e1002012-09-11 00:39:15 +0000995 if (!checkSchedLimit())
996 break;
997
998 scheduleMI(SU, IsTopNode);
999
1000 updateQueues(SU, IsTopNode);
Andrew Trickd7f890e2013-12-28 21:56:47 +00001001
1002 if (DFSResult) {
1003 unsigned SubtreeID = DFSResult->getSubtreeID(SU);
1004 if (!ScheduledTrees.test(SubtreeID)) {
1005 ScheduledTrees.set(SubtreeID);
1006 DFSResult->scheduleTree(SubtreeID);
1007 SchedImpl->scheduleTree(SubtreeID);
1008 }
1009 }
1010
1011 // Notify the scheduling strategy after updating the DAG.
1012 SchedImpl->schedNode(SU, IsTopNode);
Andrew Trick7a8e1002012-09-11 00:39:15 +00001013 }
1014 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
1015
1016 placeDebugValues();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001017
1018 DEBUG({
Andrew Trickcf7e6972012-11-28 03:42:47 +00001019 unsigned BBNum = begin()->getParent()->getNumber();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001020 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
1021 dumpSchedule();
1022 dbgs() << '\n';
1023 });
Andrew Trick7a8e1002012-09-11 00:39:15 +00001024}
1025
1026/// Build the DAG and setup three register pressure trackers.
Andrew Trickd7f890e2013-12-28 21:56:47 +00001027void ScheduleDAGMILive::buildDAGWithRegPressure() {
Andrew Trickb6e74712013-09-04 20:59:59 +00001028 if (!ShouldTrackPressure) {
1029 RPTracker.reset();
1030 RegionCriticalPSets.clear();
1031 buildSchedGraph(AA);
1032 return;
1033 }
1034
Andrew Trick4add42f2012-05-10 21:06:10 +00001035 // Initialize the register pressure tracker used by buildSchedGraph.
Andrew Trick9c17eab2013-07-30 19:59:12 +00001036 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
1037 /*TrackUntiedDefs=*/true);
Andrew Trick88639922012-04-24 17:56:43 +00001038
Andrew Trick4add42f2012-05-10 21:06:10 +00001039 // Account for liveness generate by the region boundary.
1040 if (LiveRegionEnd != RegionEnd)
1041 RPTracker.recede();
1042
1043 // Build the DAG, and compute current register pressure.
Andrew Trick1a831342013-08-30 03:49:48 +00001044 buildSchedGraph(AA, &RPTracker, &SUPressureDiffs);
Andrew Trick02a80da2012-03-08 01:41:12 +00001045
Andrew Trick4add42f2012-05-10 21:06:10 +00001046 // Initialize top/bottom trackers after computing region pressure.
1047 initRegPressure();
Andrew Trick7a8e1002012-09-11 00:39:15 +00001048}
Andrew Trick4add42f2012-05-10 21:06:10 +00001049
Andrew Trickd7f890e2013-12-28 21:56:47 +00001050void ScheduleDAGMILive::computeDFSResult() {
Andrew Trick44f750a2013-01-25 04:01:04 +00001051 if (!DFSResult)
1052 DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize);
1053 DFSResult->clear();
Andrew Trick44f750a2013-01-25 04:01:04 +00001054 ScheduledTrees.clear();
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001055 DFSResult->resize(SUnits.size());
1056 DFSResult->compute(SUnits);
Andrew Trick44f750a2013-01-25 04:01:04 +00001057 ScheduledTrees.resize(DFSResult->getNumSubtrees());
1058}
1059
Andrew Trick483f4192013-08-29 18:04:49 +00001060/// Compute the max cyclic critical path through the DAG. The scheduling DAG
1061/// only provides the critical path for single block loops. To handle loops that
1062/// span blocks, we could use the vreg path latencies provided by
1063/// MachineTraceMetrics instead. However, MachineTraceMetrics is not currently
1064/// available for use in the scheduler.
1065///
1066/// The cyclic path estimation identifies a def-use pair that crosses the back
Andrew Trickef80f502013-08-30 02:02:12 +00001067/// edge and considers the depth and height of the nodes. For example, consider
Andrew Trick483f4192013-08-29 18:04:49 +00001068/// the following instruction sequence where each instruction has unit latency
1069/// and defines an epomymous virtual register:
1070///
1071/// a->b(a,c)->c(b)->d(c)->exit
1072///
1073/// The cyclic critical path is a two cycles: b->c->b
1074/// The acyclic critical path is four cycles: a->b->c->d->exit
1075/// LiveOutHeight = height(c) = len(c->d->exit) = 2
1076/// LiveOutDepth = depth(c) + 1 = len(a->b->c) + 1 = 3
1077/// LiveInHeight = height(b) + 1 = len(b->c->d->exit) + 1 = 4
1078/// LiveInDepth = depth(b) = len(a->b) = 1
1079///
1080/// LiveOutDepth - LiveInDepth = 3 - 1 = 2
1081/// LiveInHeight - LiveOutHeight = 4 - 2 = 2
1082/// CyclicCriticalPath = min(2, 2) = 2
Andrew Trickd7f890e2013-12-28 21:56:47 +00001083///
1084/// This could be relevant to PostRA scheduling, but is currently implemented
1085/// assuming LiveIntervals.
1086unsigned ScheduleDAGMILive::computeCyclicCriticalPath() {
Andrew Trick483f4192013-08-29 18:04:49 +00001087 // This only applies to single block loop.
1088 if (!BB->isSuccessor(BB))
1089 return 0;
1090
1091 unsigned MaxCyclicLatency = 0;
1092 // Visit each live out vreg def to find def/use pairs that cross iterations.
1093 ArrayRef<unsigned> LiveOuts = RPTracker.getPressure().LiveOutRegs;
1094 for (ArrayRef<unsigned>::iterator RI = LiveOuts.begin(), RE = LiveOuts.end();
1095 RI != RE; ++RI) {
1096 unsigned Reg = *RI;
1097 if (!TRI->isVirtualRegister(Reg))
1098 continue;
1099 const LiveInterval &LI = LIS->getInterval(Reg);
1100 const VNInfo *DefVNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
1101 if (!DefVNI)
1102 continue;
1103
1104 MachineInstr *DefMI = LIS->getInstructionFromIndex(DefVNI->def);
1105 const SUnit *DefSU = getSUnit(DefMI);
1106 if (!DefSU)
1107 continue;
1108
1109 unsigned LiveOutHeight = DefSU->getHeight();
1110 unsigned LiveOutDepth = DefSU->getDepth() + DefSU->Latency;
1111 // Visit all local users of the vreg def.
1112 for (VReg2UseMap::iterator
1113 UI = VRegUses.find(Reg); UI != VRegUses.end(); ++UI) {
1114 if (UI->SU == &ExitSU)
1115 continue;
1116
1117 // Only consider uses of the phi.
Matthias Braun88dd0ab2013-10-10 21:28:52 +00001118 LiveQueryResult LRQ =
1119 LI.Query(LIS->getInstructionIndex(UI->SU->getInstr()));
Andrew Trick483f4192013-08-29 18:04:49 +00001120 if (!LRQ.valueIn()->isPHIDef())
1121 continue;
1122
1123 // Assume that a path spanning two iterations is a cycle, which could
1124 // overestimate in strange cases. This allows cyclic latency to be
1125 // estimated as the minimum slack of the vreg's depth or height.
1126 unsigned CyclicLatency = 0;
1127 if (LiveOutDepth > UI->SU->getDepth())
1128 CyclicLatency = LiveOutDepth - UI->SU->getDepth();
1129
1130 unsigned LiveInHeight = UI->SU->getHeight() + DefSU->Latency;
1131 if (LiveInHeight > LiveOutHeight) {
1132 if (LiveInHeight - LiveOutHeight < CyclicLatency)
1133 CyclicLatency = LiveInHeight - LiveOutHeight;
1134 }
1135 else
1136 CyclicLatency = 0;
1137
1138 DEBUG(dbgs() << "Cyclic Path: SU(" << DefSU->NodeNum << ") -> SU("
1139 << UI->SU->NodeNum << ") = " << CyclicLatency << "c\n");
1140 if (CyclicLatency > MaxCyclicLatency)
1141 MaxCyclicLatency = CyclicLatency;
1142 }
1143 }
1144 DEBUG(dbgs() << "Cyclic Critical Path: " << MaxCyclicLatency << "c\n");
1145 return MaxCyclicLatency;
1146}
1147
Andrew Trick7a8e1002012-09-11 00:39:15 +00001148/// Move an instruction and update register pressure.
Andrew Trickd7f890e2013-12-28 21:56:47 +00001149void ScheduleDAGMILive::scheduleMI(SUnit *SU, bool IsTopNode) {
Andrew Trick7a8e1002012-09-11 00:39:15 +00001150 // Move the instruction to its new location in the instruction stream.
1151 MachineInstr *MI = SU->getInstr();
Andrew Trick02a80da2012-03-08 01:41:12 +00001152
Andrew Trick7a8e1002012-09-11 00:39:15 +00001153 if (IsTopNode) {
1154 assert(SU->isTopReady() && "node still has unscheduled dependencies");
1155 if (&*CurrentTop == MI)
1156 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
Andrew Trick8823dec2012-03-14 04:00:41 +00001157 else {
Andrew Trick7a8e1002012-09-11 00:39:15 +00001158 moveInstruction(MI, CurrentTop);
1159 TopRPTracker.setPos(MI);
Andrew Trick8823dec2012-03-14 04:00:41 +00001160 }
Andrew Trickc3ea0052012-04-24 18:04:37 +00001161
Andrew Trickb6e74712013-09-04 20:59:59 +00001162 if (ShouldTrackPressure) {
1163 // Update top scheduled pressure.
1164 TopRPTracker.advance();
1165 assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
Andrew Trickb248b4a2013-09-06 17:32:47 +00001166 updateScheduledPressure(SU, TopRPTracker.getPressure().MaxSetPressure);
Andrew Trickb6e74712013-09-04 20:59:59 +00001167 }
Andrew Trick7a8e1002012-09-11 00:39:15 +00001168 }
1169 else {
1170 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
1171 MachineBasicBlock::iterator priorII =
1172 priorNonDebug(CurrentBottom, CurrentTop);
1173 if (&*priorII == MI)
1174 CurrentBottom = priorII;
1175 else {
1176 if (&*CurrentTop == MI) {
1177 CurrentTop = nextIfDebug(++CurrentTop, priorII);
1178 TopRPTracker.setPos(CurrentTop);
1179 }
1180 moveInstruction(MI, CurrentBottom);
1181 CurrentBottom = MI;
1182 }
Andrew Trickb6e74712013-09-04 20:59:59 +00001183 if (ShouldTrackPressure) {
1184 // Update bottom scheduled pressure.
1185 SmallVector<unsigned, 8> LiveUses;
1186 BotRPTracker.recede(&LiveUses);
1187 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
Andrew Trickb248b4a2013-09-06 17:32:47 +00001188 updateScheduledPressure(SU, BotRPTracker.getPressure().MaxSetPressure);
Andrew Trickb6e74712013-09-04 20:59:59 +00001189 updatePressureDiffs(LiveUses);
Andrew Trickb6e74712013-09-04 20:59:59 +00001190 }
Andrew Trick7a8e1002012-09-11 00:39:15 +00001191 }
1192}
1193
Andrew Trick263280242012-11-12 19:52:20 +00001194//===----------------------------------------------------------------------===//
1195// LoadClusterMutation - DAG post-processing to cluster loads.
1196//===----------------------------------------------------------------------===//
1197
Andrew Tricka7714a02012-11-12 19:40:10 +00001198namespace {
1199/// \brief Post-process the DAG to create cluster edges between neighboring
1200/// loads.
1201class LoadClusterMutation : public ScheduleDAGMutation {
1202 struct LoadInfo {
1203 SUnit *SU;
1204 unsigned BaseReg;
1205 unsigned Offset;
1206 LoadInfo(SUnit *su, unsigned reg, unsigned ofs)
1207 : SU(su), BaseReg(reg), Offset(ofs) {}
Benjamin Kramerb0f74b22014-03-07 21:35:39 +00001208
1209 bool operator<(const LoadInfo &RHS) const {
1210 return std::tie(BaseReg, Offset) < std::tie(RHS.BaseReg, RHS.Offset);
1211 }
Andrew Tricka7714a02012-11-12 19:40:10 +00001212 };
Andrew Tricka7714a02012-11-12 19:40:10 +00001213
1214 const TargetInstrInfo *TII;
1215 const TargetRegisterInfo *TRI;
1216public:
1217 LoadClusterMutation(const TargetInstrInfo *tii,
1218 const TargetRegisterInfo *tri)
1219 : TII(tii), TRI(tri) {}
1220
Craig Topper4584cd52014-03-07 09:26:03 +00001221 void apply(ScheduleDAGMI *DAG) override;
Andrew Tricka7714a02012-11-12 19:40:10 +00001222protected:
1223 void clusterNeighboringLoads(ArrayRef<SUnit*> Loads, ScheduleDAGMI *DAG);
1224};
1225} // anonymous
1226
Andrew Tricka7714a02012-11-12 19:40:10 +00001227void LoadClusterMutation::clusterNeighboringLoads(ArrayRef<SUnit*> Loads,
1228 ScheduleDAGMI *DAG) {
1229 SmallVector<LoadClusterMutation::LoadInfo,32> LoadRecords;
1230 for (unsigned Idx = 0, End = Loads.size(); Idx != End; ++Idx) {
1231 SUnit *SU = Loads[Idx];
1232 unsigned BaseReg;
1233 unsigned Offset;
1234 if (TII->getLdStBaseRegImmOfs(SU->getInstr(), BaseReg, Offset, TRI))
1235 LoadRecords.push_back(LoadInfo(SU, BaseReg, Offset));
1236 }
1237 if (LoadRecords.size() < 2)
1238 return;
Benjamin Kramerb0f74b22014-03-07 21:35:39 +00001239 std::sort(LoadRecords.begin(), LoadRecords.end());
Andrew Tricka7714a02012-11-12 19:40:10 +00001240 unsigned ClusterLength = 1;
1241 for (unsigned Idx = 0, End = LoadRecords.size(); Idx < (End - 1); ++Idx) {
1242 if (LoadRecords[Idx].BaseReg != LoadRecords[Idx+1].BaseReg) {
1243 ClusterLength = 1;
1244 continue;
1245 }
1246
1247 SUnit *SUa = LoadRecords[Idx].SU;
1248 SUnit *SUb = LoadRecords[Idx+1].SU;
Andrew Trickec369d52012-11-12 21:28:10 +00001249 if (TII->shouldClusterLoads(SUa->getInstr(), SUb->getInstr(), ClusterLength)
Andrew Tricka7714a02012-11-12 19:40:10 +00001250 && DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
1251
1252 DEBUG(dbgs() << "Cluster loads SU(" << SUa->NodeNum << ") - SU("
1253 << SUb->NodeNum << ")\n");
1254 // Copy successor edges from SUa to SUb. Interleaving computation
1255 // dependent on SUa can prevent load combining due to register reuse.
1256 // Predecessor edges do not need to be copied from SUb to SUa since nearby
1257 // loads should have effectively the same inputs.
1258 for (SUnit::const_succ_iterator
1259 SI = SUa->Succs.begin(), SE = SUa->Succs.end(); SI != SE; ++SI) {
1260 if (SI->getSUnit() == SUb)
1261 continue;
1262 DEBUG(dbgs() << " Copy Succ SU(" << SI->getSUnit()->NodeNum << ")\n");
1263 DAG->addEdge(SI->getSUnit(), SDep(SUb, SDep::Artificial));
1264 }
1265 ++ClusterLength;
1266 }
1267 else
1268 ClusterLength = 1;
1269 }
1270}
1271
1272/// \brief Callback from DAG postProcessing to create cluster edges for loads.
1273void LoadClusterMutation::apply(ScheduleDAGMI *DAG) {
1274 // Map DAG NodeNum to store chain ID.
1275 DenseMap<unsigned, unsigned> StoreChainIDs;
1276 // Map each store chain to a set of dependent loads.
1277 SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
1278 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
1279 SUnit *SU = &DAG->SUnits[Idx];
1280 if (!SU->getInstr()->mayLoad())
1281 continue;
1282 unsigned ChainPredID = DAG->SUnits.size();
1283 for (SUnit::const_pred_iterator
1284 PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
1285 if (PI->isCtrl()) {
1286 ChainPredID = PI->getSUnit()->NodeNum;
1287 break;
1288 }
1289 }
1290 // Check if this chain-like pred has been seen
1291 // before. ChainPredID==MaxNodeID for loads at the top of the schedule.
1292 unsigned NumChains = StoreChainDependents.size();
1293 std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
1294 StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
1295 if (Result.second)
1296 StoreChainDependents.resize(NumChains + 1);
1297 StoreChainDependents[Result.first->second].push_back(SU);
1298 }
1299 // Iterate over the store chains.
1300 for (unsigned Idx = 0, End = StoreChainDependents.size(); Idx != End; ++Idx)
1301 clusterNeighboringLoads(StoreChainDependents[Idx], DAG);
1302}
1303
Andrew Trick02a80da2012-03-08 01:41:12 +00001304//===----------------------------------------------------------------------===//
Andrew Trick263280242012-11-12 19:52:20 +00001305// MacroFusion - DAG post-processing to encourage fusion of macro ops.
1306//===----------------------------------------------------------------------===//
1307
1308namespace {
1309/// \brief Post-process the DAG to create cluster edges between instructions
1310/// that may be fused by the processor into a single operation.
1311class MacroFusion : public ScheduleDAGMutation {
1312 const TargetInstrInfo *TII;
1313public:
1314 MacroFusion(const TargetInstrInfo *tii): TII(tii) {}
1315
Craig Topper4584cd52014-03-07 09:26:03 +00001316 void apply(ScheduleDAGMI *DAG) override;
Andrew Trick263280242012-11-12 19:52:20 +00001317};
1318} // anonymous
1319
1320/// \brief Callback from DAG postProcessing to create cluster edges to encourage
1321/// fused operations.
1322void MacroFusion::apply(ScheduleDAGMI *DAG) {
1323 // For now, assume targets can only fuse with the branch.
1324 MachineInstr *Branch = DAG->ExitSU.getInstr();
1325 if (!Branch)
1326 return;
1327
1328 for (unsigned Idx = DAG->SUnits.size(); Idx > 0;) {
1329 SUnit *SU = &DAG->SUnits[--Idx];
1330 if (!TII->shouldScheduleAdjacent(SU->getInstr(), Branch))
1331 continue;
1332
1333 // Create a single weak edge from SU to ExitSU. The only effect is to cause
1334 // bottom-up scheduling to heavily prioritize the clustered SU. There is no
1335 // need to copy predecessor edges from ExitSU to SU, since top-down
1336 // scheduling cannot prioritize ExitSU anyway. To defer top-down scheduling
1337 // of SU, we could create an artificial edge from the deepest root, but it
1338 // hasn't been needed yet.
1339 bool Success = DAG->addEdge(&DAG->ExitSU, SDep(SU, SDep::Cluster));
1340 (void)Success;
1341 assert(Success && "No DAG nodes should be reachable from ExitSU");
1342
1343 DEBUG(dbgs() << "Macro Fuse SU(" << SU->NodeNum << ")\n");
1344 break;
1345 }
1346}
1347
1348//===----------------------------------------------------------------------===//
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001349// CopyConstrain - DAG post-processing to encourage copy elimination.
1350//===----------------------------------------------------------------------===//
1351
1352namespace {
1353/// \brief Post-process the DAG to create weak edges from all uses of a copy to
1354/// the one use that defines the copy's source vreg, most likely an induction
1355/// variable increment.
1356class CopyConstrain : public ScheduleDAGMutation {
1357 // Transient state.
1358 SlotIndex RegionBeginIdx;
Andrew Trick2e875172013-04-24 23:19:56 +00001359 // RegionEndIdx is the slot index of the last non-debug instruction in the
1360 // scheduling region. So we may have RegionBeginIdx == RegionEndIdx.
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001361 SlotIndex RegionEndIdx;
1362public:
1363 CopyConstrain(const TargetInstrInfo *, const TargetRegisterInfo *) {}
1364
Craig Topper4584cd52014-03-07 09:26:03 +00001365 void apply(ScheduleDAGMI *DAG) override;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001366
1367protected:
Andrew Trickd7f890e2013-12-28 21:56:47 +00001368 void constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG);
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001369};
1370} // anonymous
1371
1372/// constrainLocalCopy handles two possibilities:
1373/// 1) Local src:
1374/// I0: = dst
1375/// I1: src = ...
1376/// I2: = dst
1377/// I3: dst = src (copy)
1378/// (create pred->succ edges I0->I1, I2->I1)
1379///
1380/// 2) Local copy:
1381/// I0: dst = src (copy)
1382/// I1: = dst
1383/// I2: src = ...
1384/// I3: = dst
1385/// (create pred->succ edges I1->I2, I3->I2)
1386///
1387/// Although the MachineScheduler is currently constrained to single blocks,
1388/// this algorithm should handle extended blocks. An EBB is a set of
1389/// contiguously numbered blocks such that the previous block in the EBB is
1390/// always the single predecessor.
Andrew Trickd7f890e2013-12-28 21:56:47 +00001391void CopyConstrain::constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG) {
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001392 LiveIntervals *LIS = DAG->getLIS();
1393 MachineInstr *Copy = CopySU->getInstr();
1394
1395 // Check for pure vreg copies.
1396 unsigned SrcReg = Copy->getOperand(1).getReg();
1397 if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
1398 return;
1399
1400 unsigned DstReg = Copy->getOperand(0).getReg();
1401 if (!TargetRegisterInfo::isVirtualRegister(DstReg))
1402 return;
1403
1404 // Check if either the dest or source is local. If it's live across a back
1405 // edge, it's not local. Note that if both vregs are live across the back
1406 // edge, we cannot successfully contrain the copy without cyclic scheduling.
1407 unsigned LocalReg = DstReg;
1408 unsigned GlobalReg = SrcReg;
1409 LiveInterval *LocalLI = &LIS->getInterval(LocalReg);
1410 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx)) {
1411 LocalReg = SrcReg;
1412 GlobalReg = DstReg;
1413 LocalLI = &LIS->getInterval(LocalReg);
1414 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx))
1415 return;
1416 }
1417 LiveInterval *GlobalLI = &LIS->getInterval(GlobalReg);
1418
1419 // Find the global segment after the start of the local LI.
1420 LiveInterval::iterator GlobalSegment = GlobalLI->find(LocalLI->beginIndex());
1421 // If GlobalLI does not overlap LocalLI->start, then a copy directly feeds a
1422 // local live range. We could create edges from other global uses to the local
1423 // start, but the coalescer should have already eliminated these cases, so
1424 // don't bother dealing with it.
1425 if (GlobalSegment == GlobalLI->end())
1426 return;
1427
1428 // If GlobalSegment is killed at the LocalLI->start, the call to find()
1429 // returned the next global segment. But if GlobalSegment overlaps with
1430 // LocalLI->start, then advance to the next segement. If a hole in GlobalLI
1431 // exists in LocalLI's vicinity, GlobalSegment will be the end of the hole.
1432 if (GlobalSegment->contains(LocalLI->beginIndex()))
1433 ++GlobalSegment;
1434
1435 if (GlobalSegment == GlobalLI->end())
1436 return;
1437
1438 // Check if GlobalLI contains a hole in the vicinity of LocalLI.
1439 if (GlobalSegment != GlobalLI->begin()) {
1440 // Two address defs have no hole.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001441 if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->end,
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001442 GlobalSegment->start)) {
1443 return;
1444 }
Andrew Trickd9761772013-07-30 19:59:08 +00001445 // If the prior global segment may be defined by the same two-address
1446 // instruction that also defines LocalLI, then can't make a hole here.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001447 if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->start,
Andrew Trickd9761772013-07-30 19:59:08 +00001448 LocalLI->beginIndex())) {
1449 return;
1450 }
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001451 // If GlobalLI has a prior segment, it must be live into the EBB. Otherwise
1452 // it would be a disconnected component in the live range.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001453 assert(std::prev(GlobalSegment)->start < LocalLI->beginIndex() &&
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001454 "Disconnected LRG within the scheduling region.");
1455 }
1456 MachineInstr *GlobalDef = LIS->getInstructionFromIndex(GlobalSegment->start);
1457 if (!GlobalDef)
1458 return;
1459
1460 SUnit *GlobalSU = DAG->getSUnit(GlobalDef);
1461 if (!GlobalSU)
1462 return;
1463
1464 // GlobalDef is the bottom of the GlobalLI hole. Open the hole by
1465 // constraining the uses of the last local def to precede GlobalDef.
1466 SmallVector<SUnit*,8> LocalUses;
1467 const VNInfo *LastLocalVN = LocalLI->getVNInfoBefore(LocalLI->endIndex());
1468 MachineInstr *LastLocalDef = LIS->getInstructionFromIndex(LastLocalVN->def);
1469 SUnit *LastLocalSU = DAG->getSUnit(LastLocalDef);
1470 for (SUnit::const_succ_iterator
1471 I = LastLocalSU->Succs.begin(), E = LastLocalSU->Succs.end();
1472 I != E; ++I) {
1473 if (I->getKind() != SDep::Data || I->getReg() != LocalReg)
1474 continue;
1475 if (I->getSUnit() == GlobalSU)
1476 continue;
1477 if (!DAG->canAddEdge(GlobalSU, I->getSUnit()))
1478 return;
1479 LocalUses.push_back(I->getSUnit());
1480 }
1481 // Open the top of the GlobalLI hole by constraining any earlier global uses
1482 // to precede the start of LocalLI.
1483 SmallVector<SUnit*,8> GlobalUses;
1484 MachineInstr *FirstLocalDef =
1485 LIS->getInstructionFromIndex(LocalLI->beginIndex());
1486 SUnit *FirstLocalSU = DAG->getSUnit(FirstLocalDef);
1487 for (SUnit::const_pred_iterator
1488 I = GlobalSU->Preds.begin(), E = GlobalSU->Preds.end(); I != E; ++I) {
1489 if (I->getKind() != SDep::Anti || I->getReg() != GlobalReg)
1490 continue;
1491 if (I->getSUnit() == FirstLocalSU)
1492 continue;
1493 if (!DAG->canAddEdge(FirstLocalSU, I->getSUnit()))
1494 return;
1495 GlobalUses.push_back(I->getSUnit());
1496 }
1497 DEBUG(dbgs() << "Constraining copy SU(" << CopySU->NodeNum << ")\n");
1498 // Add the weak edges.
1499 for (SmallVectorImpl<SUnit*>::const_iterator
1500 I = LocalUses.begin(), E = LocalUses.end(); I != E; ++I) {
1501 DEBUG(dbgs() << " Local use SU(" << (*I)->NodeNum << ") -> SU("
1502 << GlobalSU->NodeNum << ")\n");
1503 DAG->addEdge(GlobalSU, SDep(*I, SDep::Weak));
1504 }
1505 for (SmallVectorImpl<SUnit*>::const_iterator
1506 I = GlobalUses.begin(), E = GlobalUses.end(); I != E; ++I) {
1507 DEBUG(dbgs() << " Global use SU(" << (*I)->NodeNum << ") -> SU("
1508 << FirstLocalSU->NodeNum << ")\n");
1509 DAG->addEdge(FirstLocalSU, SDep(*I, SDep::Weak));
1510 }
1511}
1512
1513/// \brief Callback from DAG postProcessing to create weak edges to encourage
1514/// copy elimination.
1515void CopyConstrain::apply(ScheduleDAGMI *DAG) {
Andrew Trickd7f890e2013-12-28 21:56:47 +00001516 assert(DAG->hasVRegLiveness() && "Expect VRegs with LiveIntervals");
1517
Andrew Trick2e875172013-04-24 23:19:56 +00001518 MachineBasicBlock::iterator FirstPos = nextIfDebug(DAG->begin(), DAG->end());
1519 if (FirstPos == DAG->end())
1520 return;
1521 RegionBeginIdx = DAG->getLIS()->getInstructionIndex(&*FirstPos);
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001522 RegionEndIdx = DAG->getLIS()->getInstructionIndex(
1523 &*priorNonDebug(DAG->end(), DAG->begin()));
1524
1525 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
1526 SUnit *SU = &DAG->SUnits[Idx];
1527 if (!SU->getInstr()->isCopy())
1528 continue;
1529
Andrew Trickd7f890e2013-12-28 21:56:47 +00001530 constrainLocalCopy(SU, static_cast<ScheduleDAGMILive*>(DAG));
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001531 }
1532}
1533
1534//===----------------------------------------------------------------------===//
Andrew Trickfc127d12013-12-07 05:59:44 +00001535// MachineSchedStrategy helpers used by GenericScheduler, GenericPostScheduler
1536// and possibly other custom schedulers.
Andrew Trickd14d7c22013-12-28 21:56:57 +00001537//===----------------------------------------------------------------------===//
Andrew Tricke1c034f2012-01-17 06:55:03 +00001538
Andrew Trick5a22df42013-12-05 17:56:02 +00001539static const unsigned InvalidCycle = ~0U;
1540
Andrew Trickfc127d12013-12-07 05:59:44 +00001541SchedBoundary::~SchedBoundary() { delete HazardRec; }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001542
Andrew Trickfc127d12013-12-07 05:59:44 +00001543void SchedBoundary::reset() {
1544 // A new HazardRec is created for each DAG and owned by SchedBoundary.
1545 // Destroying and reconstructing it is very expensive though. So keep
1546 // invalid, placeholder HazardRecs.
1547 if (HazardRec && HazardRec->isEnabled()) {
1548 delete HazardRec;
1549 HazardRec = 0;
1550 }
1551 Available.clear();
1552 Pending.clear();
1553 CheckPending = false;
1554 NextSUs.clear();
1555 CurrCycle = 0;
1556 CurrMOps = 0;
1557 MinReadyCycle = UINT_MAX;
1558 ExpectedLatency = 0;
1559 DependentLatency = 0;
1560 RetiredMOps = 0;
1561 MaxExecutedResCount = 0;
1562 ZoneCritResIdx = 0;
1563 IsResourceLimited = false;
1564 ReservedCycles.clear();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001565#ifndef NDEBUG
Andrew Trickd14d7c22013-12-28 21:56:57 +00001566 // Track the maximum number of stall cycles that could arise either from the
1567 // latency of a DAG edge or the number of cycles that a processor resource is
1568 // reserved (SchedBoundary::ReservedCycles).
Andrew Trickfc127d12013-12-07 05:59:44 +00001569 MaxObservedLatency = 0;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001570#endif
Andrew Trickfc127d12013-12-07 05:59:44 +00001571 // Reserve a zero-count for invalid CritResIdx.
1572 ExecutedResCounts.resize(1);
1573 assert(!ExecutedResCounts[0] && "nonzero count for bad resource");
1574}
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001575
Andrew Trickfc127d12013-12-07 05:59:44 +00001576void SchedRemainder::
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001577init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
1578 reset();
1579 if (!SchedModel->hasInstrSchedModel())
1580 return;
1581 RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
1582 for (std::vector<SUnit>::iterator
1583 I = DAG->SUnits.begin(), E = DAG->SUnits.end(); I != E; ++I) {
1584 const MCSchedClassDesc *SC = DAG->getSchedClass(&*I);
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001585 RemIssueCount += SchedModel->getNumMicroOps(I->getInstr(), SC)
1586 * SchedModel->getMicroOpFactor();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001587 for (TargetSchedModel::ProcResIter
1588 PI = SchedModel->getWriteProcResBegin(SC),
1589 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1590 unsigned PIdx = PI->ProcResourceIdx;
1591 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1592 RemainingCounts[PIdx] += (Factor * PI->Cycles);
1593 }
1594 }
1595}
1596
Andrew Trickfc127d12013-12-07 05:59:44 +00001597void SchedBoundary::
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001598init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
1599 reset();
1600 DAG = dag;
1601 SchedModel = smodel;
1602 Rem = rem;
Andrew Trick5a22df42013-12-05 17:56:02 +00001603 if (SchedModel->hasInstrSchedModel()) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001604 ExecutedResCounts.resize(SchedModel->getNumProcResourceKinds());
Andrew Trick5a22df42013-12-05 17:56:02 +00001605 ReservedCycles.resize(SchedModel->getNumProcResourceKinds(), InvalidCycle);
1606 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001607}
1608
Andrew Trick880e5732013-12-05 17:55:58 +00001609/// Compute the stall cycles based on this SUnit's ready time. Heuristics treat
1610/// these "soft stalls" differently than the hard stall cycles based on CPU
1611/// resources and computed by checkHazard(). A fully in-order model
1612/// (MicroOpBufferSize==0) will not make use of this since instructions are not
1613/// available for scheduling until they are ready. However, a weaker in-order
1614/// model may use this for heuristics. For example, if a processor has in-order
1615/// behavior when reading certain resources, this may come into play.
Andrew Trickfc127d12013-12-07 05:59:44 +00001616unsigned SchedBoundary::getLatencyStallCycles(SUnit *SU) {
Andrew Trick880e5732013-12-05 17:55:58 +00001617 if (!SU->isUnbuffered)
1618 return 0;
1619
1620 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
1621 if (ReadyCycle > CurrCycle)
1622 return ReadyCycle - CurrCycle;
1623 return 0;
1624}
1625
Andrew Trick5a22df42013-12-05 17:56:02 +00001626/// Compute the next cycle at which the given processor resource can be
1627/// scheduled.
Andrew Trickfc127d12013-12-07 05:59:44 +00001628unsigned SchedBoundary::
Andrew Trick5a22df42013-12-05 17:56:02 +00001629getNextResourceCycle(unsigned PIdx, unsigned Cycles) {
1630 unsigned NextUnreserved = ReservedCycles[PIdx];
1631 // If this resource has never been used, always return cycle zero.
1632 if (NextUnreserved == InvalidCycle)
1633 return 0;
1634 // For bottom-up scheduling add the cycles needed for the current operation.
1635 if (!isTop())
1636 NextUnreserved += Cycles;
1637 return NextUnreserved;
1638}
1639
Andrew Trick8c9e6722012-06-29 03:23:24 +00001640/// Does this SU have a hazard within the current instruction group.
1641///
1642/// The scheduler supports two modes of hazard recognition. The first is the
1643/// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
1644/// supports highly complicated in-order reservation tables
1645/// (ScoreboardHazardRecognizer) and arbitraty target-specific logic.
1646///
1647/// The second is a streamlined mechanism that checks for hazards based on
1648/// simple counters that the scheduler itself maintains. It explicitly checks
1649/// for instruction dispatch limitations, including the number of micro-ops that
1650/// can dispatch per cycle.
1651///
1652/// TODO: Also check whether the SU must start a new group.
Andrew Trickfc127d12013-12-07 05:59:44 +00001653bool SchedBoundary::checkHazard(SUnit *SU) {
Andrew Trickd14d7c22013-12-28 21:56:57 +00001654 if (HazardRec->isEnabled()
1655 && HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard) {
1656 return true;
1657 }
Andrew Trickdd79f0f2012-10-10 05:43:09 +00001658 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
Andrew Tricke2ff5752013-06-15 04:49:49 +00001659 if ((CurrMOps > 0) && (CurrMOps + uops > SchedModel->getIssueWidth())) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001660 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") uops="
1661 << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
Andrew Trick8c9e6722012-06-29 03:23:24 +00001662 return true;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001663 }
Andrew Trick5a22df42013-12-05 17:56:02 +00001664 if (SchedModel->hasInstrSchedModel() && SU->hasReservedResource) {
1665 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1666 for (TargetSchedModel::ProcResIter
1667 PI = SchedModel->getWriteProcResBegin(SC),
1668 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1669 if (getNextResourceCycle(PI->ProcResourceIdx, PI->Cycles) > CurrCycle)
1670 return true;
1671 }
1672 }
Andrew Trick8c9e6722012-06-29 03:23:24 +00001673 return false;
1674}
1675
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001676// Find the unscheduled node in ReadySUs with the highest latency.
Andrew Trickfc127d12013-12-07 05:59:44 +00001677unsigned SchedBoundary::
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001678findMaxLatency(ArrayRef<SUnit*> ReadySUs) {
1679 SUnit *LateSU = 0;
1680 unsigned RemLatency = 0;
1681 for (ArrayRef<SUnit*>::iterator I = ReadySUs.begin(), E = ReadySUs.end();
Andrew Trickd6d5ad32012-12-18 20:52:56 +00001682 I != E; ++I) {
1683 unsigned L = getUnscheduledLatency(*I);
Andrew Trickf5b8ef22013-06-15 04:49:44 +00001684 if (L > RemLatency) {
Andrew Trickd6d5ad32012-12-18 20:52:56 +00001685 RemLatency = L;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001686 LateSU = *I;
Andrew Trickf5b8ef22013-06-15 04:49:44 +00001687 }
Andrew Trickd6d5ad32012-12-18 20:52:56 +00001688 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001689 if (LateSU) {
1690 DEBUG(dbgs() << Available.getName() << " RemLatency SU("
1691 << LateSU->NodeNum << ") " << RemLatency << "c\n");
Andrew Trickd6d5ad32012-12-18 20:52:56 +00001692 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001693 return RemLatency;
1694}
Andrew Trickf5b8ef22013-06-15 04:49:44 +00001695
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001696// Count resources in this zone and the remaining unscheduled
1697// instruction. Return the max count, scaled. Set OtherCritIdx to the critical
1698// resource index, or zero if the zone is issue limited.
Andrew Trickfc127d12013-12-07 05:59:44 +00001699unsigned SchedBoundary::
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001700getOtherResourceCount(unsigned &OtherCritIdx) {
Alexey Samsonov64c391d2013-07-19 08:55:18 +00001701 OtherCritIdx = 0;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001702 if (!SchedModel->hasInstrSchedModel())
1703 return 0;
1704
1705 unsigned OtherCritCount = Rem->RemIssueCount
1706 + (RetiredMOps * SchedModel->getMicroOpFactor());
1707 DEBUG(dbgs() << " " << Available.getName() << " + Remain MOps: "
1708 << OtherCritCount / SchedModel->getMicroOpFactor() << '\n');
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001709 for (unsigned PIdx = 1, PEnd = SchedModel->getNumProcResourceKinds();
1710 PIdx != PEnd; ++PIdx) {
1711 unsigned OtherCount = getResourceCount(PIdx) + Rem->RemainingCounts[PIdx];
1712 if (OtherCount > OtherCritCount) {
1713 OtherCritCount = OtherCount;
1714 OtherCritIdx = PIdx;
1715 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001716 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001717 if (OtherCritIdx) {
1718 DEBUG(dbgs() << " " << Available.getName() << " + Remain CritRes: "
1719 << OtherCritCount / SchedModel->getResourceFactor(OtherCritIdx)
Andrew Trickfc127d12013-12-07 05:59:44 +00001720 << " " << SchedModel->getResourceName(OtherCritIdx) << "\n");
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001721 }
1722 return OtherCritCount;
1723}
1724
Andrew Trickfc127d12013-12-07 05:59:44 +00001725void SchedBoundary::releaseNode(SUnit *SU, unsigned ReadyCycle) {
Andrew Trick61f1a272012-05-24 22:11:09 +00001726 if (ReadyCycle < MinReadyCycle)
1727 MinReadyCycle = ReadyCycle;
1728
1729 // Check for interlocks first. For the purpose of other heuristics, an
1730 // instruction that cannot issue appears as if it's not in the ReadyQueue.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001731 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
1732 if ((!IsBuffered && ReadyCycle > CurrCycle) || checkHazard(SU))
Andrew Trick61f1a272012-05-24 22:11:09 +00001733 Pending.push(SU);
1734 else
1735 Available.push(SU);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001736
1737 // Record this node as an immediate dependent of the scheduled node.
1738 NextSUs.insert(SU);
Andrew Trick61f1a272012-05-24 22:11:09 +00001739}
1740
Andrew Trickfc127d12013-12-07 05:59:44 +00001741void SchedBoundary::releaseTopNode(SUnit *SU) {
1742 if (SU->isScheduled)
1743 return;
1744
1745 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1746 I != E; ++I) {
1747 if (I->isWeak())
1748 continue;
1749 unsigned PredReadyCycle = I->getSUnit()->TopReadyCycle;
1750 unsigned Latency = I->getLatency();
1751#ifndef NDEBUG
1752 MaxObservedLatency = std::max(Latency, MaxObservedLatency);
1753#endif
1754 if (SU->TopReadyCycle < PredReadyCycle + Latency)
1755 SU->TopReadyCycle = PredReadyCycle + Latency;
1756 }
1757 releaseNode(SU, SU->TopReadyCycle);
1758}
1759
1760void SchedBoundary::releaseBottomNode(SUnit *SU) {
1761 if (SU->isScheduled)
1762 return;
1763
1764 assert(SU->getInstr() && "Scheduled SUnit must have instr");
1765
1766 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1767 I != E; ++I) {
1768 if (I->isWeak())
1769 continue;
1770 unsigned SuccReadyCycle = I->getSUnit()->BotReadyCycle;
1771 unsigned Latency = I->getLatency();
1772#ifndef NDEBUG
1773 MaxObservedLatency = std::max(Latency, MaxObservedLatency);
1774#endif
1775 if (SU->BotReadyCycle < SuccReadyCycle + Latency)
1776 SU->BotReadyCycle = SuccReadyCycle + Latency;
1777 }
1778 releaseNode(SU, SU->BotReadyCycle);
1779}
1780
Andrew Trick61f1a272012-05-24 22:11:09 +00001781/// Move the boundary of scheduled code by one cycle.
Andrew Trickfc127d12013-12-07 05:59:44 +00001782void SchedBoundary::bumpCycle(unsigned NextCycle) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001783 if (SchedModel->getMicroOpBufferSize() == 0) {
1784 assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
1785 if (MinReadyCycle > NextCycle)
1786 NextCycle = MinReadyCycle;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001787 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001788 // Update the current micro-ops, which will issue in the next cycle.
1789 unsigned DecMOps = SchedModel->getIssueWidth() * (NextCycle - CurrCycle);
1790 CurrMOps = (CurrMOps <= DecMOps) ? 0 : CurrMOps - DecMOps;
1791
1792 // Decrement DependentLatency based on the next cycle.
Andrew Trickf5b8ef22013-06-15 04:49:44 +00001793 if ((NextCycle - CurrCycle) > DependentLatency)
1794 DependentLatency = 0;
1795 else
1796 DependentLatency -= (NextCycle - CurrCycle);
Andrew Trick61f1a272012-05-24 22:11:09 +00001797
1798 if (!HazardRec->isEnabled()) {
Andrew Trick45446062012-06-05 21:11:27 +00001799 // Bypass HazardRec virtual calls.
Andrew Trick61f1a272012-05-24 22:11:09 +00001800 CurrCycle = NextCycle;
1801 }
1802 else {
Andrew Trick45446062012-06-05 21:11:27 +00001803 // Bypass getHazardType calls in case of long latency.
Andrew Trick61f1a272012-05-24 22:11:09 +00001804 for (; CurrCycle != NextCycle; ++CurrCycle) {
1805 if (isTop())
1806 HazardRec->AdvanceCycle();
1807 else
1808 HazardRec->RecedeCycle();
1809 }
1810 }
1811 CheckPending = true;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001812 unsigned LFactor = SchedModel->getLatencyFactor();
1813 IsResourceLimited =
1814 (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
1815 > (int)LFactor;
Andrew Trick61f1a272012-05-24 22:11:09 +00001816
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001817 DEBUG(dbgs() << "Cycle: " << CurrCycle << ' ' << Available.getName() << '\n');
1818}
1819
Andrew Trickfc127d12013-12-07 05:59:44 +00001820void SchedBoundary::incExecutedResources(unsigned PIdx, unsigned Count) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001821 ExecutedResCounts[PIdx] += Count;
1822 if (ExecutedResCounts[PIdx] > MaxExecutedResCount)
1823 MaxExecutedResCount = ExecutedResCounts[PIdx];
Andrew Trick61f1a272012-05-24 22:11:09 +00001824}
1825
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001826/// Add the given processor resource to this scheduled zone.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001827///
1828/// \param Cycles indicates the number of consecutive (non-pipelined) cycles
1829/// during which this resource is consumed.
1830///
1831/// \return the next cycle at which the instruction may execute without
1832/// oversubscribing resources.
Andrew Trickfc127d12013-12-07 05:59:44 +00001833unsigned SchedBoundary::
Andrew Trick5a22df42013-12-05 17:56:02 +00001834countResource(unsigned PIdx, unsigned Cycles, unsigned NextCycle) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001835 unsigned Factor = SchedModel->getResourceFactor(PIdx);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001836 unsigned Count = Factor * Cycles;
Andrew Trickfc127d12013-12-07 05:59:44 +00001837 DEBUG(dbgs() << " " << SchedModel->getResourceName(PIdx)
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001838 << " +" << Cycles << "x" << Factor << "u\n");
1839
1840 // Update Executed resources counts.
1841 incExecutedResources(PIdx, Count);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001842 assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
1843 Rem->RemainingCounts[PIdx] -= Count;
1844
Andrew Trickb13ef172013-07-19 00:20:07 +00001845 // Check if this resource exceeds the current critical resource. If so, it
1846 // becomes the critical resource.
1847 if (ZoneCritResIdx != PIdx && (getResourceCount(PIdx) > getCriticalCount())) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001848 ZoneCritResIdx = PIdx;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001849 DEBUG(dbgs() << " *** Critical resource "
Andrew Trickfc127d12013-12-07 05:59:44 +00001850 << SchedModel->getResourceName(PIdx) << ": "
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001851 << getResourceCount(PIdx) / SchedModel->getLatencyFactor() << "c\n");
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001852 }
Andrew Trick5a22df42013-12-05 17:56:02 +00001853 // For reserved resources, record the highest cycle using the resource.
1854 unsigned NextAvailable = getNextResourceCycle(PIdx, Cycles);
1855 if (NextAvailable > CurrCycle) {
1856 DEBUG(dbgs() << " Resource conflict: "
1857 << SchedModel->getProcResource(PIdx)->Name << " reserved until @"
1858 << NextAvailable << "\n");
1859 }
1860 return NextAvailable;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001861}
1862
Andrew Trick45446062012-06-05 21:11:27 +00001863/// Move the boundary of scheduled code by one SUnit.
Andrew Trickfc127d12013-12-07 05:59:44 +00001864void SchedBoundary::bumpNode(SUnit *SU) {
Andrew Trick45446062012-06-05 21:11:27 +00001865 // Update the reservation table.
1866 if (HazardRec->isEnabled()) {
1867 if (!isTop() && SU->isCall) {
1868 // Calls are scheduled with their preceding instructions. For bottom-up
1869 // scheduling, clear the pipeline state before emitting.
1870 HazardRec->Reset();
1871 }
1872 HazardRec->EmitInstruction(SU);
1873 }
Andrew Trick5a22df42013-12-05 17:56:02 +00001874 // checkHazard should prevent scheduling multiple instructions per cycle that
1875 // exceed the issue width.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001876 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1877 unsigned IncMOps = SchedModel->getNumMicroOps(SU->getInstr());
Daniel Jasper0d92abd2013-12-06 08:58:22 +00001878 assert(
1879 (CurrMOps == 0 || (CurrMOps + IncMOps) <= SchedModel->getIssueWidth()) &&
Andrew Trickf7760a22013-12-06 17:19:20 +00001880 "Cannot schedule this instruction's MicroOps in the current cycle.");
Andrew Trick5a22df42013-12-05 17:56:02 +00001881
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001882 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
1883 DEBUG(dbgs() << " Ready @" << ReadyCycle << "c\n");
1884
Andrew Trick5a22df42013-12-05 17:56:02 +00001885 unsigned NextCycle = CurrCycle;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001886 switch (SchedModel->getMicroOpBufferSize()) {
1887 case 0:
1888 assert(ReadyCycle <= CurrCycle && "Broken PendingQueue");
1889 break;
1890 case 1:
1891 if (ReadyCycle > NextCycle) {
1892 NextCycle = ReadyCycle;
1893 DEBUG(dbgs() << " *** Stall until: " << ReadyCycle << "\n");
1894 }
1895 break;
1896 default:
1897 // We don't currently model the OOO reorder buffer, so consider all
Andrew Trick880e5732013-12-05 17:55:58 +00001898 // scheduled MOps to be "retired". We do loosely model in-order resource
1899 // latency. If this instruction uses an in-order resource, account for any
1900 // likely stall cycles.
1901 if (SU->isUnbuffered && ReadyCycle > NextCycle)
1902 NextCycle = ReadyCycle;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001903 break;
1904 }
1905 RetiredMOps += IncMOps;
1906
1907 // Update resource counts and critical resource.
1908 if (SchedModel->hasInstrSchedModel()) {
1909 unsigned DecRemIssue = IncMOps * SchedModel->getMicroOpFactor();
1910 assert(Rem->RemIssueCount >= DecRemIssue && "MOps double counted");
1911 Rem->RemIssueCount -= DecRemIssue;
1912 if (ZoneCritResIdx) {
1913 // Scale scheduled micro-ops for comparing with the critical resource.
1914 unsigned ScaledMOps =
1915 RetiredMOps * SchedModel->getMicroOpFactor();
1916
1917 // If scaled micro-ops are now more than the previous critical resource by
1918 // a full cycle, then micro-ops issue becomes critical.
1919 if ((int)(ScaledMOps - getResourceCount(ZoneCritResIdx))
1920 >= (int)SchedModel->getLatencyFactor()) {
1921 ZoneCritResIdx = 0;
1922 DEBUG(dbgs() << " *** Critical resource NumMicroOps: "
1923 << ScaledMOps / SchedModel->getLatencyFactor() << "c\n");
1924 }
1925 }
1926 for (TargetSchedModel::ProcResIter
1927 PI = SchedModel->getWriteProcResBegin(SC),
1928 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1929 unsigned RCycle =
Andrew Trick5a22df42013-12-05 17:56:02 +00001930 countResource(PI->ProcResourceIdx, PI->Cycles, NextCycle);
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001931 if (RCycle > NextCycle)
1932 NextCycle = RCycle;
1933 }
Andrew Trick5a22df42013-12-05 17:56:02 +00001934 if (SU->hasReservedResource) {
1935 // For reserved resources, record the highest cycle using the resource.
1936 // For top-down scheduling, this is the cycle in which we schedule this
1937 // instruction plus the number of cycles the operations reserves the
1938 // resource. For bottom-up is it simply the instruction's cycle.
1939 for (TargetSchedModel::ProcResIter
1940 PI = SchedModel->getWriteProcResBegin(SC),
1941 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1942 unsigned PIdx = PI->ProcResourceIdx;
Andrew Trickd14d7c22013-12-28 21:56:57 +00001943 if (SchedModel->getProcResource(PIdx)->BufferSize == 0) {
Andrew Trick5a22df42013-12-05 17:56:02 +00001944 ReservedCycles[PIdx] = isTop() ? NextCycle + PI->Cycles : NextCycle;
Andrew Trickd14d7c22013-12-28 21:56:57 +00001945#ifndef NDEBUG
1946 MaxObservedLatency = std::max(PI->Cycles, MaxObservedLatency);
1947#endif
1948 }
Andrew Trick5a22df42013-12-05 17:56:02 +00001949 }
1950 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001951 }
1952 // Update ExpectedLatency and DependentLatency.
1953 unsigned &TopLatency = isTop() ? ExpectedLatency : DependentLatency;
1954 unsigned &BotLatency = isTop() ? DependentLatency : ExpectedLatency;
1955 if (SU->getDepth() > TopLatency) {
1956 TopLatency = SU->getDepth();
1957 DEBUG(dbgs() << " " << Available.getName()
1958 << " TopLatency SU(" << SU->NodeNum << ") " << TopLatency << "c\n");
1959 }
1960 if (SU->getHeight() > BotLatency) {
1961 BotLatency = SU->getHeight();
1962 DEBUG(dbgs() << " " << Available.getName()
1963 << " BotLatency SU(" << SU->NodeNum << ") " << BotLatency << "c\n");
1964 }
1965 // If we stall for any reason, bump the cycle.
1966 if (NextCycle > CurrCycle) {
1967 bumpCycle(NextCycle);
1968 }
1969 else {
1970 // After updating ZoneCritResIdx and ExpectedLatency, check if we're
Alp Tokercb402912014-01-24 17:20:08 +00001971 // resource limited. If a stall occurred, bumpCycle does this.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001972 unsigned LFactor = SchedModel->getLatencyFactor();
1973 IsResourceLimited =
1974 (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
1975 > (int)LFactor;
1976 }
Andrew Trick5a22df42013-12-05 17:56:02 +00001977 // Update CurrMOps after calling bumpCycle to handle stalls, since bumpCycle
1978 // resets CurrMOps. Loop to handle instructions with more MOps than issue in
1979 // one cycle. Since we commonly reach the max MOps here, opportunistically
1980 // bump the cycle to avoid uselessly checking everything in the readyQ.
1981 CurrMOps += IncMOps;
1982 while (CurrMOps >= SchedModel->getIssueWidth()) {
Andrew Trick5a22df42013-12-05 17:56:02 +00001983 DEBUG(dbgs() << " *** Max MOps " << CurrMOps
1984 << " at cycle " << CurrCycle << '\n');
Andrew Trickd14d7c22013-12-28 21:56:57 +00001985 bumpCycle(++NextCycle);
Andrew Trick5a22df42013-12-05 17:56:02 +00001986 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001987 DEBUG(dumpScheduledState());
Andrew Trick45446062012-06-05 21:11:27 +00001988}
1989
Andrew Trick61f1a272012-05-24 22:11:09 +00001990/// Release pending ready nodes in to the available queue. This makes them
1991/// visible to heuristics.
Andrew Trickfc127d12013-12-07 05:59:44 +00001992void SchedBoundary::releasePending() {
Andrew Trick61f1a272012-05-24 22:11:09 +00001993 // If the available queue is empty, it is safe to reset MinReadyCycle.
1994 if (Available.empty())
1995 MinReadyCycle = UINT_MAX;
1996
1997 // Check to see if any of the pending instructions are ready to issue. If
1998 // so, add them to the available queue.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001999 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
Andrew Trick61f1a272012-05-24 22:11:09 +00002000 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
2001 SUnit *SU = *(Pending.begin()+i);
Andrew Trick45446062012-06-05 21:11:27 +00002002 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
Andrew Trick61f1a272012-05-24 22:11:09 +00002003
2004 if (ReadyCycle < MinReadyCycle)
2005 MinReadyCycle = ReadyCycle;
2006
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002007 if (!IsBuffered && ReadyCycle > CurrCycle)
Andrew Trick61f1a272012-05-24 22:11:09 +00002008 continue;
2009
Andrew Trick8c9e6722012-06-29 03:23:24 +00002010 if (checkHazard(SU))
Andrew Trick61f1a272012-05-24 22:11:09 +00002011 continue;
2012
2013 Available.push(SU);
2014 Pending.remove(Pending.begin()+i);
2015 --i; --e;
2016 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002017 DEBUG(if (!Pending.empty()) Pending.dump());
Andrew Trick61f1a272012-05-24 22:11:09 +00002018 CheckPending = false;
2019}
2020
2021/// Remove SU from the ready set for this boundary.
Andrew Trickfc127d12013-12-07 05:59:44 +00002022void SchedBoundary::removeReady(SUnit *SU) {
Andrew Trick61f1a272012-05-24 22:11:09 +00002023 if (Available.isInQueue(SU))
2024 Available.remove(Available.find(SU));
2025 else {
2026 assert(Pending.isInQueue(SU) && "bad ready count");
2027 Pending.remove(Pending.find(SU));
2028 }
2029}
2030
2031/// If this queue only has one ready candidate, return it. As a side effect,
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002032/// defer any nodes that now hit a hazard, and advance the cycle until at least
2033/// one node is ready. If multiple instructions are ready, return NULL.
Andrew Trickfc127d12013-12-07 05:59:44 +00002034SUnit *SchedBoundary::pickOnlyChoice() {
Andrew Trick61f1a272012-05-24 22:11:09 +00002035 if (CheckPending)
2036 releasePending();
2037
Andrew Tricke2ff5752013-06-15 04:49:49 +00002038 if (CurrMOps > 0) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002039 // Defer any ready instrs that now have a hazard.
2040 for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
2041 if (checkHazard(*I)) {
2042 Pending.push(*I);
2043 I = Available.remove(I);
2044 continue;
2045 }
2046 ++I;
2047 }
2048 }
Andrew Trick61f1a272012-05-24 22:11:09 +00002049 for (unsigned i = 0; Available.empty(); ++i) {
Andrew Trickde2109e2013-06-15 04:49:57 +00002050 assert(i <= (HazardRec->getMaxLookAhead() + MaxObservedLatency) &&
Andrew Trick45446062012-06-05 21:11:27 +00002051 "permanent hazard"); (void)i;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002052 bumpCycle(CurrCycle + 1);
Andrew Trick61f1a272012-05-24 22:11:09 +00002053 releasePending();
2054 }
2055 if (Available.size() == 1)
2056 return *Available.begin();
2057 return NULL;
2058}
2059
Andrew Trick8e8415f2013-06-15 05:46:47 +00002060#ifndef NDEBUG
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002061// This is useful information to dump after bumpNode.
2062// Note that the Queue contents are more useful before pickNodeFromQueue.
Andrew Trickfc127d12013-12-07 05:59:44 +00002063void SchedBoundary::dumpScheduledState() {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002064 unsigned ResFactor;
2065 unsigned ResCount;
2066 if (ZoneCritResIdx) {
2067 ResFactor = SchedModel->getResourceFactor(ZoneCritResIdx);
2068 ResCount = getResourceCount(ZoneCritResIdx);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002069 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002070 else {
2071 ResFactor = SchedModel->getMicroOpFactor();
2072 ResCount = RetiredMOps * SchedModel->getMicroOpFactor();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002073 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002074 unsigned LFactor = SchedModel->getLatencyFactor();
2075 dbgs() << Available.getName() << " @" << CurrCycle << "c\n"
2076 << " Retired: " << RetiredMOps;
2077 dbgs() << "\n Executed: " << getExecutedCount() / LFactor << "c";
2078 dbgs() << "\n Critical: " << ResCount / LFactor << "c, "
Andrew Trickfc127d12013-12-07 05:59:44 +00002079 << ResCount / ResFactor << " "
2080 << SchedModel->getResourceName(ZoneCritResIdx)
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002081 << "\n ExpectedLatency: " << ExpectedLatency << "c\n"
2082 << (IsResourceLimited ? " - Resource" : " - Latency")
2083 << " limited.\n";
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002084}
Andrew Trick8e8415f2013-06-15 05:46:47 +00002085#endif
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002086
Andrew Trickfc127d12013-12-07 05:59:44 +00002087//===----------------------------------------------------------------------===//
Andrew Trickd14d7c22013-12-28 21:56:57 +00002088// GenericScheduler - Generic implementation of MachineSchedStrategy.
Andrew Trickfc127d12013-12-07 05:59:44 +00002089//===----------------------------------------------------------------------===//
2090
2091namespace {
Andrew Trickd14d7c22013-12-28 21:56:57 +00002092/// Base class for GenericScheduler. This class maintains information about
2093/// scheduling candidates based on TargetSchedModel making it easy to implement
2094/// heuristics for either preRA or postRA scheduling.
2095class GenericSchedulerBase : public MachineSchedStrategy {
Andrew Trickfc127d12013-12-07 05:59:44 +00002096public:
2097 /// Represent the type of SchedCandidate found within a single queue.
2098 /// pickNodeBidirectional depends on these listed by decreasing priority.
2099 enum CandReason {
2100 NoCand, PhysRegCopy, RegExcess, RegCritical, Stall, Cluster, Weak, RegMax,
2101 ResourceReduce, ResourceDemand, BotHeightReduce, BotPathReduce,
2102 TopDepthReduce, TopPathReduce, NextDefUse, NodeOrder};
2103
2104#ifndef NDEBUG
Andrew Trickd14d7c22013-12-28 21:56:57 +00002105 static const char *getReasonStr(GenericSchedulerBase::CandReason Reason);
Andrew Trickfc127d12013-12-07 05:59:44 +00002106#endif
2107
2108 /// Policy for scheduling the next instruction in the candidate's zone.
2109 struct CandPolicy {
2110 bool ReduceLatency;
2111 unsigned ReduceResIdx;
2112 unsigned DemandResIdx;
2113
2114 CandPolicy(): ReduceLatency(false), ReduceResIdx(0), DemandResIdx(0) {}
2115 };
2116
2117 /// Status of an instruction's critical resource consumption.
2118 struct SchedResourceDelta {
2119 // Count critical resources in the scheduled region required by SU.
2120 unsigned CritResources;
2121
2122 // Count critical resources from another region consumed by SU.
2123 unsigned DemandedResources;
2124
2125 SchedResourceDelta(): CritResources(0), DemandedResources(0) {}
2126
2127 bool operator==(const SchedResourceDelta &RHS) const {
2128 return CritResources == RHS.CritResources
2129 && DemandedResources == RHS.DemandedResources;
2130 }
2131 bool operator!=(const SchedResourceDelta &RHS) const {
2132 return !operator==(RHS);
2133 }
2134 };
2135
2136 /// Store the state used by GenericScheduler heuristics, required for the
2137 /// lifetime of one invocation of pickNode().
2138 struct SchedCandidate {
2139 CandPolicy Policy;
2140
2141 // The best SUnit candidate.
2142 SUnit *SU;
2143
2144 // The reason for this candidate.
2145 CandReason Reason;
2146
2147 // Set of reasons that apply to multiple candidates.
2148 uint32_t RepeatReasonSet;
2149
2150 // Register pressure values for the best candidate.
2151 RegPressureDelta RPDelta;
2152
2153 // Critical resource consumption of the best candidate.
2154 SchedResourceDelta ResDelta;
2155
2156 SchedCandidate(const CandPolicy &policy)
2157 : Policy(policy), SU(NULL), Reason(NoCand), RepeatReasonSet(0) {}
2158
2159 bool isValid() const { return SU; }
2160
2161 // Copy the status of another candidate without changing policy.
2162 void setBest(SchedCandidate &Best) {
2163 assert(Best.Reason != NoCand && "uninitialized Sched candidate");
2164 SU = Best.SU;
2165 Reason = Best.Reason;
2166 RPDelta = Best.RPDelta;
2167 ResDelta = Best.ResDelta;
2168 }
2169
2170 bool isRepeat(CandReason R) { return RepeatReasonSet & (1 << R); }
2171 void setRepeat(CandReason R) { RepeatReasonSet |= (1 << R); }
2172
Andrew Trickd14d7c22013-12-28 21:56:57 +00002173 void initResourceDelta(const ScheduleDAGMI *DAG,
Andrew Trickfc127d12013-12-07 05:59:44 +00002174 const TargetSchedModel *SchedModel);
2175 };
2176
Andrew Trickd14d7c22013-12-28 21:56:57 +00002177protected:
Andrew Trickfc127d12013-12-07 05:59:44 +00002178 const MachineSchedContext *Context;
Andrew Trickfc127d12013-12-07 05:59:44 +00002179 const TargetSchedModel *SchedModel;
2180 const TargetRegisterInfo *TRI;
2181
Andrew Trickfc127d12013-12-07 05:59:44 +00002182 SchedRemainder Rem;
Andrew Trickd14d7c22013-12-28 21:56:57 +00002183protected:
2184 GenericSchedulerBase(const MachineSchedContext *C):
2185 Context(C), SchedModel(0), TRI(0) {}
2186
2187 void setPolicy(CandPolicy &Policy, bool IsPostRA, SchedBoundary &CurrZone,
2188 SchedBoundary *OtherZone);
2189
2190#ifndef NDEBUG
2191 void traceCandidate(const SchedCandidate &Cand);
2192#endif
2193};
2194} // namespace
2195
2196void GenericSchedulerBase::SchedCandidate::
2197initResourceDelta(const ScheduleDAGMI *DAG,
2198 const TargetSchedModel *SchedModel) {
2199 if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
2200 return;
2201
2202 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
2203 for (TargetSchedModel::ProcResIter
2204 PI = SchedModel->getWriteProcResBegin(SC),
2205 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2206 if (PI->ProcResourceIdx == Policy.ReduceResIdx)
2207 ResDelta.CritResources += PI->Cycles;
2208 if (PI->ProcResourceIdx == Policy.DemandResIdx)
2209 ResDelta.DemandedResources += PI->Cycles;
2210 }
2211}
2212
2213/// Set the CandPolicy given a scheduling zone given the current resources and
2214/// latencies inside and outside the zone.
2215void GenericSchedulerBase::setPolicy(CandPolicy &Policy,
2216 bool IsPostRA,
2217 SchedBoundary &CurrZone,
2218 SchedBoundary *OtherZone) {
2219 // Apply preemptive heuristics based on the the total latency and resources
2220 // inside and outside this zone. Potential stalls should be considered before
2221 // following this policy.
2222
2223 // Compute remaining latency. We need this both to determine whether the
2224 // overall schedule has become latency-limited and whether the instructions
2225 // outside this zone are resource or latency limited.
2226 //
2227 // The "dependent" latency is updated incrementally during scheduling as the
2228 // max height/depth of scheduled nodes minus the cycles since it was
2229 // scheduled:
2230 // DLat = max (N.depth - (CurrCycle - N.ReadyCycle) for N in Zone
2231 //
2232 // The "independent" latency is the max ready queue depth:
2233 // ILat = max N.depth for N in Available|Pending
2234 //
2235 // RemainingLatency is the greater of independent and dependent latency.
2236 unsigned RemLatency = CurrZone.getDependentLatency();
2237 RemLatency = std::max(RemLatency,
2238 CurrZone.findMaxLatency(CurrZone.Available.elements()));
2239 RemLatency = std::max(RemLatency,
2240 CurrZone.findMaxLatency(CurrZone.Pending.elements()));
2241
2242 // Compute the critical resource outside the zone.
Andrew Trick7afe4812013-12-28 22:25:57 +00002243 unsigned OtherCritIdx = 0;
Andrew Trickd14d7c22013-12-28 21:56:57 +00002244 unsigned OtherCount =
2245 OtherZone ? OtherZone->getOtherResourceCount(OtherCritIdx) : 0;
2246
2247 bool OtherResLimited = false;
2248 if (SchedModel->hasInstrSchedModel()) {
2249 unsigned LFactor = SchedModel->getLatencyFactor();
2250 OtherResLimited = (int)(OtherCount - (RemLatency * LFactor)) > (int)LFactor;
2251 }
2252 // Schedule aggressively for latency in PostRA mode. We don't check for
2253 // acyclic latency during PostRA, and highly out-of-order processors will
2254 // skip PostRA scheduling.
2255 if (!OtherResLimited) {
2256 if (IsPostRA || (RemLatency + CurrZone.getCurrCycle() > Rem.CriticalPath)) {
2257 Policy.ReduceLatency |= true;
2258 DEBUG(dbgs() << " " << CurrZone.Available.getName()
2259 << " RemainingLatency " << RemLatency << " + "
2260 << CurrZone.getCurrCycle() << "c > CritPath "
2261 << Rem.CriticalPath << "\n");
2262 }
2263 }
2264 // If the same resource is limiting inside and outside the zone, do nothing.
2265 if (CurrZone.getZoneCritResIdx() == OtherCritIdx)
2266 return;
2267
2268 DEBUG(
2269 if (CurrZone.isResourceLimited()) {
2270 dbgs() << " " << CurrZone.Available.getName() << " ResourceLimited: "
2271 << SchedModel->getResourceName(CurrZone.getZoneCritResIdx())
2272 << "\n";
2273 }
2274 if (OtherResLimited)
2275 dbgs() << " RemainingLimit: "
2276 << SchedModel->getResourceName(OtherCritIdx) << "\n";
2277 if (!CurrZone.isResourceLimited() && !OtherResLimited)
2278 dbgs() << " Latency limited both directions.\n");
2279
2280 if (CurrZone.isResourceLimited() && !Policy.ReduceResIdx)
2281 Policy.ReduceResIdx = CurrZone.getZoneCritResIdx();
2282
2283 if (OtherResLimited)
2284 Policy.DemandResIdx = OtherCritIdx;
2285}
2286
2287#ifndef NDEBUG
2288const char *GenericSchedulerBase::getReasonStr(
2289 GenericSchedulerBase::CandReason Reason) {
2290 switch (Reason) {
2291 case NoCand: return "NOCAND ";
2292 case PhysRegCopy: return "PREG-COPY";
2293 case RegExcess: return "REG-EXCESS";
2294 case RegCritical: return "REG-CRIT ";
2295 case Stall: return "STALL ";
2296 case Cluster: return "CLUSTER ";
2297 case Weak: return "WEAK ";
2298 case RegMax: return "REG-MAX ";
2299 case ResourceReduce: return "RES-REDUCE";
2300 case ResourceDemand: return "RES-DEMAND";
2301 case TopDepthReduce: return "TOP-DEPTH ";
2302 case TopPathReduce: return "TOP-PATH ";
2303 case BotHeightReduce:return "BOT-HEIGHT";
2304 case BotPathReduce: return "BOT-PATH ";
2305 case NextDefUse: return "DEF-USE ";
2306 case NodeOrder: return "ORDER ";
2307 };
2308 llvm_unreachable("Unknown reason!");
2309}
2310
2311void GenericSchedulerBase::traceCandidate(const SchedCandidate &Cand) {
2312 PressureChange P;
2313 unsigned ResIdx = 0;
2314 unsigned Latency = 0;
2315 switch (Cand.Reason) {
2316 default:
2317 break;
2318 case RegExcess:
2319 P = Cand.RPDelta.Excess;
2320 break;
2321 case RegCritical:
2322 P = Cand.RPDelta.CriticalMax;
2323 break;
2324 case RegMax:
2325 P = Cand.RPDelta.CurrentMax;
2326 break;
2327 case ResourceReduce:
2328 ResIdx = Cand.Policy.ReduceResIdx;
2329 break;
2330 case ResourceDemand:
2331 ResIdx = Cand.Policy.DemandResIdx;
2332 break;
2333 case TopDepthReduce:
2334 Latency = Cand.SU->getDepth();
2335 break;
2336 case TopPathReduce:
2337 Latency = Cand.SU->getHeight();
2338 break;
2339 case BotHeightReduce:
2340 Latency = Cand.SU->getHeight();
2341 break;
2342 case BotPathReduce:
2343 Latency = Cand.SU->getDepth();
2344 break;
2345 }
2346 dbgs() << " SU(" << Cand.SU->NodeNum << ") " << getReasonStr(Cand.Reason);
2347 if (P.isValid())
2348 dbgs() << " " << TRI->getRegPressureSetName(P.getPSet())
2349 << ":" << P.getUnitInc() << " ";
2350 else
2351 dbgs() << " ";
2352 if (ResIdx)
2353 dbgs() << " " << SchedModel->getProcResource(ResIdx)->Name << " ";
2354 else
2355 dbgs() << " ";
2356 if (Latency)
2357 dbgs() << " " << Latency << " cycles ";
2358 else
2359 dbgs() << " ";
2360 dbgs() << '\n';
2361}
2362#endif
2363
2364/// Return true if this heuristic determines order.
2365static bool tryLess(int TryVal, int CandVal,
2366 GenericSchedulerBase::SchedCandidate &TryCand,
2367 GenericSchedulerBase::SchedCandidate &Cand,
2368 GenericSchedulerBase::CandReason Reason) {
2369 if (TryVal < CandVal) {
2370 TryCand.Reason = Reason;
2371 return true;
2372 }
2373 if (TryVal > CandVal) {
2374 if (Cand.Reason > Reason)
2375 Cand.Reason = Reason;
2376 return true;
2377 }
2378 Cand.setRepeat(Reason);
2379 return false;
2380}
2381
2382static bool tryGreater(int TryVal, int CandVal,
2383 GenericSchedulerBase::SchedCandidate &TryCand,
2384 GenericSchedulerBase::SchedCandidate &Cand,
2385 GenericSchedulerBase::CandReason Reason) {
2386 if (TryVal > CandVal) {
2387 TryCand.Reason = Reason;
2388 return true;
2389 }
2390 if (TryVal < CandVal) {
2391 if (Cand.Reason > Reason)
2392 Cand.Reason = Reason;
2393 return true;
2394 }
2395 Cand.setRepeat(Reason);
2396 return false;
2397}
2398
2399static bool tryLatency(GenericSchedulerBase::SchedCandidate &TryCand,
2400 GenericSchedulerBase::SchedCandidate &Cand,
2401 SchedBoundary &Zone) {
2402 if (Zone.isTop()) {
2403 if (Cand.SU->getDepth() > Zone.getScheduledLatency()) {
2404 if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2405 TryCand, Cand, GenericSchedulerBase::TopDepthReduce))
2406 return true;
2407 }
2408 if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2409 TryCand, Cand, GenericSchedulerBase::TopPathReduce))
2410 return true;
2411 }
2412 else {
2413 if (Cand.SU->getHeight() > Zone.getScheduledLatency()) {
2414 if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2415 TryCand, Cand, GenericSchedulerBase::BotHeightReduce))
2416 return true;
2417 }
2418 if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2419 TryCand, Cand, GenericSchedulerBase::BotPathReduce))
2420 return true;
2421 }
2422 return false;
2423}
2424
2425static void tracePick(const GenericSchedulerBase::SchedCandidate &Cand,
2426 bool IsTop) {
2427 DEBUG(dbgs() << "Pick " << (IsTop ? "Top " : "Bot ")
2428 << GenericSchedulerBase::getReasonStr(Cand.Reason) << '\n');
2429}
2430
2431namespace {
2432/// GenericScheduler shrinks the unscheduled zone using heuristics to balance
2433/// the schedule.
2434class GenericScheduler : public GenericSchedulerBase {
2435 ScheduleDAGMILive *DAG;
2436
2437 // State of the top and bottom scheduled instruction boundaries.
Andrew Trickfc127d12013-12-07 05:59:44 +00002438 SchedBoundary Top;
2439 SchedBoundary Bot;
2440
2441 MachineSchedPolicy RegionPolicy;
2442public:
2443 GenericScheduler(const MachineSchedContext *C):
Andrew Trickd14d7c22013-12-28 21:56:57 +00002444 GenericSchedulerBase(C), DAG(0), Top(SchedBoundary::TopQID, "TopQ"),
2445 Bot(SchedBoundary::BotQID, "BotQ") {}
Andrew Trickfc127d12013-12-07 05:59:44 +00002446
Craig Topper24e685f2014-03-10 05:29:18 +00002447 void initPolicy(MachineBasicBlock::iterator Begin,
2448 MachineBasicBlock::iterator End,
2449 unsigned NumRegionInstrs) override;
Andrew Trickfc127d12013-12-07 05:59:44 +00002450
Craig Topper24e685f2014-03-10 05:29:18 +00002451 bool shouldTrackPressure() const override {
Andrew Trickd14d7c22013-12-28 21:56:57 +00002452 return RegionPolicy.ShouldTrackPressure;
2453 }
Andrew Trickfc127d12013-12-07 05:59:44 +00002454
Craig Topper24e685f2014-03-10 05:29:18 +00002455 void initialize(ScheduleDAGMI *dag) override;
Andrew Trickfc127d12013-12-07 05:59:44 +00002456
Craig Topper24e685f2014-03-10 05:29:18 +00002457 SUnit *pickNode(bool &IsTopNode) override;
Andrew Trickfc127d12013-12-07 05:59:44 +00002458
Craig Topper24e685f2014-03-10 05:29:18 +00002459 void schedNode(SUnit *SU, bool IsTopNode) override;
Andrew Trickfc127d12013-12-07 05:59:44 +00002460
Craig Topper24e685f2014-03-10 05:29:18 +00002461 void releaseTopNode(SUnit *SU) override {
Andrew Trickd14d7c22013-12-28 21:56:57 +00002462 Top.releaseTopNode(SU);
2463 }
Andrew Trickfc127d12013-12-07 05:59:44 +00002464
Craig Topper24e685f2014-03-10 05:29:18 +00002465 void releaseBottomNode(SUnit *SU) override {
Andrew Trickd14d7c22013-12-28 21:56:57 +00002466 Bot.releaseBottomNode(SU);
2467 }
Andrew Trickfc127d12013-12-07 05:59:44 +00002468
Craig Topper24e685f2014-03-10 05:29:18 +00002469 void registerRoots() override;
Andrew Trickfc127d12013-12-07 05:59:44 +00002470
2471protected:
2472 void checkAcyclicLatency();
2473
Andrew Trickfc127d12013-12-07 05:59:44 +00002474 void tryCandidate(SchedCandidate &Cand,
2475 SchedCandidate &TryCand,
2476 SchedBoundary &Zone,
2477 const RegPressureTracker &RPTracker,
2478 RegPressureTracker &TempTracker);
2479
2480 SUnit *pickNodeBidirectional(bool &IsTopNode);
2481
2482 void pickNodeFromQueue(SchedBoundary &Zone,
2483 const RegPressureTracker &RPTracker,
2484 SchedCandidate &Candidate);
2485
2486 void reschedulePhysRegCopies(SUnit *SU, bool isTop);
Andrew Trickfc127d12013-12-07 05:59:44 +00002487};
2488} // namespace
2489
2490void GenericScheduler::initialize(ScheduleDAGMI *dag) {
Andrew Trickd7f890e2013-12-28 21:56:47 +00002491 assert(dag->hasVRegLiveness() &&
2492 "(PreRA)GenericScheduler needs vreg liveness");
2493 DAG = static_cast<ScheduleDAGMILive*>(dag);
Andrew Trickfc127d12013-12-07 05:59:44 +00002494 SchedModel = DAG->getSchedModel();
2495 TRI = DAG->TRI;
2496
2497 Rem.init(DAG, SchedModel);
2498 Top.init(DAG, SchedModel, &Rem);
2499 Bot.init(DAG, SchedModel, &Rem);
2500
2501 // Initialize resource counts.
2502
2503 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
2504 // are disabled, then these HazardRecs will be disabled.
2505 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
2506 const TargetMachine &TM = DAG->MF.getTarget();
2507 if (!Top.HazardRec) {
2508 Top.HazardRec =
2509 TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
2510 }
2511 if (!Bot.HazardRec) {
2512 Bot.HazardRec =
2513 TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
2514 }
2515}
2516
2517/// Initialize the per-region scheduling policy.
2518void GenericScheduler::initPolicy(MachineBasicBlock::iterator Begin,
2519 MachineBasicBlock::iterator End,
2520 unsigned NumRegionInstrs) {
2521 const TargetMachine &TM = Context->MF->getTarget();
Andrew Trick46753512014-01-22 03:38:55 +00002522 const TargetLowering *TLI = TM.getTargetLowering();
Andrew Trickfc127d12013-12-07 05:59:44 +00002523
2524 // Avoid setting up the register pressure tracker for small regions to save
2525 // compile time. As a rough heuristic, only track pressure when the number of
2526 // schedulable instructions exceeds half the integer register file.
Andrew Trick350ff2c2014-01-21 21:27:37 +00002527 RegionPolicy.ShouldTrackPressure = true;
Andrew Trick46753512014-01-22 03:38:55 +00002528 for (unsigned VT = MVT::i32; VT > (unsigned)MVT::i1; --VT) {
2529 MVT::SimpleValueType LegalIntVT = (MVT::SimpleValueType)VT;
2530 if (TLI->isTypeLegal(LegalIntVT)) {
Andrew Trick350ff2c2014-01-21 21:27:37 +00002531 unsigned NIntRegs = Context->RegClassInfo->getNumAllocatableRegs(
Andrew Trick46753512014-01-22 03:38:55 +00002532 TLI->getRegClassFor(LegalIntVT));
Andrew Trick350ff2c2014-01-21 21:27:37 +00002533 RegionPolicy.ShouldTrackPressure = NumRegionInstrs > (NIntRegs / 2);
2534 }
2535 }
Andrew Trickfc127d12013-12-07 05:59:44 +00002536
2537 // For generic targets, we default to bottom-up, because it's simpler and more
2538 // compile-time optimizations have been implemented in that direction.
2539 RegionPolicy.OnlyBottomUp = true;
2540
2541 // Allow the subtarget to override default policy.
2542 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
2543 ST.overrideSchedPolicy(RegionPolicy, Begin, End, NumRegionInstrs);
2544
2545 // After subtarget overrides, apply command line options.
2546 if (!EnableRegPressure)
2547 RegionPolicy.ShouldTrackPressure = false;
2548
2549 // Check -misched-topdown/bottomup can force or unforce scheduling direction.
2550 // e.g. -misched-bottomup=false allows scheduling in both directions.
2551 assert((!ForceTopDown || !ForceBottomUp) &&
2552 "-misched-topdown incompatible with -misched-bottomup");
2553 if (ForceBottomUp.getNumOccurrences() > 0) {
2554 RegionPolicy.OnlyBottomUp = ForceBottomUp;
2555 if (RegionPolicy.OnlyBottomUp)
2556 RegionPolicy.OnlyTopDown = false;
2557 }
2558 if (ForceTopDown.getNumOccurrences() > 0) {
2559 RegionPolicy.OnlyTopDown = ForceTopDown;
2560 if (RegionPolicy.OnlyTopDown)
2561 RegionPolicy.OnlyBottomUp = false;
2562 }
2563}
2564
2565/// Set IsAcyclicLatencyLimited if the acyclic path is longer than the cyclic
2566/// critical path by more cycles than it takes to drain the instruction buffer.
2567/// We estimate an upper bounds on in-flight instructions as:
2568///
2569/// CyclesPerIteration = max( CyclicPath, Loop-Resource-Height )
2570/// InFlightIterations = AcyclicPath / CyclesPerIteration
2571/// InFlightResources = InFlightIterations * LoopResources
2572///
2573/// TODO: Check execution resources in addition to IssueCount.
2574void GenericScheduler::checkAcyclicLatency() {
2575 if (Rem.CyclicCritPath == 0 || Rem.CyclicCritPath >= Rem.CriticalPath)
2576 return;
2577
2578 // Scaled number of cycles per loop iteration.
2579 unsigned IterCount =
2580 std::max(Rem.CyclicCritPath * SchedModel->getLatencyFactor(),
2581 Rem.RemIssueCount);
2582 // Scaled acyclic critical path.
2583 unsigned AcyclicCount = Rem.CriticalPath * SchedModel->getLatencyFactor();
2584 // InFlightCount = (AcyclicPath / IterCycles) * InstrPerLoop
2585 unsigned InFlightCount =
2586 (AcyclicCount * Rem.RemIssueCount + IterCount-1) / IterCount;
2587 unsigned BufferLimit =
2588 SchedModel->getMicroOpBufferSize() * SchedModel->getMicroOpFactor();
2589
2590 Rem.IsAcyclicLatencyLimited = InFlightCount > BufferLimit;
2591
2592 DEBUG(dbgs() << "IssueCycles="
2593 << Rem.RemIssueCount / SchedModel->getLatencyFactor() << "c "
2594 << "IterCycles=" << IterCount / SchedModel->getLatencyFactor()
2595 << "c NumIters=" << (AcyclicCount + IterCount-1) / IterCount
2596 << " InFlight=" << InFlightCount / SchedModel->getMicroOpFactor()
2597 << "m BufferLim=" << SchedModel->getMicroOpBufferSize() << "m\n";
2598 if (Rem.IsAcyclicLatencyLimited)
2599 dbgs() << " ACYCLIC LATENCY LIMIT\n");
2600}
2601
2602void GenericScheduler::registerRoots() {
2603 Rem.CriticalPath = DAG->ExitSU.getDepth();
2604
2605 // Some roots may not feed into ExitSU. Check all of them in case.
2606 for (std::vector<SUnit*>::const_iterator
2607 I = Bot.Available.begin(), E = Bot.Available.end(); I != E; ++I) {
2608 if ((*I)->getDepth() > Rem.CriticalPath)
2609 Rem.CriticalPath = (*I)->getDepth();
2610 }
2611 DEBUG(dbgs() << "Critical Path: " << Rem.CriticalPath << '\n');
2612
2613 if (EnableCyclicPath) {
2614 Rem.CyclicCritPath = DAG->computeCyclicCriticalPath();
2615 checkAcyclicLatency();
2616 }
2617}
2618
Andrew Trick1a831342013-08-30 03:49:48 +00002619static bool tryPressure(const PressureChange &TryP,
2620 const PressureChange &CandP,
Andrew Trickd14d7c22013-12-28 21:56:57 +00002621 GenericSchedulerBase::SchedCandidate &TryCand,
2622 GenericSchedulerBase::SchedCandidate &Cand,
2623 GenericSchedulerBase::CandReason Reason) {
Andrew Trickb1a45b62013-08-30 04:27:29 +00002624 int TryRank = TryP.getPSetOrMax();
2625 int CandRank = CandP.getPSetOrMax();
2626 // If both candidates affect the same set, go with the smallest increase.
2627 if (TryRank == CandRank) {
2628 return tryLess(TryP.getUnitInc(), CandP.getUnitInc(), TryCand, Cand,
2629 Reason);
Andrew Trick401b6952013-07-25 07:26:35 +00002630 }
Andrew Trickb1a45b62013-08-30 04:27:29 +00002631 // If one candidate decreases and the other increases, go with it.
2632 // Invalid candidates have UnitInc==0.
2633 if (tryLess(TryP.getUnitInc() < 0, CandP.getUnitInc() < 0, TryCand, Cand,
2634 Reason)) {
2635 return true;
2636 }
Andrew Trick401b6952013-07-25 07:26:35 +00002637 // If the candidates are decreasing pressure, reverse priority.
Andrew Trick1a831342013-08-30 03:49:48 +00002638 if (TryP.getUnitInc() < 0)
Andrew Trick401b6952013-07-25 07:26:35 +00002639 std::swap(TryRank, CandRank);
2640 return tryGreater(TryRank, CandRank, TryCand, Cand, Reason);
2641}
2642
Andrew Tricka7714a02012-11-12 19:40:10 +00002643static unsigned getWeakLeft(const SUnit *SU, bool isTop) {
2644 return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
2645}
2646
Andrew Tricke833e1c2013-04-13 06:07:40 +00002647/// Minimize physical register live ranges. Regalloc wants them adjacent to
2648/// their physreg def/use.
2649///
2650/// FIXME: This is an unnecessary check on the critical path. Most are root/leaf
2651/// copies which can be prescheduled. The rest (e.g. x86 MUL) could be bundled
2652/// with the operation that produces or consumes the physreg. We'll do this when
2653/// regalloc has support for parallel copies.
2654static int biasPhysRegCopy(const SUnit *SU, bool isTop) {
2655 const MachineInstr *MI = SU->getInstr();
2656 if (!MI->isCopy())
2657 return 0;
2658
2659 unsigned ScheduledOper = isTop ? 1 : 0;
2660 unsigned UnscheduledOper = isTop ? 0 : 1;
2661 // If we have already scheduled the physreg produce/consumer, immediately
2662 // schedule the copy.
2663 if (TargetRegisterInfo::isPhysicalRegister(
2664 MI->getOperand(ScheduledOper).getReg()))
2665 return 1;
2666 // If the physreg is at the boundary, defer it. Otherwise schedule it
2667 // immediately to free the dependent. We can hoist the copy later.
2668 bool AtBoundary = isTop ? !SU->NumSuccsLeft : !SU->NumPredsLeft;
2669 if (TargetRegisterInfo::isPhysicalRegister(
2670 MI->getOperand(UnscheduledOper).getReg()))
2671 return AtBoundary ? -1 : 1;
2672 return 0;
2673}
2674
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002675/// Apply a set of heursitics to a new candidate. Heuristics are currently
2676/// hierarchical. This may be more efficient than a graduated cost model because
2677/// we don't need to evaluate all aspects of the model for each node in the
2678/// queue. But it's really done to make the heuristics easier to debug and
2679/// statistically analyze.
2680///
2681/// \param Cand provides the policy and current best candidate.
2682/// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
2683/// \param Zone describes the scheduled zone that we are extending.
2684/// \param RPTracker describes reg pressure within the scheduled zone.
2685/// \param TempTracker is a scratch pressure tracker to reuse in queries.
Andrew Trick665d3ec2013-09-19 23:10:59 +00002686void GenericScheduler::tryCandidate(SchedCandidate &Cand,
Andrew Trickbb1247b2013-12-05 17:55:47 +00002687 SchedCandidate &TryCand,
2688 SchedBoundary &Zone,
2689 const RegPressureTracker &RPTracker,
2690 RegPressureTracker &TempTracker) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002691
Andrew Trick66c3dfb2013-09-04 21:00:11 +00002692 if (DAG->isTrackingPressure()) {
Andrew Trick310190e2013-09-04 21:00:02 +00002693 // Always initialize TryCand's RPDelta.
2694 if (Zone.isTop()) {
2695 TempTracker.getMaxDownwardPressureDelta(
Andrew Trick1a831342013-08-30 03:49:48 +00002696 TryCand.SU->getInstr(),
Andrew Trick1a831342013-08-30 03:49:48 +00002697 TryCand.RPDelta,
2698 DAG->getRegionCriticalPSets(),
2699 DAG->getRegPressure().MaxSetPressure);
2700 }
2701 else {
Andrew Trick310190e2013-09-04 21:00:02 +00002702 if (VerifyScheduling) {
2703 TempTracker.getMaxUpwardPressureDelta(
2704 TryCand.SU->getInstr(),
2705 &DAG->getPressureDiff(TryCand.SU),
2706 TryCand.RPDelta,
2707 DAG->getRegionCriticalPSets(),
2708 DAG->getRegPressure().MaxSetPressure);
2709 }
2710 else {
2711 RPTracker.getUpwardPressureDelta(
2712 TryCand.SU->getInstr(),
2713 DAG->getPressureDiff(TryCand.SU),
2714 TryCand.RPDelta,
2715 DAG->getRegionCriticalPSets(),
2716 DAG->getRegPressure().MaxSetPressure);
2717 }
Andrew Trick1a831342013-08-30 03:49:48 +00002718 }
2719 }
Andrew Trickc573cd92013-09-06 17:32:44 +00002720 DEBUG(if (TryCand.RPDelta.Excess.isValid())
2721 dbgs() << " SU(" << TryCand.SU->NodeNum << ") "
2722 << TRI->getRegPressureSetName(TryCand.RPDelta.Excess.getPSet())
2723 << ":" << TryCand.RPDelta.Excess.getUnitInc() << "\n");
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002724
2725 // Initialize the candidate if needed.
2726 if (!Cand.isValid()) {
2727 TryCand.Reason = NodeOrder;
2728 return;
2729 }
Andrew Tricke833e1c2013-04-13 06:07:40 +00002730
2731 if (tryGreater(biasPhysRegCopy(TryCand.SU, Zone.isTop()),
2732 biasPhysRegCopy(Cand.SU, Zone.isTop()),
2733 TryCand, Cand, PhysRegCopy))
2734 return;
2735
Andrew Trick401b6952013-07-25 07:26:35 +00002736 // Avoid exceeding the target's limit. If signed PSetID is negative, it is
2737 // invalid; convert it to INT_MAX to give it lowest priority.
Andrew Trick66c3dfb2013-09-04 21:00:11 +00002738 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.Excess,
2739 Cand.RPDelta.Excess,
2740 TryCand, Cand, RegExcess))
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002741 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002742
2743 // Avoid increasing the max critical pressure in the scheduled region.
Andrew Trick66c3dfb2013-09-04 21:00:11 +00002744 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CriticalMax,
2745 Cand.RPDelta.CriticalMax,
2746 TryCand, Cand, RegCritical))
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002747 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002748
Andrew Trickddffae92013-09-06 17:32:36 +00002749 // For loops that are acyclic path limited, aggressively schedule for latency.
Andrew Tricke1f7bf22013-09-09 22:28:08 +00002750 // This can result in very long dependence chains scheduled in sequence, so
2751 // once every cycle (when CurrMOps == 0), switch to normal heuristics.
Andrew Trickfc127d12013-12-07 05:59:44 +00002752 if (Rem.IsAcyclicLatencyLimited && !Zone.getCurrMOps()
Andrew Tricke1f7bf22013-09-09 22:28:08 +00002753 && tryLatency(TryCand, Cand, Zone))
Andrew Trickddffae92013-09-06 17:32:36 +00002754 return;
2755
Andrew Trick880e5732013-12-05 17:55:58 +00002756 // Prioritize instructions that read unbuffered resources by stall cycles.
2757 if (tryLess(Zone.getLatencyStallCycles(TryCand.SU),
2758 Zone.getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
2759 return;
2760
Andrew Tricka7714a02012-11-12 19:40:10 +00002761 // Keep clustered nodes together to encourage downstream peephole
2762 // optimizations which may reduce resource requirements.
2763 //
2764 // This is a best effort to set things up for a post-RA pass. Optimizations
2765 // like generating loads of multiple registers should ideally be done within
2766 // the scheduler pass by combining the loads during DAG postprocessing.
2767 const SUnit *NextClusterSU =
2768 Zone.isTop() ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
2769 if (tryGreater(TryCand.SU == NextClusterSU, Cand.SU == NextClusterSU,
2770 TryCand, Cand, Cluster))
2771 return;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00002772
2773 // Weak edges are for clustering and other constraints.
Andrew Tricka7714a02012-11-12 19:40:10 +00002774 if (tryLess(getWeakLeft(TryCand.SU, Zone.isTop()),
2775 getWeakLeft(Cand.SU, Zone.isTop()),
Andrew Trick85a1d4c2013-04-24 15:54:43 +00002776 TryCand, Cand, Weak)) {
Andrew Tricka7714a02012-11-12 19:40:10 +00002777 return;
2778 }
Andrew Trick71f08a32013-06-17 21:45:13 +00002779 // Avoid increasing the max pressure of the entire region.
Andrew Trick66c3dfb2013-09-04 21:00:11 +00002780 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CurrentMax,
2781 Cand.RPDelta.CurrentMax,
2782 TryCand, Cand, RegMax))
Andrew Trick71f08a32013-06-17 21:45:13 +00002783 return;
2784
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002785 // Avoid critical resource consumption and balance the schedule.
2786 TryCand.initResourceDelta(DAG, SchedModel);
2787 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
2788 TryCand, Cand, ResourceReduce))
2789 return;
2790 if (tryGreater(TryCand.ResDelta.DemandedResources,
2791 Cand.ResDelta.DemandedResources,
2792 TryCand, Cand, ResourceDemand))
2793 return;
2794
2795 // Avoid serializing long latency dependence chains.
Andrew Trickc01b0042013-08-23 17:48:43 +00002796 // For acyclic path limited loops, latency was already checked above.
2797 if (Cand.Policy.ReduceLatency && !Rem.IsAcyclicLatencyLimited
2798 && tryLatency(TryCand, Cand, Zone)) {
2799 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002800 }
2801
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002802 // Prefer immediate defs/users of the last scheduled instruction. This is a
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002803 // local pressure avoidance strategy that also makes the machine code
2804 // readable.
Andrew Trickfc127d12013-12-07 05:59:44 +00002805 if (tryGreater(Zone.isNextSU(TryCand.SU), Zone.isNextSU(Cand.SU),
Andrew Tricka7714a02012-11-12 19:40:10 +00002806 TryCand, Cand, NextDefUse))
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002807 return;
Andrew Tricka7714a02012-11-12 19:40:10 +00002808
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002809 // Fall through to original instruction order.
2810 if ((Zone.isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
2811 || (!Zone.isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
2812 TryCand.Reason = NodeOrder;
2813 }
2814}
Andrew Trick419eae22012-05-10 21:06:19 +00002815
Andrew Trickc573cd92013-09-06 17:32:44 +00002816/// Pick the best candidate from the queue.
Andrew Trick7ee9de52012-05-10 21:06:16 +00002817///
2818/// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
2819/// DAG building. To adjust for the current scheduling location we need to
2820/// maintain the number of vreg uses remaining to be top-scheduled.
Andrew Trick665d3ec2013-09-19 23:10:59 +00002821void GenericScheduler::pickNodeFromQueue(SchedBoundary &Zone,
Andrew Trickbb1247b2013-12-05 17:55:47 +00002822 const RegPressureTracker &RPTracker,
2823 SchedCandidate &Cand) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002824 ReadyQueue &Q = Zone.Available;
2825
Andrew Tricka8ad5f72012-05-24 22:11:12 +00002826 DEBUG(Q.dump());
Andrew Trick22025772012-05-17 18:35:10 +00002827
Andrew Trick7ee9de52012-05-10 21:06:16 +00002828 // getMaxPressureDelta temporarily modifies the tracker.
2829 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
2830
Andrew Trickdd375dd2012-05-24 22:11:03 +00002831 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
Andrew Trick7ee9de52012-05-10 21:06:16 +00002832
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002833 SchedCandidate TryCand(Cand.Policy);
2834 TryCand.SU = *I;
2835 tryCandidate(Cand, TryCand, Zone, RPTracker, TempTracker);
2836 if (TryCand.Reason != NoCand) {
2837 // Initialize resource delta if needed in case future heuristics query it.
2838 if (TryCand.ResDelta == SchedResourceDelta())
2839 TryCand.initResourceDelta(DAG, SchedModel);
2840 Cand.setBest(TryCand);
Andrew Trick419d4912013-04-05 00:31:29 +00002841 DEBUG(traceCandidate(Cand));
Andrew Trick22025772012-05-17 18:35:10 +00002842 }
Andrew Trick7ee9de52012-05-10 21:06:16 +00002843 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002844}
2845
Andrew Trick22025772012-05-17 18:35:10 +00002846/// Pick the best candidate node from either the top or bottom queue.
Andrew Trick665d3ec2013-09-19 23:10:59 +00002847SUnit *GenericScheduler::pickNodeBidirectional(bool &IsTopNode) {
Andrew Trick22025772012-05-17 18:35:10 +00002848 // Schedule as far as possible in the direction of no choice. This is most
2849 // efficient, but also provides the best heuristics for CriticalPSets.
Andrew Trick61f1a272012-05-24 22:11:09 +00002850 if (SUnit *SU = Bot.pickOnlyChoice()) {
Andrew Trick22025772012-05-17 18:35:10 +00002851 IsTopNode = false;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002852 DEBUG(dbgs() << "Pick Bot NOCAND\n");
Andrew Trick61f1a272012-05-24 22:11:09 +00002853 return SU;
Andrew Trick22025772012-05-17 18:35:10 +00002854 }
Andrew Trick61f1a272012-05-24 22:11:09 +00002855 if (SUnit *SU = Top.pickOnlyChoice()) {
Andrew Trick22025772012-05-17 18:35:10 +00002856 IsTopNode = true;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002857 DEBUG(dbgs() << "Pick Top NOCAND\n");
Andrew Trick61f1a272012-05-24 22:11:09 +00002858 return SU;
Andrew Trick22025772012-05-17 18:35:10 +00002859 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002860 CandPolicy NoPolicy;
2861 SchedCandidate BotCand(NoPolicy);
2862 SchedCandidate TopCand(NoPolicy);
Andrew Trickfc127d12013-12-07 05:59:44 +00002863 // Set the bottom-up policy based on the state of the current bottom zone and
2864 // the instructions outside the zone, including the top zone.
Andrew Trickd14d7c22013-12-28 21:56:57 +00002865 setPolicy(BotCand.Policy, /*IsPostRA=*/false, Bot, &Top);
Andrew Trickfc127d12013-12-07 05:59:44 +00002866 // Set the top-down policy based on the state of the current top zone and
2867 // the instructions outside the zone, including the bottom zone.
Andrew Trickd14d7c22013-12-28 21:56:57 +00002868 setPolicy(TopCand.Policy, /*IsPostRA=*/false, Top, &Bot);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002869
Andrew Trick22025772012-05-17 18:35:10 +00002870 // Prefer bottom scheduling when heuristics are silent.
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002871 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
2872 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick22025772012-05-17 18:35:10 +00002873
2874 // If either Q has a single candidate that provides the least increase in
2875 // Excess pressure, we can immediately schedule from that Q.
2876 //
2877 // RegionCriticalPSets summarizes the pressure within the scheduled region and
2878 // affects picking from either Q. If scheduling in one direction must
2879 // increase pressure for one of the excess PSets, then schedule in that
2880 // direction first to provide more freedom in the other direction.
Andrew Trickd40d0f22013-06-17 21:45:05 +00002881 if ((BotCand.Reason == RegExcess && !BotCand.isRepeat(RegExcess))
2882 || (BotCand.Reason == RegCritical
2883 && !BotCand.isRepeat(RegCritical)))
2884 {
Andrew Trick22025772012-05-17 18:35:10 +00002885 IsTopNode = false;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002886 tracePick(BotCand, IsTopNode);
Andrew Trick61f1a272012-05-24 22:11:09 +00002887 return BotCand.SU;
Andrew Trick22025772012-05-17 18:35:10 +00002888 }
2889 // Check if the top Q has a better candidate.
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002890 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
2891 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick22025772012-05-17 18:35:10 +00002892
Andrew Trickd40d0f22013-06-17 21:45:05 +00002893 // Choose the queue with the most important (lowest enum) reason.
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002894 if (TopCand.Reason < BotCand.Reason) {
2895 IsTopNode = true;
2896 tracePick(TopCand, IsTopNode);
2897 return TopCand.SU;
2898 }
Andrew Trickd40d0f22013-06-17 21:45:05 +00002899 // Otherwise prefer the bottom candidate, in node order if all else failed.
Andrew Trick22025772012-05-17 18:35:10 +00002900 IsTopNode = false;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002901 tracePick(BotCand, IsTopNode);
Andrew Trick61f1a272012-05-24 22:11:09 +00002902 return BotCand.SU;
Andrew Trick22025772012-05-17 18:35:10 +00002903}
2904
2905/// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
Andrew Trick665d3ec2013-09-19 23:10:59 +00002906SUnit *GenericScheduler::pickNode(bool &IsTopNode) {
Andrew Trick7ee9de52012-05-10 21:06:16 +00002907 if (DAG->top() == DAG->bottom()) {
Andrew Trick61f1a272012-05-24 22:11:09 +00002908 assert(Top.Available.empty() && Top.Pending.empty() &&
2909 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
Andrew Trick7ee9de52012-05-10 21:06:16 +00002910 return NULL;
2911 }
Andrew Trick7ee9de52012-05-10 21:06:16 +00002912 SUnit *SU;
Andrew Trick984d98b2012-10-08 18:53:53 +00002913 do {
Andrew Trick75e411c2013-09-06 17:32:34 +00002914 if (RegionPolicy.OnlyTopDown) {
Andrew Trick984d98b2012-10-08 18:53:53 +00002915 SU = Top.pickOnlyChoice();
2916 if (!SU) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002917 CandPolicy NoPolicy;
2918 SchedCandidate TopCand(NoPolicy);
2919 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
Andrew Trick1ab16d92013-09-04 21:00:13 +00002920 assert(TopCand.Reason != NoCand && "failed to find a candidate");
Andrew Trickef54c592013-09-04 21:00:16 +00002921 tracePick(TopCand, true);
Andrew Trick984d98b2012-10-08 18:53:53 +00002922 SU = TopCand.SU;
2923 }
2924 IsTopNode = true;
Andrew Tricka306a8a2012-05-24 23:11:17 +00002925 }
Andrew Trick75e411c2013-09-06 17:32:34 +00002926 else if (RegionPolicy.OnlyBottomUp) {
Andrew Trick984d98b2012-10-08 18:53:53 +00002927 SU = Bot.pickOnlyChoice();
2928 if (!SU) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002929 CandPolicy NoPolicy;
2930 SchedCandidate BotCand(NoPolicy);
2931 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
Andrew Trick1ab16d92013-09-04 21:00:13 +00002932 assert(BotCand.Reason != NoCand && "failed to find a candidate");
Andrew Trickef54c592013-09-04 21:00:16 +00002933 tracePick(BotCand, false);
Andrew Trick984d98b2012-10-08 18:53:53 +00002934 SU = BotCand.SU;
2935 }
2936 IsTopNode = false;
Andrew Tricka306a8a2012-05-24 23:11:17 +00002937 }
Andrew Trick984d98b2012-10-08 18:53:53 +00002938 else {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002939 SU = pickNodeBidirectional(IsTopNode);
Andrew Trick984d98b2012-10-08 18:53:53 +00002940 }
2941 } while (SU->isScheduled);
2942
Andrew Trick61f1a272012-05-24 22:11:09 +00002943 if (SU->isTopReady())
2944 Top.removeReady(SU);
2945 if (SU->isBottomReady())
2946 Bot.removeReady(SU);
Andrew Trick4e7f6a72012-05-25 02:02:39 +00002947
Andrew Trick1f0bb692013-04-13 06:07:49 +00002948 DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " << *SU->getInstr());
Andrew Trick7ee9de52012-05-10 21:06:16 +00002949 return SU;
2950}
2951
Andrew Trick665d3ec2013-09-19 23:10:59 +00002952void GenericScheduler::reschedulePhysRegCopies(SUnit *SU, bool isTop) {
Andrew Tricke833e1c2013-04-13 06:07:40 +00002953
2954 MachineBasicBlock::iterator InsertPos = SU->getInstr();
2955 if (!isTop)
2956 ++InsertPos;
2957 SmallVectorImpl<SDep> &Deps = isTop ? SU->Preds : SU->Succs;
2958
2959 // Find already scheduled copies with a single physreg dependence and move
2960 // them just above the scheduled instruction.
2961 for (SmallVectorImpl<SDep>::iterator I = Deps.begin(), E = Deps.end();
2962 I != E; ++I) {
2963 if (I->getKind() != SDep::Data || !TRI->isPhysicalRegister(I->getReg()))
2964 continue;
2965 SUnit *DepSU = I->getSUnit();
2966 if (isTop ? DepSU->Succs.size() > 1 : DepSU->Preds.size() > 1)
2967 continue;
2968 MachineInstr *Copy = DepSU->getInstr();
2969 if (!Copy->isCopy())
2970 continue;
2971 DEBUG(dbgs() << " Rescheduling physreg copy ";
2972 I->getSUnit()->dump(DAG));
2973 DAG->moveInstruction(Copy, InsertPos);
2974 }
2975}
2976
Andrew Trick61f1a272012-05-24 22:11:09 +00002977/// Update the scheduler's state after scheduling a node. This is the same node
Andrew Trickd14d7c22013-12-28 21:56:57 +00002978/// that was just returned by pickNode(). However, ScheduleDAGMILive needs to
2979/// update it's state based on the current cycle before MachineSchedStrategy
2980/// does.
Andrew Tricke833e1c2013-04-13 06:07:40 +00002981///
2982/// FIXME: Eventually, we may bundle physreg copies rather than rescheduling
2983/// them here. See comments in biasPhysRegCopy.
Andrew Trick665d3ec2013-09-19 23:10:59 +00002984void GenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
Andrew Trick45446062012-06-05 21:11:27 +00002985 if (IsTopNode) {
Andrew Trickfc127d12013-12-07 05:59:44 +00002986 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
Andrew Trickce27bb92012-06-29 03:23:22 +00002987 Top.bumpNode(SU);
Andrew Tricke833e1c2013-04-13 06:07:40 +00002988 if (SU->hasPhysRegUses)
2989 reschedulePhysRegCopies(SU, true);
Andrew Trick61f1a272012-05-24 22:11:09 +00002990 }
Andrew Trick45446062012-06-05 21:11:27 +00002991 else {
Andrew Trickfc127d12013-12-07 05:59:44 +00002992 SU->BotReadyCycle = std::max(SU->BotReadyCycle, Bot.getCurrCycle());
Andrew Trickce27bb92012-06-29 03:23:22 +00002993 Bot.bumpNode(SU);
Andrew Tricke833e1c2013-04-13 06:07:40 +00002994 if (SU->hasPhysRegDefs)
2995 reschedulePhysRegCopies(SU, false);
Andrew Trick61f1a272012-05-24 22:11:09 +00002996 }
2997}
2998
Andrew Trick8823dec2012-03-14 04:00:41 +00002999/// Create the standard converging machine scheduler. This will be used as the
3000/// default scheduler if the target does not set a default.
Andrew Trickd14d7c22013-12-28 21:56:57 +00003001static ScheduleDAGInstrs *createGenericSchedLive(MachineSchedContext *C) {
3002 ScheduleDAGMILive *DAG = new ScheduleDAGMILive(C, new GenericScheduler(C));
Andrew Tricka7714a02012-11-12 19:40:10 +00003003 // Register DAG post-processors.
Andrew Trick85a1d4c2013-04-24 15:54:43 +00003004 //
3005 // FIXME: extend the mutation API to allow earlier mutations to instantiate
3006 // data and pass it to later mutations. Have a single mutation that gathers
3007 // the interesting nodes in one pass.
Andrew Trick0cd8afc2013-06-15 04:49:46 +00003008 DAG->addMutation(new CopyConstrain(DAG->TII, DAG->TRI));
Andrew Tricka6e87772013-09-04 21:00:08 +00003009 if (EnableLoadCluster && DAG->TII->enableClusterLoads())
Andrew Tricka7714a02012-11-12 19:40:10 +00003010 DAG->addMutation(new LoadClusterMutation(DAG->TII, DAG->TRI));
Andrew Trick263280242012-11-12 19:52:20 +00003011 if (EnableMacroFusion)
3012 DAG->addMutation(new MacroFusion(DAG->TII));
Andrew Tricka7714a02012-11-12 19:40:10 +00003013 return DAG;
Andrew Tricke1c034f2012-01-17 06:55:03 +00003014}
Andrew Trickd14d7c22013-12-28 21:56:57 +00003015
Andrew Tricke1c034f2012-01-17 06:55:03 +00003016static MachineSchedRegistry
Andrew Trick665d3ec2013-09-19 23:10:59 +00003017GenericSchedRegistry("converge", "Standard converging scheduler.",
Andrew Trickd14d7c22013-12-28 21:56:57 +00003018 createGenericSchedLive);
3019
3020//===----------------------------------------------------------------------===//
3021// PostGenericScheduler - Generic PostRA implementation of MachineSchedStrategy.
3022//===----------------------------------------------------------------------===//
3023
3024namespace {
3025/// PostGenericScheduler - Interface to the scheduling algorithm used by
3026/// ScheduleDAGMI.
3027///
3028/// Callbacks from ScheduleDAGMI:
3029/// initPolicy -> initialize(DAG) -> registerRoots -> pickNode ...
3030class PostGenericScheduler : public GenericSchedulerBase {
3031 ScheduleDAGMI *DAG;
3032 SchedBoundary Top;
3033 SmallVector<SUnit*, 8> BotRoots;
3034public:
3035 PostGenericScheduler(const MachineSchedContext *C):
3036 GenericSchedulerBase(C), Top(SchedBoundary::TopQID, "TopQ") {}
3037
3038 virtual ~PostGenericScheduler() {}
3039
Craig Topper24e685f2014-03-10 05:29:18 +00003040 void initPolicy(MachineBasicBlock::iterator Begin,
3041 MachineBasicBlock::iterator End,
3042 unsigned NumRegionInstrs) override {
Andrew Trickd14d7c22013-12-28 21:56:57 +00003043 /* no configurable policy */
3044 };
3045
3046 /// PostRA scheduling does not track pressure.
Craig Topper24e685f2014-03-10 05:29:18 +00003047 bool shouldTrackPressure() const override { return false; }
Andrew Trickd14d7c22013-12-28 21:56:57 +00003048
Craig Topper24e685f2014-03-10 05:29:18 +00003049 void initialize(ScheduleDAGMI *Dag) override {
Andrew Trickd14d7c22013-12-28 21:56:57 +00003050 DAG = Dag;
3051 SchedModel = DAG->getSchedModel();
3052 TRI = DAG->TRI;
3053
3054 Rem.init(DAG, SchedModel);
3055 Top.init(DAG, SchedModel, &Rem);
3056 BotRoots.clear();
3057
3058 // Initialize the HazardRecognizers. If itineraries don't exist, are empty,
3059 // or are disabled, then these HazardRecs will be disabled.
3060 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
3061 const TargetMachine &TM = DAG->MF.getTarget();
3062 if (!Top.HazardRec) {
3063 Top.HazardRec =
3064 TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
3065 }
3066 }
3067
Craig Topper24e685f2014-03-10 05:29:18 +00003068 void registerRoots() override;
Andrew Trickd14d7c22013-12-28 21:56:57 +00003069
Craig Topper24e685f2014-03-10 05:29:18 +00003070 SUnit *pickNode(bool &IsTopNode) override;
Andrew Trickd14d7c22013-12-28 21:56:57 +00003071
Craig Topper24e685f2014-03-10 05:29:18 +00003072 void scheduleTree(unsigned SubtreeID) override {
Andrew Trickd14d7c22013-12-28 21:56:57 +00003073 llvm_unreachable("PostRA scheduler does not support subtree analysis.");
3074 }
3075
Craig Topper24e685f2014-03-10 05:29:18 +00003076 void schedNode(SUnit *SU, bool IsTopNode) override;
Andrew Trickd14d7c22013-12-28 21:56:57 +00003077
Craig Topper24e685f2014-03-10 05:29:18 +00003078 void releaseTopNode(SUnit *SU) override {
Andrew Trickd14d7c22013-12-28 21:56:57 +00003079 Top.releaseTopNode(SU);
3080 }
3081
3082 // Only called for roots.
Craig Topper24e685f2014-03-10 05:29:18 +00003083 void releaseBottomNode(SUnit *SU) override {
Andrew Trickd14d7c22013-12-28 21:56:57 +00003084 BotRoots.push_back(SU);
3085 }
3086
3087protected:
3088 void tryCandidate(SchedCandidate &Cand, SchedCandidate &TryCand);
3089
3090 void pickNodeFromQueue(SchedCandidate &Cand);
3091};
3092} // namespace
3093
3094void PostGenericScheduler::registerRoots() {
3095 Rem.CriticalPath = DAG->ExitSU.getDepth();
3096
3097 // Some roots may not feed into ExitSU. Check all of them in case.
3098 for (SmallVectorImpl<SUnit*>::const_iterator
3099 I = BotRoots.begin(), E = BotRoots.end(); I != E; ++I) {
3100 if ((*I)->getDepth() > Rem.CriticalPath)
3101 Rem.CriticalPath = (*I)->getDepth();
3102 }
3103 DEBUG(dbgs() << "Critical Path: " << Rem.CriticalPath << '\n');
3104}
3105
3106/// Apply a set of heursitics to a new candidate for PostRA scheduling.
3107///
3108/// \param Cand provides the policy and current best candidate.
3109/// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
3110void PostGenericScheduler::tryCandidate(SchedCandidate &Cand,
3111 SchedCandidate &TryCand) {
3112
3113 // Initialize the candidate if needed.
3114 if (!Cand.isValid()) {
3115 TryCand.Reason = NodeOrder;
3116 return;
3117 }
3118
3119 // Prioritize instructions that read unbuffered resources by stall cycles.
3120 if (tryLess(Top.getLatencyStallCycles(TryCand.SU),
3121 Top.getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
3122 return;
3123
3124 // Avoid critical resource consumption and balance the schedule.
3125 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
3126 TryCand, Cand, ResourceReduce))
3127 return;
3128 if (tryGreater(TryCand.ResDelta.DemandedResources,
3129 Cand.ResDelta.DemandedResources,
3130 TryCand, Cand, ResourceDemand))
3131 return;
3132
3133 // Avoid serializing long latency dependence chains.
3134 if (Cand.Policy.ReduceLatency && tryLatency(TryCand, Cand, Top)) {
3135 return;
3136 }
3137
3138 // Fall through to original instruction order.
3139 if (TryCand.SU->NodeNum < Cand.SU->NodeNum)
3140 TryCand.Reason = NodeOrder;
3141}
3142
3143void PostGenericScheduler::pickNodeFromQueue(SchedCandidate &Cand) {
3144 ReadyQueue &Q = Top.Available;
3145
3146 DEBUG(Q.dump());
3147
3148 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
3149 SchedCandidate TryCand(Cand.Policy);
3150 TryCand.SU = *I;
3151 TryCand.initResourceDelta(DAG, SchedModel);
3152 tryCandidate(Cand, TryCand);
3153 if (TryCand.Reason != NoCand) {
3154 Cand.setBest(TryCand);
3155 DEBUG(traceCandidate(Cand));
3156 }
3157 }
3158}
3159
3160/// Pick the next node to schedule.
3161SUnit *PostGenericScheduler::pickNode(bool &IsTopNode) {
3162 if (DAG->top() == DAG->bottom()) {
3163 assert(Top.Available.empty() && Top.Pending.empty() && "ReadyQ garbage");
3164 return NULL;
3165 }
3166 SUnit *SU;
3167 do {
3168 SU = Top.pickOnlyChoice();
3169 if (!SU) {
3170 CandPolicy NoPolicy;
3171 SchedCandidate TopCand(NoPolicy);
3172 // Set the top-down policy based on the state of the current top zone and
3173 // the instructions outside the zone, including the bottom zone.
3174 setPolicy(TopCand.Policy, /*IsPostRA=*/true, Top, NULL);
3175 pickNodeFromQueue(TopCand);
3176 assert(TopCand.Reason != NoCand && "failed to find a candidate");
3177 tracePick(TopCand, true);
3178 SU = TopCand.SU;
3179 }
3180 } while (SU->isScheduled);
3181
3182 IsTopNode = true;
3183 Top.removeReady(SU);
3184
3185 DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " << *SU->getInstr());
3186 return SU;
3187}
3188
3189/// Called after ScheduleDAGMI has scheduled an instruction and updated
3190/// scheduled/remaining flags in the DAG nodes.
3191void PostGenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
3192 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
3193 Top.bumpNode(SU);
3194}
3195
3196/// Create a generic scheduler with no vreg liveness or DAG mutation passes.
3197static ScheduleDAGInstrs *createGenericSchedPostRA(MachineSchedContext *C) {
3198 return new ScheduleDAGMI(C, new PostGenericScheduler(C), /*IsPostRA=*/true);
3199}
Andrew Tricke1c034f2012-01-17 06:55:03 +00003200
3201//===----------------------------------------------------------------------===//
Andrew Trick90f711d2012-10-15 18:02:27 +00003202// ILP Scheduler. Currently for experimental analysis of heuristics.
3203//===----------------------------------------------------------------------===//
3204
3205namespace {
3206/// \brief Order nodes by the ILP metric.
3207struct ILPOrder {
Andrew Trick44f750a2013-01-25 04:01:04 +00003208 const SchedDFSResult *DFSResult;
3209 const BitVector *ScheduledTrees;
Andrew Trick90f711d2012-10-15 18:02:27 +00003210 bool MaximizeILP;
3211
Andrew Trick44f750a2013-01-25 04:01:04 +00003212 ILPOrder(bool MaxILP): DFSResult(0), ScheduledTrees(0), MaximizeILP(MaxILP) {}
Andrew Trick90f711d2012-10-15 18:02:27 +00003213
3214 /// \brief Apply a less-than relation on node priority.
Andrew Trick48d392e2012-11-28 05:13:28 +00003215 ///
3216 /// (Return true if A comes after B in the Q.)
Andrew Trick90f711d2012-10-15 18:02:27 +00003217 bool operator()(const SUnit *A, const SUnit *B) const {
Andrew Trick48d392e2012-11-28 05:13:28 +00003218 unsigned SchedTreeA = DFSResult->getSubtreeID(A);
3219 unsigned SchedTreeB = DFSResult->getSubtreeID(B);
3220 if (SchedTreeA != SchedTreeB) {
3221 // Unscheduled trees have lower priority.
3222 if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
3223 return ScheduledTrees->test(SchedTreeB);
3224
3225 // Trees with shallower connections have have lower priority.
3226 if (DFSResult->getSubtreeLevel(SchedTreeA)
3227 != DFSResult->getSubtreeLevel(SchedTreeB)) {
3228 return DFSResult->getSubtreeLevel(SchedTreeA)
3229 < DFSResult->getSubtreeLevel(SchedTreeB);
3230 }
3231 }
Andrew Trick90f711d2012-10-15 18:02:27 +00003232 if (MaximizeILP)
Andrew Trick48d392e2012-11-28 05:13:28 +00003233 return DFSResult->getILP(A) < DFSResult->getILP(B);
Andrew Trick90f711d2012-10-15 18:02:27 +00003234 else
Andrew Trick48d392e2012-11-28 05:13:28 +00003235 return DFSResult->getILP(A) > DFSResult->getILP(B);
Andrew Trick90f711d2012-10-15 18:02:27 +00003236 }
3237};
3238
3239/// \brief Schedule based on the ILP metric.
3240class ILPScheduler : public MachineSchedStrategy {
Andrew Trickd7f890e2013-12-28 21:56:47 +00003241 ScheduleDAGMILive *DAG;
Andrew Trick90f711d2012-10-15 18:02:27 +00003242 ILPOrder Cmp;
3243
3244 std::vector<SUnit*> ReadyQ;
3245public:
Andrew Trick44f750a2013-01-25 04:01:04 +00003246 ILPScheduler(bool MaximizeILP): DAG(0), Cmp(MaximizeILP) {}
Andrew Trick90f711d2012-10-15 18:02:27 +00003247
Craig Topper4584cd52014-03-07 09:26:03 +00003248 void initialize(ScheduleDAGMI *dag) override {
Andrew Trickd7f890e2013-12-28 21:56:47 +00003249 assert(dag->hasVRegLiveness() && "ILPScheduler needs vreg liveness");
3250 DAG = static_cast<ScheduleDAGMILive*>(dag);
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00003251 DAG->computeDFSResult();
Andrew Trick44f750a2013-01-25 04:01:04 +00003252 Cmp.DFSResult = DAG->getDFSResult();
3253 Cmp.ScheduledTrees = &DAG->getScheduledTrees();
Andrew Trick90f711d2012-10-15 18:02:27 +00003254 ReadyQ.clear();
Andrew Trick90f711d2012-10-15 18:02:27 +00003255 }
3256
Craig Topper4584cd52014-03-07 09:26:03 +00003257 void registerRoots() override {
Benjamin Krameraa598b32012-11-29 14:36:26 +00003258 // Restore the heap in ReadyQ with the updated DFS results.
3259 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
Andrew Trick90f711d2012-10-15 18:02:27 +00003260 }
3261
3262 /// Implement MachineSchedStrategy interface.
3263 /// -----------------------------------------
3264
Andrew Trick48d392e2012-11-28 05:13:28 +00003265 /// Callback to select the highest priority node from the ready Q.
Craig Topper4584cd52014-03-07 09:26:03 +00003266 SUnit *pickNode(bool &IsTopNode) override {
Andrew Trick90f711d2012-10-15 18:02:27 +00003267 if (ReadyQ.empty()) return NULL;
Matt Arsenault4ab769f2013-03-21 00:57:21 +00003268 std::pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
Andrew Trick90f711d2012-10-15 18:02:27 +00003269 SUnit *SU = ReadyQ.back();
3270 ReadyQ.pop_back();
3271 IsTopNode = false;
Andrew Trick1f0bb692013-04-13 06:07:49 +00003272 DEBUG(dbgs() << "Pick node " << "SU(" << SU->NodeNum << ") "
Andrew Trick44f750a2013-01-25 04:01:04 +00003273 << " ILP: " << DAG->getDFSResult()->getILP(SU)
3274 << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU) << " @"
3275 << DAG->getDFSResult()->getSubtreeLevel(
Andrew Trick1f0bb692013-04-13 06:07:49 +00003276 DAG->getDFSResult()->getSubtreeID(SU)) << '\n'
3277 << "Scheduling " << *SU->getInstr());
Andrew Trick90f711d2012-10-15 18:02:27 +00003278 return SU;
3279 }
3280
Andrew Trick44f750a2013-01-25 04:01:04 +00003281 /// \brief Scheduler callback to notify that a new subtree is scheduled.
Craig Topper4584cd52014-03-07 09:26:03 +00003282 void scheduleTree(unsigned SubtreeID) override {
Andrew Trick44f750a2013-01-25 04:01:04 +00003283 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3284 }
3285
Andrew Trick48d392e2012-11-28 05:13:28 +00003286 /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
3287 /// DFSResults, and resort the priority Q.
Craig Topper4584cd52014-03-07 09:26:03 +00003288 void schedNode(SUnit *SU, bool IsTopNode) override {
Andrew Trick48d392e2012-11-28 05:13:28 +00003289 assert(!IsTopNode && "SchedDFSResult needs bottom-up");
Andrew Trick48d392e2012-11-28 05:13:28 +00003290 }
Andrew Trick90f711d2012-10-15 18:02:27 +00003291
Craig Topper4584cd52014-03-07 09:26:03 +00003292 void releaseTopNode(SUnit *) override { /*only called for top roots*/ }
Andrew Trick90f711d2012-10-15 18:02:27 +00003293
Craig Topper4584cd52014-03-07 09:26:03 +00003294 void releaseBottomNode(SUnit *SU) override {
Andrew Trick90f711d2012-10-15 18:02:27 +00003295 ReadyQ.push_back(SU);
3296 std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3297 }
3298};
3299} // namespace
3300
3301static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
Andrew Trickd7f890e2013-12-28 21:56:47 +00003302 return new ScheduleDAGMILive(C, new ILPScheduler(true));
Andrew Trick90f711d2012-10-15 18:02:27 +00003303}
3304static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
Andrew Trickd7f890e2013-12-28 21:56:47 +00003305 return new ScheduleDAGMILive(C, new ILPScheduler(false));
Andrew Trick90f711d2012-10-15 18:02:27 +00003306}
3307static MachineSchedRegistry ILPMaxRegistry(
3308 "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
3309static MachineSchedRegistry ILPMinRegistry(
3310 "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
3311
3312//===----------------------------------------------------------------------===//
Andrew Trick63440872012-01-14 02:17:06 +00003313// Machine Instruction Shuffler for Correctness Testing
3314//===----------------------------------------------------------------------===//
3315
Andrew Tricke77e84e2012-01-13 06:30:30 +00003316#ifndef NDEBUG
3317namespace {
Andrew Trick8823dec2012-03-14 04:00:41 +00003318/// Apply a less-than relation on the node order, which corresponds to the
3319/// instruction order prior to scheduling. IsReverse implements greater-than.
3320template<bool IsReverse>
3321struct SUnitOrder {
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003322 bool operator()(SUnit *A, SUnit *B) const {
Andrew Trick8823dec2012-03-14 04:00:41 +00003323 if (IsReverse)
3324 return A->NodeNum > B->NodeNum;
3325 else
3326 return A->NodeNum < B->NodeNum;
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003327 }
3328};
3329
Andrew Tricke77e84e2012-01-13 06:30:30 +00003330/// Reorder instructions as much as possible.
Andrew Trick8823dec2012-03-14 04:00:41 +00003331class InstructionShuffler : public MachineSchedStrategy {
3332 bool IsAlternating;
3333 bool IsTopDown;
3334
3335 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
3336 // gives nodes with a higher number higher priority causing the latest
3337 // instructions to be scheduled first.
3338 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
3339 TopQ;
3340 // When scheduling bottom-up, use greater-than as the queue priority.
3341 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
3342 BottomQ;
Andrew Tricke77e84e2012-01-13 06:30:30 +00003343public:
Andrew Trick8823dec2012-03-14 04:00:41 +00003344 InstructionShuffler(bool alternate, bool topdown)
3345 : IsAlternating(alternate), IsTopDown(topdown) {}
Andrew Tricke77e84e2012-01-13 06:30:30 +00003346
Andrew Trickd7f890e2013-12-28 21:56:47 +00003347 virtual void initialize(ScheduleDAGMI*) {
Andrew Trick8823dec2012-03-14 04:00:41 +00003348 TopQ.clear();
3349 BottomQ.clear();
3350 }
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003351
Andrew Trick8823dec2012-03-14 04:00:41 +00003352 /// Implement MachineSchedStrategy interface.
3353 /// -----------------------------------------
3354
3355 virtual SUnit *pickNode(bool &IsTopNode) {
3356 SUnit *SU;
3357 if (IsTopDown) {
3358 do {
3359 if (TopQ.empty()) return NULL;
3360 SU = TopQ.top();
3361 TopQ.pop();
3362 } while (SU->isScheduled);
3363 IsTopNode = true;
3364 }
3365 else {
3366 do {
3367 if (BottomQ.empty()) return NULL;
3368 SU = BottomQ.top();
3369 BottomQ.pop();
3370 } while (SU->isScheduled);
3371 IsTopNode = false;
3372 }
3373 if (IsAlternating)
3374 IsTopDown = !IsTopDown;
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003375 return SU;
3376 }
3377
Andrew Trick61f1a272012-05-24 22:11:09 +00003378 virtual void schedNode(SUnit *SU, bool IsTopNode) {}
3379
Andrew Trick8823dec2012-03-14 04:00:41 +00003380 virtual void releaseTopNode(SUnit *SU) {
3381 TopQ.push(SU);
3382 }
3383 virtual void releaseBottomNode(SUnit *SU) {
3384 BottomQ.push(SU);
Andrew Tricke77e84e2012-01-13 06:30:30 +00003385 }
3386};
3387} // namespace
3388
Andrew Trick02a80da2012-03-08 01:41:12 +00003389static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
Andrew Trick8823dec2012-03-14 04:00:41 +00003390 bool Alternate = !ForceTopDown && !ForceBottomUp;
3391 bool TopDown = !ForceBottomUp;
Benjamin Kramer05e7a842012-03-14 11:26:37 +00003392 assert((TopDown || !ForceTopDown) &&
Andrew Trick8823dec2012-03-14 04:00:41 +00003393 "-misched-topdown incompatible with -misched-bottomup");
Andrew Trickd7f890e2013-12-28 21:56:47 +00003394 return new ScheduleDAGMILive(C, new InstructionShuffler(Alternate, TopDown));
Andrew Tricke77e84e2012-01-13 06:30:30 +00003395}
Andrew Trick8823dec2012-03-14 04:00:41 +00003396static MachineSchedRegistry ShufflerRegistry(
3397 "shuffle", "Shuffle machine instructions alternating directions",
3398 createInstructionShuffler);
Andrew Tricke77e84e2012-01-13 06:30:30 +00003399#endif // !NDEBUG
Andrew Trickea9fd952013-01-25 07:45:29 +00003400
3401//===----------------------------------------------------------------------===//
Andrew Trickd7f890e2013-12-28 21:56:47 +00003402// GraphWriter support for ScheduleDAGMILive.
Andrew Trickea9fd952013-01-25 07:45:29 +00003403//===----------------------------------------------------------------------===//
3404
3405#ifndef NDEBUG
3406namespace llvm {
3407
3408template<> struct GraphTraits<
3409 ScheduleDAGMI*> : public GraphTraits<ScheduleDAG*> {};
3410
3411template<>
3412struct DOTGraphTraits<ScheduleDAGMI*> : public DefaultDOTGraphTraits {
3413
3414 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
3415
3416 static std::string getGraphName(const ScheduleDAG *G) {
3417 return G->MF.getName();
3418 }
3419
3420 static bool renderGraphFromBottomUp() {
3421 return true;
3422 }
3423
3424 static bool isNodeHidden(const SUnit *Node) {
Andrew Trick856ecd92013-09-04 21:00:18 +00003425 return (Node->Preds.size() > 10 || Node->Succs.size() > 10);
Andrew Trickea9fd952013-01-25 07:45:29 +00003426 }
3427
3428 static bool hasNodeAddressLabel(const SUnit *Node,
3429 const ScheduleDAG *Graph) {
3430 return false;
3431 }
3432
3433 /// If you want to override the dot attributes printed for a particular
3434 /// edge, override this method.
3435 static std::string getEdgeAttributes(const SUnit *Node,
3436 SUnitIterator EI,
3437 const ScheduleDAG *Graph) {
3438 if (EI.isArtificialDep())
3439 return "color=cyan,style=dashed";
3440 if (EI.isCtrlDep())
3441 return "color=blue,style=dashed";
3442 return "";
3443 }
3444
3445 static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) {
3446 std::string Str;
3447 raw_string_ostream SS(Str);
Andrew Trickd7f890e2013-12-28 21:56:47 +00003448 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3449 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
3450 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : 0;
Andrew Trick7609b7d2013-09-06 17:32:42 +00003451 SS << "SU:" << SU->NodeNum;
3452 if (DFS)
3453 SS << " I:" << DFS->getNumInstrs(SU);
Andrew Trickea9fd952013-01-25 07:45:29 +00003454 return SS.str();
3455 }
3456 static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G) {
3457 return G->getGraphNodeLabel(SU);
3458 }
3459
Andrew Trickd7f890e2013-12-28 21:56:47 +00003460 static std::string getNodeAttributes(const SUnit *N, const ScheduleDAG *G) {
Andrew Trickea9fd952013-01-25 07:45:29 +00003461 std::string Str("shape=Mrecord");
Andrew Trickd7f890e2013-12-28 21:56:47 +00003462 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3463 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
3464 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : 0;
Andrew Trickea9fd952013-01-25 07:45:29 +00003465 if (DFS) {
3466 Str += ",style=filled,fillcolor=\"#";
3467 Str += DOT::getColorString(DFS->getSubtreeID(N));
3468 Str += '"';
3469 }
3470 return Str;
3471 }
3472};
3473} // namespace llvm
3474#endif // NDEBUG
3475
3476/// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
3477/// rendered using 'dot'.
3478///
3479void ScheduleDAGMI::viewGraph(const Twine &Name, const Twine &Title) {
3480#ifndef NDEBUG
3481 ViewGraph(this, Name, false, Title);
3482#else
3483 errs() << "ScheduleDAGMI::viewGraph is only available in debug builds on "
3484 << "systems with Graphviz or gv!\n";
3485#endif // NDEBUG
3486}
3487
3488/// Out-of-line implementation with no arguments is handy for gdb.
3489void ScheduleDAGMI::viewGraph() {
3490 viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName());
3491}