blob: cbe937a06f02efc98b5f905f2284153b930a1f67 [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
Andrew Trick02a80da2012-03-08 01:41:12 +000015#include "llvm/CodeGen/MachineScheduler.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/PriorityQueue.h"
17#include "llvm/Analysis/AliasAnalysis.h"
18#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Jakub Staszakdf17ddd2013-03-10 13:11:23 +000019#include "llvm/CodeGen/MachineDominators.h"
20#include "llvm/CodeGen/MachineLoopInfo.h"
Andrew Trick736dd9a2013-06-21 18:32:58 +000021#include "llvm/CodeGen/MachineRegisterInfo.h"
Andrew Tricke77e84e2012-01-13 06:30:30 +000022#include "llvm/CodeGen/Passes.h"
Andrew Trick05ff4662012-06-06 20:29:31 +000023#include "llvm/CodeGen/RegisterClassInfo.h"
Andrew Trickcd1c2f92012-11-28 05:13:24 +000024#include "llvm/CodeGen/ScheduleDFS.h"
Andrew Trick61f1a272012-05-24 22:11:09 +000025#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
Andrew Tricke77e84e2012-01-13 06:30:30 +000026#include "llvm/Support/CommandLine.h"
27#include "llvm/Support/Debug.h"
28#include "llvm/Support/ErrorHandling.h"
Andrew Trickea9fd952013-01-25 07:45:29 +000029#include "llvm/Support/GraphWriter.h"
Andrew Tricke77e84e2012-01-13 06:30:30 +000030#include "llvm/Support/raw_ostream.h"
Jakub Staszak80df8b82013-06-14 00:00:13 +000031#include "llvm/Target/TargetInstrInfo.h"
Andrew Trick7ccdc5c2012-01-17 06:55:07 +000032#include <queue>
33
Andrew Tricke77e84e2012-01-13 06:30:30 +000034using namespace llvm;
35
Chandler Carruth1b9dde02014-04-22 02:02:50 +000036#define DEBUG_TYPE "misched"
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():
Craig Topperc0196b12014-04-14 00:51:57 +000088 MF(nullptr), MLI(nullptr), MDT(nullptr), PassConfig(nullptr), AA(nullptr), LIS(nullptr) {
Andrew Trick4d4b5462012-04-24 20:36:19 +000089 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 Topperc0196b12014-04-14 00:51:57 +0000103 void print(raw_ostream &O, const Module* = nullptr) 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) {
Craig Topperc0196b12014-04-14 00:51:57 +0000195 return nullptr;
Andrew Trick45300682012-03-09 00:52:20 +0000196}
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) {
Paul Robinson7c99ec52014-03-31 17:43:35 +0000333 if (skipOptnoneFunction(*mf.getFunction()))
334 return false;
335
Andrew Trick8d2ee372014-06-04 07:06:27 +0000336 const TargetSubtargetInfo &ST =
337 mf.getTarget().getSubtarget<TargetSubtargetInfo>();
338 if (!ST.enablePostMachineScheduler()) {
339 DEBUG(dbgs() << "Subtarget disables post-MI-sched.\n");
340 return false;
341 }
Andrew Trick17080b92013-12-28 21:56:51 +0000342 DEBUG(dbgs() << "Before post-MI-sched:\n"; mf.print(dbgs()));
343
344 // Initialize the context of the pass.
345 MF = &mf;
346 PassConfig = &getAnalysis<TargetPassConfig>();
347
348 if (VerifyScheduling)
349 MF->verify(this, "Before post machine scheduling.");
350
351 // Instantiate the selected scheduler for this target, function, and
352 // optimization level.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000353 std::unique_ptr<ScheduleDAGInstrs> Scheduler(createPostMachineScheduler());
Andrew Trick17080b92013-12-28 21:56:51 +0000354 scheduleRegions(*Scheduler);
355
356 if (VerifyScheduling)
357 MF->verify(this, "After post machine scheduling.");
358 return true;
359}
360
Andrew Trickd14d7c22013-12-28 21:56:57 +0000361/// Return true of the given instruction should not be included in a scheduling
362/// region.
363///
364/// MachineScheduler does not currently support scheduling across calls. To
365/// handle calls, the DAG builder needs to be modified to create register
366/// anti/output dependencies on the registers clobbered by the call's regmask
367/// operand. In PreRA scheduling, the stack pointer adjustment already prevents
368/// scheduling across calls. In PostRA scheduling, we need the isCall to enforce
369/// the boundary, but there would be no benefit to postRA scheduling across
370/// calls this late anyway.
371static bool isSchedBoundary(MachineBasicBlock::iterator MI,
372 MachineBasicBlock *MBB,
373 MachineFunction *MF,
374 const TargetInstrInfo *TII,
375 bool IsPostRA) {
376 return MI->isCall() || TII->isSchedulingBoundary(MI, MBB, *MF);
377}
378
Andrew Trickd7f890e2013-12-28 21:56:47 +0000379/// Main driver for both MachineScheduler and PostMachineScheduler.
380void MachineSchedulerBase::scheduleRegions(ScheduleDAGInstrs &Scheduler) {
381 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
Andrew Trickd14d7c22013-12-28 21:56:57 +0000382 bool IsPostRA = Scheduler.isPostRA();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000383
384 // Visit all machine basic blocks.
Andrew Trick88639922012-04-24 17:56:43 +0000385 //
386 // TODO: Visit blocks in global postorder or postorder within the bottom-up
387 // loop tree. Then we can optionally compute global RegPressure.
Andrew Tricke77e84e2012-01-13 06:30:30 +0000388 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
389 MBB != MBBEnd; ++MBB) {
390
Andrew Trickd7f890e2013-12-28 21:56:47 +0000391 Scheduler.startBlock(MBB);
Andrew Trickedfe2ec2012-03-09 08:02:51 +0000392
Andrew Trick33e05d72013-12-28 21:57:02 +0000393#ifndef NDEBUG
394 if (SchedOnlyFunc.getNumOccurrences() && SchedOnlyFunc != MF->getName())
395 continue;
396 if (SchedOnlyBlock.getNumOccurrences()
397 && (int)SchedOnlyBlock != MBB->getNumber())
398 continue;
399#endif
400
Andrew Trick7e120f42012-01-14 02:17:09 +0000401 // Break the block into scheduling regions [I, RegionEnd), and schedule each
Sylvestre Ledru35521e22012-07-23 08:51:15 +0000402 // region as soon as it is discovered. RegionEnd points the scheduling
Andrew Trickaf1bee72012-03-09 22:34:56 +0000403 // boundary at the bottom of the region. The DAG does not include RegionEnd,
404 // but the region does (i.e. the next RegionEnd is above the previous
405 // RegionBegin). If the current block has no terminator then RegionEnd ==
406 // MBB->end() for the bottom region.
407 //
408 // The Scheduler may insert instructions during either schedule() or
409 // exitRegion(), even for empty regions. So the local iterators 'I' and
410 // 'RegionEnd' are invalid across these calls.
Andrew Trickd14d7c22013-12-28 21:56:57 +0000411 //
412 // MBB::size() uses instr_iterator to count. Here we need a bundle to count
413 // as a single instruction.
414 unsigned RemainingInstrs = std::distance(MBB->begin(), MBB->end());
Andrew Tricka21daf72012-03-09 03:46:39 +0000415 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
Andrew Trickd7f890e2013-12-28 21:56:47 +0000416 RegionEnd != MBB->begin(); RegionEnd = Scheduler.begin()) {
Andrew Trick88639922012-04-24 17:56:43 +0000417
Andrew Trickedfe2ec2012-03-09 08:02:51 +0000418 // Avoid decrementing RegionEnd for blocks with no terminator.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000419 if (RegionEnd != MBB->end() ||
420 isSchedBoundary(std::prev(RegionEnd), MBB, MF, TII, IsPostRA)) {
Andrew Trickedfe2ec2012-03-09 08:02:51 +0000421 --RegionEnd;
422 // Count the boundary instruction.
Andrew Trick4d1fa712012-11-06 07:10:34 +0000423 --RemainingInstrs;
Andrew Trickedfe2ec2012-03-09 08:02:51 +0000424 }
425
Andrew Trick7e120f42012-01-14 02:17:09 +0000426 // The next region starts above the previous region. Look backward in the
427 // instruction stream until we find the nearest boundary.
Andrew Tricka53e1012013-08-23 17:48:33 +0000428 unsigned NumRegionInstrs = 0;
Andrew Trick7e120f42012-01-14 02:17:09 +0000429 MachineBasicBlock::iterator I = RegionEnd;
Andrew Tricka53e1012013-08-23 17:48:33 +0000430 for(;I != MBB->begin(); --I, --RemainingInstrs, ++NumRegionInstrs) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000431 if (isSchedBoundary(std::prev(I), MBB, MF, TII, IsPostRA))
Andrew Trick7e120f42012-01-14 02:17:09 +0000432 break;
433 }
Andrew Trick60cf03e2012-03-07 05:21:52 +0000434 // Notify the scheduler of the region, even if we may skip scheduling
435 // it. Perhaps it still needs to be bundled.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000436 Scheduler.enterRegion(MBB, I, RegionEnd, NumRegionInstrs);
Andrew Trick60cf03e2012-03-07 05:21:52 +0000437
438 // Skip empty scheduling regions (0 or 1 schedulable instructions).
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000439 if (I == RegionEnd || I == std::prev(RegionEnd)) {
Andrew Trick60cf03e2012-03-07 05:21:52 +0000440 // Close the current region. Bundle the terminator if needed.
Andrew Trickaf1bee72012-03-09 22:34:56 +0000441 // This invalidates 'RegionEnd' and 'I'.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000442 Scheduler.exitRegion();
Andrew Trick7ccdc5c2012-01-17 06:55:07 +0000443 continue;
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000444 }
Andrew Trickd14d7c22013-12-28 21:56:57 +0000445 DEBUG(dbgs() << "********** " << ((Scheduler.isPostRA()) ? "PostRA " : "")
446 << "MI Scheduling **********\n");
Craig Toppera538d832012-08-22 06:07:19 +0000447 DEBUG(dbgs() << MF->getName()
Andrew Trick54b2ce32013-01-25 07:45:31 +0000448 << ":BB#" << MBB->getNumber() << " " << MBB->getName()
449 << "\n From: " << *I << " To: ";
Andrew Tricke57583a2012-02-08 02:17:21 +0000450 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
451 else dbgs() << "End";
Andrew Tricka53e1012013-08-23 17:48:33 +0000452 dbgs() << " RegionInstrs: " << NumRegionInstrs
453 << " Remaining: " << RemainingInstrs << "\n");
Andrew Trick7ccdc5c2012-01-17 06:55:07 +0000454
Andrew Trick1c0ec452012-03-09 03:46:42 +0000455 // Schedule a region: possibly reorder instructions.
Andrew Trickaf1bee72012-03-09 22:34:56 +0000456 // This invalidates 'RegionEnd' and 'I'.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000457 Scheduler.schedule();
Andrew Trick1c0ec452012-03-09 03:46:42 +0000458
459 // Close the current region.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000460 Scheduler.exitRegion();
Andrew Trick60cf03e2012-03-07 05:21:52 +0000461
462 // Scheduling has invalidated the current iterator 'I'. Ask the
463 // scheduler for the top of it's scheduled region.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000464 RegionEnd = Scheduler.begin();
Andrew Trick7e120f42012-01-14 02:17:09 +0000465 }
Andrew Trick4d1fa712012-11-06 07:10:34 +0000466 assert(RemainingInstrs == 0 && "Instruction count mismatch!");
Andrew Trickd7f890e2013-12-28 21:56:47 +0000467 Scheduler.finishBlock();
Andrew Trickd14d7c22013-12-28 21:56:57 +0000468 if (Scheduler.isPostRA()) {
469 // FIXME: Ideally, no further passes should rely on kill flags. However,
470 // thumb2 size reduction is currently an exception.
471 Scheduler.fixupKills(MBB);
472 }
Andrew Tricke77e84e2012-01-13 06:30:30 +0000473 }
Andrew Trickd7f890e2013-12-28 21:56:47 +0000474 Scheduler.finalizeSchedule();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000475}
476
Andrew Trickd7f890e2013-12-28 21:56:47 +0000477void MachineSchedulerBase::print(raw_ostream &O, const Module* m) const {
Andrew Tricke77e84e2012-01-13 06:30:30 +0000478 // unimplemented
479}
480
Manman Ren19f49ac2012-09-11 22:23:19 +0000481#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Andrew Trick7a8e1002012-09-11 00:39:15 +0000482void ReadyQueue::dump() {
Andrew Trickd40d0f22013-06-17 21:45:05 +0000483 dbgs() << Name << ": ";
Andrew Trick7a8e1002012-09-11 00:39:15 +0000484 for (unsigned i = 0, e = Queue.size(); i < e; ++i)
485 dbgs() << Queue[i]->NodeNum << " ";
486 dbgs() << "\n";
487}
488#endif
Andrew Trick8823dec2012-03-14 04:00:41 +0000489
490//===----------------------------------------------------------------------===//
Andrew Trickd7f890e2013-12-28 21:56:47 +0000491// ScheduleDAGMI - Basic machine instruction scheduling. This is
492// independent of PreRA/PostRA scheduling and involves no extra book-keeping for
493// virtual registers.
494// ===----------------------------------------------------------------------===/
Andrew Trick8823dec2012-03-14 04:00:41 +0000495
David Blaikie422b93d2014-04-21 20:32:32 +0000496// Provide a vtable anchor.
Andrew Trick44f750a2013-01-25 04:01:04 +0000497ScheduleDAGMI::~ScheduleDAGMI() {
Andrew Trick44f750a2013-01-25 04:01:04 +0000498}
499
Andrew Trick85a1d4c2013-04-24 15:54:43 +0000500bool ScheduleDAGMI::canAddEdge(SUnit *SuccSU, SUnit *PredSU) {
501 return SuccSU == &ExitSU || !Topo.IsReachable(PredSU, SuccSU);
502}
503
Andrew Tricka7714a02012-11-12 19:40:10 +0000504bool ScheduleDAGMI::addEdge(SUnit *SuccSU, const SDep &PredDep) {
Andrew Trick263280242012-11-12 19:52:20 +0000505 if (SuccSU != &ExitSU) {
506 // Do not use WillCreateCycle, it assumes SD scheduling.
507 // If Pred is reachable from Succ, then the edge creates a cycle.
508 if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
509 return false;
510 Topo.AddPred(SuccSU, PredDep.getSUnit());
511 }
Andrew Tricka7714a02012-11-12 19:40:10 +0000512 SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
513 // Return true regardless of whether a new edge needed to be inserted.
514 return true;
515}
516
Andrew Trick02a80da2012-03-08 01:41:12 +0000517/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
518/// NumPredsLeft reaches zero, release the successor node.
Andrew Trick61f1a272012-05-24 22:11:09 +0000519///
520/// FIXME: Adjust SuccSU height based on MinLatency.
Andrew Trick8823dec2012-03-14 04:00:41 +0000521void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
Andrew Trick02a80da2012-03-08 01:41:12 +0000522 SUnit *SuccSU = SuccEdge->getSUnit();
523
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000524 if (SuccEdge->isWeak()) {
525 --SuccSU->WeakPredsLeft;
Andrew Tricka7714a02012-11-12 19:40:10 +0000526 if (SuccEdge->isCluster())
527 NextClusterSucc = SuccSU;
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000528 return;
529 }
Andrew Trick02a80da2012-03-08 01:41:12 +0000530#ifndef NDEBUG
531 if (SuccSU->NumPredsLeft == 0) {
532 dbgs() << "*** Scheduling failed! ***\n";
533 SuccSU->dump(this);
534 dbgs() << " has been released too many times!\n";
Craig Topperc0196b12014-04-14 00:51:57 +0000535 llvm_unreachable(nullptr);
Andrew Trick02a80da2012-03-08 01:41:12 +0000536 }
537#endif
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000538 // SU->TopReadyCycle was set to CurrCycle when it was scheduled. However,
539 // CurrCycle may have advanced since then.
540 if (SuccSU->TopReadyCycle < SU->TopReadyCycle + SuccEdge->getLatency())
541 SuccSU->TopReadyCycle = SU->TopReadyCycle + SuccEdge->getLatency();
542
Andrew Trick02a80da2012-03-08 01:41:12 +0000543 --SuccSU->NumPredsLeft;
544 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
Andrew Trick8823dec2012-03-14 04:00:41 +0000545 SchedImpl->releaseTopNode(SuccSU);
Andrew Trick02a80da2012-03-08 01:41:12 +0000546}
547
548/// releaseSuccessors - Call releaseSucc on each of SU's successors.
Andrew Trick8823dec2012-03-14 04:00:41 +0000549void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
Andrew Trick02a80da2012-03-08 01:41:12 +0000550 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
551 I != E; ++I) {
552 releaseSucc(SU, &*I);
553 }
554}
555
Andrew Trick8823dec2012-03-14 04:00:41 +0000556/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
557/// NumSuccsLeft reaches zero, release the predecessor node.
Andrew Trick61f1a272012-05-24 22:11:09 +0000558///
559/// FIXME: Adjust PredSU height based on MinLatency.
Andrew Trick8823dec2012-03-14 04:00:41 +0000560void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
561 SUnit *PredSU = PredEdge->getSUnit();
562
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000563 if (PredEdge->isWeak()) {
564 --PredSU->WeakSuccsLeft;
Andrew Tricka7714a02012-11-12 19:40:10 +0000565 if (PredEdge->isCluster())
566 NextClusterPred = PredSU;
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000567 return;
568 }
Andrew Trick8823dec2012-03-14 04:00:41 +0000569#ifndef NDEBUG
570 if (PredSU->NumSuccsLeft == 0) {
571 dbgs() << "*** Scheduling failed! ***\n";
572 PredSU->dump(this);
573 dbgs() << " has been released too many times!\n";
Craig Topperc0196b12014-04-14 00:51:57 +0000574 llvm_unreachable(nullptr);
Andrew Trick8823dec2012-03-14 04:00:41 +0000575 }
576#endif
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000577 // SU->BotReadyCycle was set to CurrCycle when it was scheduled. However,
578 // CurrCycle may have advanced since then.
579 if (PredSU->BotReadyCycle < SU->BotReadyCycle + PredEdge->getLatency())
580 PredSU->BotReadyCycle = SU->BotReadyCycle + PredEdge->getLatency();
581
Andrew Trick8823dec2012-03-14 04:00:41 +0000582 --PredSU->NumSuccsLeft;
583 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
584 SchedImpl->releaseBottomNode(PredSU);
585}
586
587/// releasePredecessors - Call releasePred on each of SU's predecessors.
588void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
589 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
590 I != E; ++I) {
591 releasePred(SU, &*I);
592 }
593}
594
Andrew Trickd7f890e2013-12-28 21:56:47 +0000595/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
596/// crossing a scheduling boundary. [begin, end) includes all instructions in
597/// the region, including the boundary itself and single-instruction regions
598/// that don't get scheduled.
599void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
600 MachineBasicBlock::iterator begin,
601 MachineBasicBlock::iterator end,
602 unsigned regioninstrs)
603{
604 ScheduleDAGInstrs::enterRegion(bb, begin, end, regioninstrs);
605
606 SchedImpl->initPolicy(begin, end, regioninstrs);
607}
608
Andrew Tricke833e1c2013-04-13 06:07:40 +0000609/// This is normally called from the main scheduler loop but may also be invoked
610/// by the scheduling strategy to perform additional code motion.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000611void ScheduleDAGMI::moveInstruction(
612 MachineInstr *MI, MachineBasicBlock::iterator InsertPos) {
Andrew Trick463b2f12012-05-17 18:35:03 +0000613 // Advance RegionBegin if the first instruction moves down.
Andrew Trick54f7def2012-03-21 04:12:10 +0000614 if (&*RegionBegin == MI)
Andrew Trick463b2f12012-05-17 18:35:03 +0000615 ++RegionBegin;
616
617 // Update the instruction stream.
Andrew Trick8823dec2012-03-14 04:00:41 +0000618 BB->splice(InsertPos, BB, MI);
Andrew Trick463b2f12012-05-17 18:35:03 +0000619
620 // Update LiveIntervals
Andrew Trickd7f890e2013-12-28 21:56:47 +0000621 if (LIS)
622 LIS->handleMove(MI, /*UpdateFlags=*/true);
Andrew Trick463b2f12012-05-17 18:35:03 +0000623
624 // Recede RegionBegin if an instruction moves above the first.
Andrew Trick8823dec2012-03-14 04:00:41 +0000625 if (RegionBegin == InsertPos)
626 RegionBegin = MI;
627}
628
Andrew Trickde670c02012-03-21 04:12:07 +0000629bool ScheduleDAGMI::checkSchedLimit() {
630#ifndef NDEBUG
631 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
632 CurrentTop = CurrentBottom;
633 return false;
634 }
635 ++NumInstrsScheduled;
636#endif
637 return true;
638}
639
Andrew Trickd7f890e2013-12-28 21:56:47 +0000640/// Per-region scheduling driver, called back from
641/// MachineScheduler::runOnMachineFunction. This is a simplified driver that
642/// does not consider liveness or register pressure. It is useful for PostRA
643/// scheduling and potentially other custom schedulers.
644void ScheduleDAGMI::schedule() {
645 // Build the DAG.
646 buildSchedGraph(AA);
647
648 Topo.InitDAGTopologicalSorting();
649
650 postprocessDAG();
651
652 SmallVector<SUnit*, 8> TopRoots, BotRoots;
653 findRootsAndBiasEdges(TopRoots, BotRoots);
654
655 // Initialize the strategy before modifying the DAG.
656 // This may initialize a DFSResult to be used for queue priority.
657 SchedImpl->initialize(this);
658
659 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
660 SUnits[su].dumpAll(this));
661 if (ViewMISchedDAGs) viewGraph();
662
663 // Initialize ready queues now that the DAG and priority data are finalized.
664 initQueues(TopRoots, BotRoots);
665
666 bool IsTopNode = false;
667 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
668 assert(!SU->isScheduled && "Node already scheduled");
669 if (!checkSchedLimit())
670 break;
671
672 MachineInstr *MI = SU->getInstr();
673 if (IsTopNode) {
674 assert(SU->isTopReady() && "node still has unscheduled dependencies");
675 if (&*CurrentTop == MI)
676 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
677 else
678 moveInstruction(MI, CurrentTop);
679 }
680 else {
681 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
682 MachineBasicBlock::iterator priorII =
683 priorNonDebug(CurrentBottom, CurrentTop);
684 if (&*priorII == MI)
685 CurrentBottom = priorII;
686 else {
687 if (&*CurrentTop == MI)
688 CurrentTop = nextIfDebug(++CurrentTop, priorII);
689 moveInstruction(MI, CurrentBottom);
690 CurrentBottom = MI;
691 }
692 }
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000693 // Notify the scheduling strategy before updating the DAG.
694 // This sets the scheduled nodes ReadyCycle to CurrCycle. When updateQueues
695 // runs, it can then use the accurate ReadyCycle time to determine whether
696 // newly released nodes can move to the readyQ.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000697 SchedImpl->schedNode(SU, IsTopNode);
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000698
699 updateQueues(SU, IsTopNode);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000700 }
701 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
702
703 placeDebugValues();
704
705 DEBUG({
706 unsigned BBNum = begin()->getParent()->getNumber();
707 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
708 dumpSchedule();
709 dbgs() << '\n';
710 });
711}
712
713/// Apply each ScheduleDAGMutation step in order.
714void ScheduleDAGMI::postprocessDAG() {
715 for (unsigned i = 0, e = Mutations.size(); i < e; ++i) {
716 Mutations[i]->apply(this);
717 }
718}
719
720void ScheduleDAGMI::
721findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
722 SmallVectorImpl<SUnit*> &BotRoots) {
723 for (std::vector<SUnit>::iterator
724 I = SUnits.begin(), E = SUnits.end(); I != E; ++I) {
725 SUnit *SU = &(*I);
726 assert(!SU->isBoundaryNode() && "Boundary node should not be in SUnits");
727
728 // Order predecessors so DFSResult follows the critical path.
729 SU->biasCriticalPath();
730
731 // A SUnit is ready to top schedule if it has no predecessors.
732 if (!I->NumPredsLeft)
733 TopRoots.push_back(SU);
734 // A SUnit is ready to bottom schedule if it has no successors.
735 if (!I->NumSuccsLeft)
736 BotRoots.push_back(SU);
737 }
738 ExitSU.biasCriticalPath();
739}
740
741/// Identify DAG roots and setup scheduler queues.
742void ScheduleDAGMI::initQueues(ArrayRef<SUnit*> TopRoots,
743 ArrayRef<SUnit*> BotRoots) {
Craig Topperc0196b12014-04-14 00:51:57 +0000744 NextClusterSucc = nullptr;
745 NextClusterPred = nullptr;
Andrew Trickd7f890e2013-12-28 21:56:47 +0000746
747 // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
748 //
749 // Nodes with unreleased weak edges can still be roots.
750 // Release top roots in forward order.
751 for (SmallVectorImpl<SUnit*>::const_iterator
752 I = TopRoots.begin(), E = TopRoots.end(); I != E; ++I) {
753 SchedImpl->releaseTopNode(*I);
754 }
755 // Release bottom roots in reverse order so the higher priority nodes appear
756 // first. This is more natural and slightly more efficient.
757 for (SmallVectorImpl<SUnit*>::const_reverse_iterator
758 I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I) {
759 SchedImpl->releaseBottomNode(*I);
760 }
761
762 releaseSuccessors(&EntrySU);
763 releasePredecessors(&ExitSU);
764
765 SchedImpl->registerRoots();
766
767 // Advance past initial DebugValues.
768 CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
769 CurrentBottom = RegionEnd;
770}
771
772/// Update scheduler queues after scheduling an instruction.
773void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
774 // Release dependent instructions for scheduling.
775 if (IsTopNode)
776 releaseSuccessors(SU);
777 else
778 releasePredecessors(SU);
779
780 SU->isScheduled = true;
781}
782
783/// Reinsert any remaining debug_values, just like the PostRA scheduler.
784void ScheduleDAGMI::placeDebugValues() {
785 // If first instruction was a DBG_VALUE then put it back.
786 if (FirstDbgValue) {
787 BB->splice(RegionBegin, BB, FirstDbgValue);
788 RegionBegin = FirstDbgValue;
789 }
790
791 for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
792 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000793 std::pair<MachineInstr *, MachineInstr *> P = *std::prev(DI);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000794 MachineInstr *DbgValue = P.first;
795 MachineBasicBlock::iterator OrigPrevMI = P.second;
796 if (&*RegionBegin == DbgValue)
797 ++RegionBegin;
798 BB->splice(++OrigPrevMI, BB, DbgValue);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000799 if (OrigPrevMI == std::prev(RegionEnd))
Andrew Trickd7f890e2013-12-28 21:56:47 +0000800 RegionEnd = DbgValue;
801 }
802 DbgValues.clear();
Craig Topperc0196b12014-04-14 00:51:57 +0000803 FirstDbgValue = nullptr;
Andrew Trickd7f890e2013-12-28 21:56:47 +0000804}
805
806#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
807void ScheduleDAGMI::dumpSchedule() const {
808 for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
809 if (SUnit *SU = getSUnit(&(*MI)))
810 SU->dump(this);
811 else
812 dbgs() << "Missing SUnit\n";
813 }
814}
815#endif
816
817//===----------------------------------------------------------------------===//
818// ScheduleDAGMILive - Base class for MachineInstr scheduling with LiveIntervals
819// preservation.
820//===----------------------------------------------------------------------===//
821
822ScheduleDAGMILive::~ScheduleDAGMILive() {
823 delete DFSResult;
824}
825
Andrew Trick88639922012-04-24 17:56:43 +0000826/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
827/// crossing a scheduling boundary. [begin, end) includes all instructions in
828/// the region, including the boundary itself and single-instruction regions
829/// that don't get scheduled.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000830void ScheduleDAGMILive::enterRegion(MachineBasicBlock *bb,
Andrew Trick88639922012-04-24 17:56:43 +0000831 MachineBasicBlock::iterator begin,
832 MachineBasicBlock::iterator end,
Andrew Tricka53e1012013-08-23 17:48:33 +0000833 unsigned regioninstrs)
Andrew Trick88639922012-04-24 17:56:43 +0000834{
Andrew Trickd7f890e2013-12-28 21:56:47 +0000835 // ScheduleDAGMI initializes SchedImpl's per-region policy.
836 ScheduleDAGMI::enterRegion(bb, begin, end, regioninstrs);
Andrew Trick4add42f2012-05-10 21:06:10 +0000837
838 // For convenience remember the end of the liveness region.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000839 LiveRegionEnd = (RegionEnd == bb->end()) ? RegionEnd : std::next(RegionEnd);
Andrew Trick75e411c2013-09-06 17:32:34 +0000840
Andrew Trickb248b4a2013-09-06 17:32:47 +0000841 SUPressureDiffs.clear();
842
Andrew Trick75e411c2013-09-06 17:32:34 +0000843 ShouldTrackPressure = SchedImpl->shouldTrackPressure();
Andrew Trick4add42f2012-05-10 21:06:10 +0000844}
845
846// Setup the register pressure trackers for the top scheduled top and bottom
847// scheduled regions.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000848void ScheduleDAGMILive::initRegPressure() {
Andrew Trick4add42f2012-05-10 21:06:10 +0000849 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin);
850 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
851
852 // Close the RPTracker to finalize live ins.
853 RPTracker.closeRegion();
854
Andrew Trick9c17eab2013-07-30 19:59:12 +0000855 DEBUG(RPTracker.dump());
Andrew Trick79d3eec2012-05-24 22:11:14 +0000856
Andrew Trick4add42f2012-05-10 21:06:10 +0000857 // Initialize the live ins and live outs.
858 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
859 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
860
861 // Close one end of the tracker so we can call
862 // getMaxUpward/DownwardPressureDelta before advancing across any
863 // instructions. This converts currently live regs into live ins/outs.
864 TopRPTracker.closeTop();
865 BotRPTracker.closeBottom();
866
Andrew Trick9c17eab2013-07-30 19:59:12 +0000867 BotRPTracker.initLiveThru(RPTracker);
868 if (!BotRPTracker.getLiveThru().empty()) {
869 TopRPTracker.initLiveThru(BotRPTracker.getLiveThru());
870 DEBUG(dbgs() << "Live Thru: ";
871 dumpRegSetPressure(BotRPTracker.getLiveThru(), TRI));
872 };
873
Andrew Trick2bc74c22013-08-30 04:36:57 +0000874 // For each live out vreg reduce the pressure change associated with other
875 // uses of the same vreg below the live-out reaching def.
876 updatePressureDiffs(RPTracker.getPressure().LiveOutRegs);
877
Andrew Trick4add42f2012-05-10 21:06:10 +0000878 // Account for liveness generated by the region boundary.
Andrew Trick2bc74c22013-08-30 04:36:57 +0000879 if (LiveRegionEnd != RegionEnd) {
880 SmallVector<unsigned, 8> LiveUses;
881 BotRPTracker.recede(&LiveUses);
882 updatePressureDiffs(LiveUses);
883 }
Andrew Trick4add42f2012-05-10 21:06:10 +0000884
885 assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
Andrew Trick22025772012-05-17 18:35:10 +0000886
887 // Cache the list of excess pressure sets in this region. This will also track
888 // the max pressure in the scheduled code for these sets.
889 RegionCriticalPSets.clear();
Jakub Staszakc641ada2013-01-25 21:44:27 +0000890 const std::vector<unsigned> &RegionPressure =
891 RPTracker.getPressure().MaxSetPressure;
Andrew Trick22025772012-05-17 18:35:10 +0000892 for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
Andrew Trick736dd9a2013-06-21 18:32:58 +0000893 unsigned Limit = RegClassInfo->getRegPressureSetLimit(i);
Andrew Trickb55db582013-06-21 18:33:01 +0000894 if (RegionPressure[i] > Limit) {
895 DEBUG(dbgs() << TRI->getRegPressureSetName(i)
896 << " Limit " << Limit
897 << " Actual " << RegionPressure[i] << "\n");
Andrew Trick1a831342013-08-30 03:49:48 +0000898 RegionCriticalPSets.push_back(PressureChange(i));
Andrew Trickb55db582013-06-21 18:33:01 +0000899 }
Andrew Trick22025772012-05-17 18:35:10 +0000900 }
901 DEBUG(dbgs() << "Excess PSets: ";
902 for (unsigned i = 0, e = RegionCriticalPSets.size(); i != e; ++i)
903 dbgs() << TRI->getRegPressureSetName(
Andrew Trick1a831342013-08-30 03:49:48 +0000904 RegionCriticalPSets[i].getPSet()) << " ";
Andrew Trick22025772012-05-17 18:35:10 +0000905 dbgs() << "\n");
906}
907
Andrew Trickd7f890e2013-12-28 21:56:47 +0000908void ScheduleDAGMILive::
Andrew Trickb248b4a2013-09-06 17:32:47 +0000909updateScheduledPressure(const SUnit *SU,
910 const std::vector<unsigned> &NewMaxPressure) {
911 const PressureDiff &PDiff = getPressureDiff(SU);
912 unsigned CritIdx = 0, CritEnd = RegionCriticalPSets.size();
913 for (PressureDiff::const_iterator I = PDiff.begin(), E = PDiff.end();
914 I != E; ++I) {
915 if (!I->isValid())
916 break;
917 unsigned ID = I->getPSet();
918 while (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() < ID)
919 ++CritIdx;
920 if (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() == ID) {
921 if ((int)NewMaxPressure[ID] > RegionCriticalPSets[CritIdx].getUnitInc()
922 && NewMaxPressure[ID] <= INT16_MAX)
923 RegionCriticalPSets[CritIdx].setUnitInc(NewMaxPressure[ID]);
924 }
925 unsigned Limit = RegClassInfo->getRegPressureSetLimit(ID);
926 if (NewMaxPressure[ID] >= Limit - 2) {
927 DEBUG(dbgs() << " " << TRI->getRegPressureSetName(ID) << ": "
928 << NewMaxPressure[ID] << " > " << Limit << "(+ "
929 << BotRPTracker.getLiveThru()[ID] << " livethru)\n");
930 }
Andrew Trick22025772012-05-17 18:35:10 +0000931 }
Andrew Trick88639922012-04-24 17:56:43 +0000932}
933
Andrew Trick2bc74c22013-08-30 04:36:57 +0000934/// Update the PressureDiff array for liveness after scheduling this
935/// instruction.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000936void ScheduleDAGMILive::updatePressureDiffs(ArrayRef<unsigned> LiveUses) {
Andrew Trick2bc74c22013-08-30 04:36:57 +0000937 for (unsigned LUIdx = 0, LUEnd = LiveUses.size(); LUIdx != LUEnd; ++LUIdx) {
938 /// FIXME: Currently assuming single-use physregs.
939 unsigned Reg = LiveUses[LUIdx];
Andrew Trickffdbefb2013-09-06 17:32:39 +0000940 DEBUG(dbgs() << " LiveReg: " << PrintVRegOrUnit(Reg, TRI) << "\n");
Andrew Trick2bc74c22013-08-30 04:36:57 +0000941 if (!TRI->isVirtualRegister(Reg))
942 continue;
Andrew Trickffdbefb2013-09-06 17:32:39 +0000943
Andrew Trick2bc74c22013-08-30 04:36:57 +0000944 // This may be called before CurrentBottom has been initialized. However,
945 // BotRPTracker must have a valid position. We want the value live into the
946 // instruction or live out of the block, so ask for the previous
947 // instruction's live-out.
948 const LiveInterval &LI = LIS->getInterval(Reg);
949 VNInfo *VNI;
Andrew Trick2c4f8b72013-08-31 05:17:58 +0000950 MachineBasicBlock::const_iterator I =
951 nextIfDebug(BotRPTracker.getPos(), BB->end());
952 if (I == BB->end())
Andrew Trick2bc74c22013-08-30 04:36:57 +0000953 VNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
954 else {
Matthias Braun88dd0ab2013-10-10 21:28:52 +0000955 LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(I));
Andrew Trick2bc74c22013-08-30 04:36:57 +0000956 VNI = LRQ.valueIn();
957 }
958 // RegisterPressureTracker guarantees that readsReg is true for LiveUses.
959 assert(VNI && "No live value at use.");
960 for (VReg2UseMap::iterator
961 UI = VRegUses.find(Reg); UI != VRegUses.end(); ++UI) {
962 SUnit *SU = UI->SU;
Andrew Trickffdbefb2013-09-06 17:32:39 +0000963 DEBUG(dbgs() << " UpdateRegP: SU(" << SU->NodeNum << ") "
964 << *SU->getInstr());
Andrew Trick2bc74c22013-08-30 04:36:57 +0000965 // If this use comes before the reaching def, it cannot be a last use, so
966 // descrease its pressure change.
967 if (!SU->isScheduled && SU != &ExitSU) {
Matthias Braun88dd0ab2013-10-10 21:28:52 +0000968 LiveQueryResult LRQ
969 = LI.Query(LIS->getInstructionIndex(SU->getInstr()));
Andrew Trick2bc74c22013-08-30 04:36:57 +0000970 if (LRQ.valueIn() == VNI)
971 getPressureDiff(SU).addPressureChange(Reg, true, &MRI);
972 }
973 }
974 }
975}
976
Andrew Trick8823dec2012-03-14 04:00:41 +0000977/// schedule - Called back from MachineScheduler::runOnMachineFunction
Andrew Trick88639922012-04-24 17:56:43 +0000978/// after setting up the current scheduling region. [RegionBegin, RegionEnd)
979/// only includes instructions that have DAG nodes, not scheduling boundaries.
Andrew Trick7a8e1002012-09-11 00:39:15 +0000980///
981/// This is a skeletal driver, with all the functionality pushed into helpers,
982/// so that it can be easilly extended by experimental schedulers. Generally,
983/// implementing MachineSchedStrategy should be sufficient to implement a new
984/// scheduling algorithm. However, if a scheduler further subclasses
Andrew Trickd7f890e2013-12-28 21:56:47 +0000985/// ScheduleDAGMILive then it will want to override this virtual method in order
986/// to update any specialized state.
987void ScheduleDAGMILive::schedule() {
Andrew Trick7a8e1002012-09-11 00:39:15 +0000988 buildDAGWithRegPressure();
989
Andrew Tricka7714a02012-11-12 19:40:10 +0000990 Topo.InitDAGTopologicalSorting();
991
Andrew Tricka2733e92012-09-14 17:22:42 +0000992 postprocessDAG();
993
Andrew Tricke2c3f5c2013-01-25 06:33:57 +0000994 SmallVector<SUnit*, 8> TopRoots, BotRoots;
995 findRootsAndBiasEdges(TopRoots, BotRoots);
996
997 // Initialize the strategy before modifying the DAG.
998 // This may initialize a DFSResult to be used for queue priority.
999 SchedImpl->initialize(this);
1000
Andrew Trick7a8e1002012-09-11 00:39:15 +00001001 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
1002 SUnits[su].dumpAll(this));
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001003 if (ViewMISchedDAGs) viewGraph();
Andrew Trick7a8e1002012-09-11 00:39:15 +00001004
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001005 // Initialize ready queues now that the DAG and priority data are finalized.
1006 initQueues(TopRoots, BotRoots);
Andrew Trick7a8e1002012-09-11 00:39:15 +00001007
Andrew Trickd7f890e2013-12-28 21:56:47 +00001008 if (ShouldTrackPressure) {
1009 assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
1010 TopRPTracker.setPos(CurrentTop);
1011 }
1012
Andrew Trick7a8e1002012-09-11 00:39:15 +00001013 bool IsTopNode = false;
1014 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
Andrew Trick984d98b2012-10-08 18:53:53 +00001015 assert(!SU->isScheduled && "Node already scheduled");
Andrew Trick7a8e1002012-09-11 00:39:15 +00001016 if (!checkSchedLimit())
1017 break;
1018
1019 scheduleMI(SU, IsTopNode);
1020
1021 updateQueues(SU, IsTopNode);
Andrew Trickd7f890e2013-12-28 21:56:47 +00001022
1023 if (DFSResult) {
1024 unsigned SubtreeID = DFSResult->getSubtreeID(SU);
1025 if (!ScheduledTrees.test(SubtreeID)) {
1026 ScheduledTrees.set(SubtreeID);
1027 DFSResult->scheduleTree(SubtreeID);
1028 SchedImpl->scheduleTree(SubtreeID);
1029 }
1030 }
1031
1032 // Notify the scheduling strategy after updating the DAG.
1033 SchedImpl->schedNode(SU, IsTopNode);
Andrew Trick7a8e1002012-09-11 00:39:15 +00001034 }
1035 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
1036
1037 placeDebugValues();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001038
1039 DEBUG({
Andrew Trickcf7e6972012-11-28 03:42:47 +00001040 unsigned BBNum = begin()->getParent()->getNumber();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001041 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
1042 dumpSchedule();
1043 dbgs() << '\n';
1044 });
Andrew Trick7a8e1002012-09-11 00:39:15 +00001045}
1046
1047/// Build the DAG and setup three register pressure trackers.
Andrew Trickd7f890e2013-12-28 21:56:47 +00001048void ScheduleDAGMILive::buildDAGWithRegPressure() {
Andrew Trickb6e74712013-09-04 20:59:59 +00001049 if (!ShouldTrackPressure) {
1050 RPTracker.reset();
1051 RegionCriticalPSets.clear();
1052 buildSchedGraph(AA);
1053 return;
1054 }
1055
Andrew Trick4add42f2012-05-10 21:06:10 +00001056 // Initialize the register pressure tracker used by buildSchedGraph.
Andrew Trick9c17eab2013-07-30 19:59:12 +00001057 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
1058 /*TrackUntiedDefs=*/true);
Andrew Trick88639922012-04-24 17:56:43 +00001059
Andrew Trick4add42f2012-05-10 21:06:10 +00001060 // Account for liveness generate by the region boundary.
1061 if (LiveRegionEnd != RegionEnd)
1062 RPTracker.recede();
1063
1064 // Build the DAG, and compute current register pressure.
Andrew Trick1a831342013-08-30 03:49:48 +00001065 buildSchedGraph(AA, &RPTracker, &SUPressureDiffs);
Andrew Trick02a80da2012-03-08 01:41:12 +00001066
Andrew Trick4add42f2012-05-10 21:06:10 +00001067 // Initialize top/bottom trackers after computing region pressure.
1068 initRegPressure();
Andrew Trick7a8e1002012-09-11 00:39:15 +00001069}
Andrew Trick4add42f2012-05-10 21:06:10 +00001070
Andrew Trickd7f890e2013-12-28 21:56:47 +00001071void ScheduleDAGMILive::computeDFSResult() {
Andrew Trick44f750a2013-01-25 04:01:04 +00001072 if (!DFSResult)
1073 DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize);
1074 DFSResult->clear();
Andrew Trick44f750a2013-01-25 04:01:04 +00001075 ScheduledTrees.clear();
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001076 DFSResult->resize(SUnits.size());
1077 DFSResult->compute(SUnits);
Andrew Trick44f750a2013-01-25 04:01:04 +00001078 ScheduledTrees.resize(DFSResult->getNumSubtrees());
1079}
1080
Andrew Trick483f4192013-08-29 18:04:49 +00001081/// Compute the max cyclic critical path through the DAG. The scheduling DAG
1082/// only provides the critical path for single block loops. To handle loops that
1083/// span blocks, we could use the vreg path latencies provided by
1084/// MachineTraceMetrics instead. However, MachineTraceMetrics is not currently
1085/// available for use in the scheduler.
1086///
1087/// The cyclic path estimation identifies a def-use pair that crosses the back
Andrew Trickef80f502013-08-30 02:02:12 +00001088/// edge and considers the depth and height of the nodes. For example, consider
Andrew Trick483f4192013-08-29 18:04:49 +00001089/// the following instruction sequence where each instruction has unit latency
1090/// and defines an epomymous virtual register:
1091///
1092/// a->b(a,c)->c(b)->d(c)->exit
1093///
1094/// The cyclic critical path is a two cycles: b->c->b
1095/// The acyclic critical path is four cycles: a->b->c->d->exit
1096/// LiveOutHeight = height(c) = len(c->d->exit) = 2
1097/// LiveOutDepth = depth(c) + 1 = len(a->b->c) + 1 = 3
1098/// LiveInHeight = height(b) + 1 = len(b->c->d->exit) + 1 = 4
1099/// LiveInDepth = depth(b) = len(a->b) = 1
1100///
1101/// LiveOutDepth - LiveInDepth = 3 - 1 = 2
1102/// LiveInHeight - LiveOutHeight = 4 - 2 = 2
1103/// CyclicCriticalPath = min(2, 2) = 2
Andrew Trickd7f890e2013-12-28 21:56:47 +00001104///
1105/// This could be relevant to PostRA scheduling, but is currently implemented
1106/// assuming LiveIntervals.
1107unsigned ScheduleDAGMILive::computeCyclicCriticalPath() {
Andrew Trick483f4192013-08-29 18:04:49 +00001108 // This only applies to single block loop.
1109 if (!BB->isSuccessor(BB))
1110 return 0;
1111
1112 unsigned MaxCyclicLatency = 0;
1113 // Visit each live out vreg def to find def/use pairs that cross iterations.
1114 ArrayRef<unsigned> LiveOuts = RPTracker.getPressure().LiveOutRegs;
1115 for (ArrayRef<unsigned>::iterator RI = LiveOuts.begin(), RE = LiveOuts.end();
1116 RI != RE; ++RI) {
1117 unsigned Reg = *RI;
1118 if (!TRI->isVirtualRegister(Reg))
1119 continue;
1120 const LiveInterval &LI = LIS->getInterval(Reg);
1121 const VNInfo *DefVNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
1122 if (!DefVNI)
1123 continue;
1124
1125 MachineInstr *DefMI = LIS->getInstructionFromIndex(DefVNI->def);
1126 const SUnit *DefSU = getSUnit(DefMI);
1127 if (!DefSU)
1128 continue;
1129
1130 unsigned LiveOutHeight = DefSU->getHeight();
1131 unsigned LiveOutDepth = DefSU->getDepth() + DefSU->Latency;
1132 // Visit all local users of the vreg def.
1133 for (VReg2UseMap::iterator
1134 UI = VRegUses.find(Reg); UI != VRegUses.end(); ++UI) {
1135 if (UI->SU == &ExitSU)
1136 continue;
1137
1138 // Only consider uses of the phi.
Matthias Braun88dd0ab2013-10-10 21:28:52 +00001139 LiveQueryResult LRQ =
1140 LI.Query(LIS->getInstructionIndex(UI->SU->getInstr()));
Andrew Trick483f4192013-08-29 18:04:49 +00001141 if (!LRQ.valueIn()->isPHIDef())
1142 continue;
1143
1144 // Assume that a path spanning two iterations is a cycle, which could
1145 // overestimate in strange cases. This allows cyclic latency to be
1146 // estimated as the minimum slack of the vreg's depth or height.
1147 unsigned CyclicLatency = 0;
1148 if (LiveOutDepth > UI->SU->getDepth())
1149 CyclicLatency = LiveOutDepth - UI->SU->getDepth();
1150
1151 unsigned LiveInHeight = UI->SU->getHeight() + DefSU->Latency;
1152 if (LiveInHeight > LiveOutHeight) {
1153 if (LiveInHeight - LiveOutHeight < CyclicLatency)
1154 CyclicLatency = LiveInHeight - LiveOutHeight;
1155 }
1156 else
1157 CyclicLatency = 0;
1158
1159 DEBUG(dbgs() << "Cyclic Path: SU(" << DefSU->NodeNum << ") -> SU("
1160 << UI->SU->NodeNum << ") = " << CyclicLatency << "c\n");
1161 if (CyclicLatency > MaxCyclicLatency)
1162 MaxCyclicLatency = CyclicLatency;
1163 }
1164 }
1165 DEBUG(dbgs() << "Cyclic Critical Path: " << MaxCyclicLatency << "c\n");
1166 return MaxCyclicLatency;
1167}
1168
Andrew Trick7a8e1002012-09-11 00:39:15 +00001169/// Move an instruction and update register pressure.
Andrew Trickd7f890e2013-12-28 21:56:47 +00001170void ScheduleDAGMILive::scheduleMI(SUnit *SU, bool IsTopNode) {
Andrew Trick7a8e1002012-09-11 00:39:15 +00001171 // Move the instruction to its new location in the instruction stream.
1172 MachineInstr *MI = SU->getInstr();
Andrew Trick02a80da2012-03-08 01:41:12 +00001173
Andrew Trick7a8e1002012-09-11 00:39:15 +00001174 if (IsTopNode) {
1175 assert(SU->isTopReady() && "node still has unscheduled dependencies");
1176 if (&*CurrentTop == MI)
1177 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
Andrew Trick8823dec2012-03-14 04:00:41 +00001178 else {
Andrew Trick7a8e1002012-09-11 00:39:15 +00001179 moveInstruction(MI, CurrentTop);
1180 TopRPTracker.setPos(MI);
Andrew Trick8823dec2012-03-14 04:00:41 +00001181 }
Andrew Trickc3ea0052012-04-24 18:04:37 +00001182
Andrew Trickb6e74712013-09-04 20:59:59 +00001183 if (ShouldTrackPressure) {
1184 // Update top scheduled pressure.
1185 TopRPTracker.advance();
1186 assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
Andrew Trickb248b4a2013-09-06 17:32:47 +00001187 updateScheduledPressure(SU, TopRPTracker.getPressure().MaxSetPressure);
Andrew Trickb6e74712013-09-04 20:59:59 +00001188 }
Andrew Trick7a8e1002012-09-11 00:39:15 +00001189 }
1190 else {
1191 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
1192 MachineBasicBlock::iterator priorII =
1193 priorNonDebug(CurrentBottom, CurrentTop);
1194 if (&*priorII == MI)
1195 CurrentBottom = priorII;
1196 else {
1197 if (&*CurrentTop == MI) {
1198 CurrentTop = nextIfDebug(++CurrentTop, priorII);
1199 TopRPTracker.setPos(CurrentTop);
1200 }
1201 moveInstruction(MI, CurrentBottom);
1202 CurrentBottom = MI;
1203 }
Andrew Trickb6e74712013-09-04 20:59:59 +00001204 if (ShouldTrackPressure) {
1205 // Update bottom scheduled pressure.
1206 SmallVector<unsigned, 8> LiveUses;
1207 BotRPTracker.recede(&LiveUses);
1208 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
Andrew Trickb248b4a2013-09-06 17:32:47 +00001209 updateScheduledPressure(SU, BotRPTracker.getPressure().MaxSetPressure);
Andrew Trickb6e74712013-09-04 20:59:59 +00001210 updatePressureDiffs(LiveUses);
Andrew Trickb6e74712013-09-04 20:59:59 +00001211 }
Andrew Trick7a8e1002012-09-11 00:39:15 +00001212 }
1213}
1214
Andrew Trick263280242012-11-12 19:52:20 +00001215//===----------------------------------------------------------------------===//
1216// LoadClusterMutation - DAG post-processing to cluster loads.
1217//===----------------------------------------------------------------------===//
1218
Andrew Tricka7714a02012-11-12 19:40:10 +00001219namespace {
1220/// \brief Post-process the DAG to create cluster edges between neighboring
1221/// loads.
1222class LoadClusterMutation : public ScheduleDAGMutation {
1223 struct LoadInfo {
1224 SUnit *SU;
1225 unsigned BaseReg;
1226 unsigned Offset;
1227 LoadInfo(SUnit *su, unsigned reg, unsigned ofs)
1228 : SU(su), BaseReg(reg), Offset(ofs) {}
Benjamin Kramerb0f74b22014-03-07 21:35:39 +00001229
1230 bool operator<(const LoadInfo &RHS) const {
1231 return std::tie(BaseReg, Offset) < std::tie(RHS.BaseReg, RHS.Offset);
1232 }
Andrew Tricka7714a02012-11-12 19:40:10 +00001233 };
Andrew Tricka7714a02012-11-12 19:40:10 +00001234
1235 const TargetInstrInfo *TII;
1236 const TargetRegisterInfo *TRI;
1237public:
1238 LoadClusterMutation(const TargetInstrInfo *tii,
1239 const TargetRegisterInfo *tri)
1240 : TII(tii), TRI(tri) {}
1241
Craig Topper4584cd52014-03-07 09:26:03 +00001242 void apply(ScheduleDAGMI *DAG) override;
Andrew Tricka7714a02012-11-12 19:40:10 +00001243protected:
1244 void clusterNeighboringLoads(ArrayRef<SUnit*> Loads, ScheduleDAGMI *DAG);
1245};
1246} // anonymous
1247
Andrew Tricka7714a02012-11-12 19:40:10 +00001248void LoadClusterMutation::clusterNeighboringLoads(ArrayRef<SUnit*> Loads,
1249 ScheduleDAGMI *DAG) {
1250 SmallVector<LoadClusterMutation::LoadInfo,32> LoadRecords;
1251 for (unsigned Idx = 0, End = Loads.size(); Idx != End; ++Idx) {
1252 SUnit *SU = Loads[Idx];
1253 unsigned BaseReg;
1254 unsigned Offset;
1255 if (TII->getLdStBaseRegImmOfs(SU->getInstr(), BaseReg, Offset, TRI))
1256 LoadRecords.push_back(LoadInfo(SU, BaseReg, Offset));
1257 }
1258 if (LoadRecords.size() < 2)
1259 return;
Benjamin Kramerb0f74b22014-03-07 21:35:39 +00001260 std::sort(LoadRecords.begin(), LoadRecords.end());
Andrew Tricka7714a02012-11-12 19:40:10 +00001261 unsigned ClusterLength = 1;
1262 for (unsigned Idx = 0, End = LoadRecords.size(); Idx < (End - 1); ++Idx) {
1263 if (LoadRecords[Idx].BaseReg != LoadRecords[Idx+1].BaseReg) {
1264 ClusterLength = 1;
1265 continue;
1266 }
1267
1268 SUnit *SUa = LoadRecords[Idx].SU;
1269 SUnit *SUb = LoadRecords[Idx+1].SU;
Andrew Trickec369d52012-11-12 21:28:10 +00001270 if (TII->shouldClusterLoads(SUa->getInstr(), SUb->getInstr(), ClusterLength)
Andrew Tricka7714a02012-11-12 19:40:10 +00001271 && DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
1272
1273 DEBUG(dbgs() << "Cluster loads SU(" << SUa->NodeNum << ") - SU("
1274 << SUb->NodeNum << ")\n");
1275 // Copy successor edges from SUa to SUb. Interleaving computation
1276 // dependent on SUa can prevent load combining due to register reuse.
1277 // Predecessor edges do not need to be copied from SUb to SUa since nearby
1278 // loads should have effectively the same inputs.
1279 for (SUnit::const_succ_iterator
1280 SI = SUa->Succs.begin(), SE = SUa->Succs.end(); SI != SE; ++SI) {
1281 if (SI->getSUnit() == SUb)
1282 continue;
1283 DEBUG(dbgs() << " Copy Succ SU(" << SI->getSUnit()->NodeNum << ")\n");
1284 DAG->addEdge(SI->getSUnit(), SDep(SUb, SDep::Artificial));
1285 }
1286 ++ClusterLength;
1287 }
1288 else
1289 ClusterLength = 1;
1290 }
1291}
1292
1293/// \brief Callback from DAG postProcessing to create cluster edges for loads.
1294void LoadClusterMutation::apply(ScheduleDAGMI *DAG) {
1295 // Map DAG NodeNum to store chain ID.
1296 DenseMap<unsigned, unsigned> StoreChainIDs;
1297 // Map each store chain to a set of dependent loads.
1298 SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
1299 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
1300 SUnit *SU = &DAG->SUnits[Idx];
1301 if (!SU->getInstr()->mayLoad())
1302 continue;
1303 unsigned ChainPredID = DAG->SUnits.size();
1304 for (SUnit::const_pred_iterator
1305 PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
1306 if (PI->isCtrl()) {
1307 ChainPredID = PI->getSUnit()->NodeNum;
1308 break;
1309 }
1310 }
1311 // Check if this chain-like pred has been seen
1312 // before. ChainPredID==MaxNodeID for loads at the top of the schedule.
1313 unsigned NumChains = StoreChainDependents.size();
1314 std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
1315 StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
1316 if (Result.second)
1317 StoreChainDependents.resize(NumChains + 1);
1318 StoreChainDependents[Result.first->second].push_back(SU);
1319 }
1320 // Iterate over the store chains.
1321 for (unsigned Idx = 0, End = StoreChainDependents.size(); Idx != End; ++Idx)
1322 clusterNeighboringLoads(StoreChainDependents[Idx], DAG);
1323}
1324
Andrew Trick02a80da2012-03-08 01:41:12 +00001325//===----------------------------------------------------------------------===//
Andrew Trick263280242012-11-12 19:52:20 +00001326// MacroFusion - DAG post-processing to encourage fusion of macro ops.
1327//===----------------------------------------------------------------------===//
1328
1329namespace {
1330/// \brief Post-process the DAG to create cluster edges between instructions
1331/// that may be fused by the processor into a single operation.
1332class MacroFusion : public ScheduleDAGMutation {
1333 const TargetInstrInfo *TII;
1334public:
1335 MacroFusion(const TargetInstrInfo *tii): TII(tii) {}
1336
Craig Topper4584cd52014-03-07 09:26:03 +00001337 void apply(ScheduleDAGMI *DAG) override;
Andrew Trick263280242012-11-12 19:52:20 +00001338};
1339} // anonymous
1340
1341/// \brief Callback from DAG postProcessing to create cluster edges to encourage
1342/// fused operations.
1343void MacroFusion::apply(ScheduleDAGMI *DAG) {
1344 // For now, assume targets can only fuse with the branch.
1345 MachineInstr *Branch = DAG->ExitSU.getInstr();
1346 if (!Branch)
1347 return;
1348
1349 for (unsigned Idx = DAG->SUnits.size(); Idx > 0;) {
1350 SUnit *SU = &DAG->SUnits[--Idx];
1351 if (!TII->shouldScheduleAdjacent(SU->getInstr(), Branch))
1352 continue;
1353
1354 // Create a single weak edge from SU to ExitSU. The only effect is to cause
1355 // bottom-up scheduling to heavily prioritize the clustered SU. There is no
1356 // need to copy predecessor edges from ExitSU to SU, since top-down
1357 // scheduling cannot prioritize ExitSU anyway. To defer top-down scheduling
1358 // of SU, we could create an artificial edge from the deepest root, but it
1359 // hasn't been needed yet.
1360 bool Success = DAG->addEdge(&DAG->ExitSU, SDep(SU, SDep::Cluster));
1361 (void)Success;
1362 assert(Success && "No DAG nodes should be reachable from ExitSU");
1363
1364 DEBUG(dbgs() << "Macro Fuse SU(" << SU->NodeNum << ")\n");
1365 break;
1366 }
1367}
1368
1369//===----------------------------------------------------------------------===//
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001370// CopyConstrain - DAG post-processing to encourage copy elimination.
1371//===----------------------------------------------------------------------===//
1372
1373namespace {
1374/// \brief Post-process the DAG to create weak edges from all uses of a copy to
1375/// the one use that defines the copy's source vreg, most likely an induction
1376/// variable increment.
1377class CopyConstrain : public ScheduleDAGMutation {
1378 // Transient state.
1379 SlotIndex RegionBeginIdx;
Andrew Trick2e875172013-04-24 23:19:56 +00001380 // RegionEndIdx is the slot index of the last non-debug instruction in the
1381 // scheduling region. So we may have RegionBeginIdx == RegionEndIdx.
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001382 SlotIndex RegionEndIdx;
1383public:
1384 CopyConstrain(const TargetInstrInfo *, const TargetRegisterInfo *) {}
1385
Craig Topper4584cd52014-03-07 09:26:03 +00001386 void apply(ScheduleDAGMI *DAG) override;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001387
1388protected:
Andrew Trickd7f890e2013-12-28 21:56:47 +00001389 void constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG);
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001390};
1391} // anonymous
1392
1393/// constrainLocalCopy handles two possibilities:
1394/// 1) Local src:
1395/// I0: = dst
1396/// I1: src = ...
1397/// I2: = dst
1398/// I3: dst = src (copy)
1399/// (create pred->succ edges I0->I1, I2->I1)
1400///
1401/// 2) Local copy:
1402/// I0: dst = src (copy)
1403/// I1: = dst
1404/// I2: src = ...
1405/// I3: = dst
1406/// (create pred->succ edges I1->I2, I3->I2)
1407///
1408/// Although the MachineScheduler is currently constrained to single blocks,
1409/// this algorithm should handle extended blocks. An EBB is a set of
1410/// contiguously numbered blocks such that the previous block in the EBB is
1411/// always the single predecessor.
Andrew Trickd7f890e2013-12-28 21:56:47 +00001412void CopyConstrain::constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG) {
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001413 LiveIntervals *LIS = DAG->getLIS();
1414 MachineInstr *Copy = CopySU->getInstr();
1415
1416 // Check for pure vreg copies.
1417 unsigned SrcReg = Copy->getOperand(1).getReg();
1418 if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
1419 return;
1420
1421 unsigned DstReg = Copy->getOperand(0).getReg();
1422 if (!TargetRegisterInfo::isVirtualRegister(DstReg))
1423 return;
1424
1425 // Check if either the dest or source is local. If it's live across a back
1426 // edge, it's not local. Note that if both vregs are live across the back
1427 // edge, we cannot successfully contrain the copy without cyclic scheduling.
1428 unsigned LocalReg = DstReg;
1429 unsigned GlobalReg = SrcReg;
1430 LiveInterval *LocalLI = &LIS->getInterval(LocalReg);
1431 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx)) {
1432 LocalReg = SrcReg;
1433 GlobalReg = DstReg;
1434 LocalLI = &LIS->getInterval(LocalReg);
1435 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx))
1436 return;
1437 }
1438 LiveInterval *GlobalLI = &LIS->getInterval(GlobalReg);
1439
1440 // Find the global segment after the start of the local LI.
1441 LiveInterval::iterator GlobalSegment = GlobalLI->find(LocalLI->beginIndex());
1442 // If GlobalLI does not overlap LocalLI->start, then a copy directly feeds a
1443 // local live range. We could create edges from other global uses to the local
1444 // start, but the coalescer should have already eliminated these cases, so
1445 // don't bother dealing with it.
1446 if (GlobalSegment == GlobalLI->end())
1447 return;
1448
1449 // If GlobalSegment is killed at the LocalLI->start, the call to find()
1450 // returned the next global segment. But if GlobalSegment overlaps with
1451 // LocalLI->start, then advance to the next segement. If a hole in GlobalLI
1452 // exists in LocalLI's vicinity, GlobalSegment will be the end of the hole.
1453 if (GlobalSegment->contains(LocalLI->beginIndex()))
1454 ++GlobalSegment;
1455
1456 if (GlobalSegment == GlobalLI->end())
1457 return;
1458
1459 // Check if GlobalLI contains a hole in the vicinity of LocalLI.
1460 if (GlobalSegment != GlobalLI->begin()) {
1461 // Two address defs have no hole.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001462 if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->end,
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001463 GlobalSegment->start)) {
1464 return;
1465 }
Andrew Trickd9761772013-07-30 19:59:08 +00001466 // If the prior global segment may be defined by the same two-address
1467 // instruction that also defines LocalLI, then can't make a hole here.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001468 if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->start,
Andrew Trickd9761772013-07-30 19:59:08 +00001469 LocalLI->beginIndex())) {
1470 return;
1471 }
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001472 // If GlobalLI has a prior segment, it must be live into the EBB. Otherwise
1473 // it would be a disconnected component in the live range.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001474 assert(std::prev(GlobalSegment)->start < LocalLI->beginIndex() &&
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001475 "Disconnected LRG within the scheduling region.");
1476 }
1477 MachineInstr *GlobalDef = LIS->getInstructionFromIndex(GlobalSegment->start);
1478 if (!GlobalDef)
1479 return;
1480
1481 SUnit *GlobalSU = DAG->getSUnit(GlobalDef);
1482 if (!GlobalSU)
1483 return;
1484
1485 // GlobalDef is the bottom of the GlobalLI hole. Open the hole by
1486 // constraining the uses of the last local def to precede GlobalDef.
1487 SmallVector<SUnit*,8> LocalUses;
1488 const VNInfo *LastLocalVN = LocalLI->getVNInfoBefore(LocalLI->endIndex());
1489 MachineInstr *LastLocalDef = LIS->getInstructionFromIndex(LastLocalVN->def);
1490 SUnit *LastLocalSU = DAG->getSUnit(LastLocalDef);
1491 for (SUnit::const_succ_iterator
1492 I = LastLocalSU->Succs.begin(), E = LastLocalSU->Succs.end();
1493 I != E; ++I) {
1494 if (I->getKind() != SDep::Data || I->getReg() != LocalReg)
1495 continue;
1496 if (I->getSUnit() == GlobalSU)
1497 continue;
1498 if (!DAG->canAddEdge(GlobalSU, I->getSUnit()))
1499 return;
1500 LocalUses.push_back(I->getSUnit());
1501 }
1502 // Open the top of the GlobalLI hole by constraining any earlier global uses
1503 // to precede the start of LocalLI.
1504 SmallVector<SUnit*,8> GlobalUses;
1505 MachineInstr *FirstLocalDef =
1506 LIS->getInstructionFromIndex(LocalLI->beginIndex());
1507 SUnit *FirstLocalSU = DAG->getSUnit(FirstLocalDef);
1508 for (SUnit::const_pred_iterator
1509 I = GlobalSU->Preds.begin(), E = GlobalSU->Preds.end(); I != E; ++I) {
1510 if (I->getKind() != SDep::Anti || I->getReg() != GlobalReg)
1511 continue;
1512 if (I->getSUnit() == FirstLocalSU)
1513 continue;
1514 if (!DAG->canAddEdge(FirstLocalSU, I->getSUnit()))
1515 return;
1516 GlobalUses.push_back(I->getSUnit());
1517 }
1518 DEBUG(dbgs() << "Constraining copy SU(" << CopySU->NodeNum << ")\n");
1519 // Add the weak edges.
1520 for (SmallVectorImpl<SUnit*>::const_iterator
1521 I = LocalUses.begin(), E = LocalUses.end(); I != E; ++I) {
1522 DEBUG(dbgs() << " Local use SU(" << (*I)->NodeNum << ") -> SU("
1523 << GlobalSU->NodeNum << ")\n");
1524 DAG->addEdge(GlobalSU, SDep(*I, SDep::Weak));
1525 }
1526 for (SmallVectorImpl<SUnit*>::const_iterator
1527 I = GlobalUses.begin(), E = GlobalUses.end(); I != E; ++I) {
1528 DEBUG(dbgs() << " Global use SU(" << (*I)->NodeNum << ") -> SU("
1529 << FirstLocalSU->NodeNum << ")\n");
1530 DAG->addEdge(FirstLocalSU, SDep(*I, SDep::Weak));
1531 }
1532}
1533
1534/// \brief Callback from DAG postProcessing to create weak edges to encourage
1535/// copy elimination.
1536void CopyConstrain::apply(ScheduleDAGMI *DAG) {
Andrew Trickd7f890e2013-12-28 21:56:47 +00001537 assert(DAG->hasVRegLiveness() && "Expect VRegs with LiveIntervals");
1538
Andrew Trick2e875172013-04-24 23:19:56 +00001539 MachineBasicBlock::iterator FirstPos = nextIfDebug(DAG->begin(), DAG->end());
1540 if (FirstPos == DAG->end())
1541 return;
1542 RegionBeginIdx = DAG->getLIS()->getInstructionIndex(&*FirstPos);
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001543 RegionEndIdx = DAG->getLIS()->getInstructionIndex(
1544 &*priorNonDebug(DAG->end(), DAG->begin()));
1545
1546 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
1547 SUnit *SU = &DAG->SUnits[Idx];
1548 if (!SU->getInstr()->isCopy())
1549 continue;
1550
Andrew Trickd7f890e2013-12-28 21:56:47 +00001551 constrainLocalCopy(SU, static_cast<ScheduleDAGMILive*>(DAG));
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001552 }
1553}
1554
1555//===----------------------------------------------------------------------===//
Andrew Trickfc127d12013-12-07 05:59:44 +00001556// MachineSchedStrategy helpers used by GenericScheduler, GenericPostScheduler
1557// and possibly other custom schedulers.
Andrew Trickd14d7c22013-12-28 21:56:57 +00001558//===----------------------------------------------------------------------===//
Andrew Tricke1c034f2012-01-17 06:55:03 +00001559
Andrew Trick5a22df42013-12-05 17:56:02 +00001560static const unsigned InvalidCycle = ~0U;
1561
Andrew Trickfc127d12013-12-07 05:59:44 +00001562SchedBoundary::~SchedBoundary() { delete HazardRec; }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001563
Andrew Trickfc127d12013-12-07 05:59:44 +00001564void SchedBoundary::reset() {
1565 // A new HazardRec is created for each DAG and owned by SchedBoundary.
1566 // Destroying and reconstructing it is very expensive though. So keep
1567 // invalid, placeholder HazardRecs.
1568 if (HazardRec && HazardRec->isEnabled()) {
1569 delete HazardRec;
Craig Topperc0196b12014-04-14 00:51:57 +00001570 HazardRec = nullptr;
Andrew Trickfc127d12013-12-07 05:59:44 +00001571 }
1572 Available.clear();
1573 Pending.clear();
1574 CheckPending = false;
1575 NextSUs.clear();
1576 CurrCycle = 0;
1577 CurrMOps = 0;
1578 MinReadyCycle = UINT_MAX;
1579 ExpectedLatency = 0;
1580 DependentLatency = 0;
1581 RetiredMOps = 0;
1582 MaxExecutedResCount = 0;
1583 ZoneCritResIdx = 0;
1584 IsResourceLimited = false;
1585 ReservedCycles.clear();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001586#ifndef NDEBUG
Andrew Trickd14d7c22013-12-28 21:56:57 +00001587 // Track the maximum number of stall cycles that could arise either from the
1588 // latency of a DAG edge or the number of cycles that a processor resource is
1589 // reserved (SchedBoundary::ReservedCycles).
Andrew Trick7f1ebbe2014-06-07 01:48:43 +00001590 MaxObservedStall = 0;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001591#endif
Andrew Trickfc127d12013-12-07 05:59:44 +00001592 // Reserve a zero-count for invalid CritResIdx.
1593 ExecutedResCounts.resize(1);
1594 assert(!ExecutedResCounts[0] && "nonzero count for bad resource");
1595}
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001596
Andrew Trickfc127d12013-12-07 05:59:44 +00001597void SchedRemainder::
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001598init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
1599 reset();
1600 if (!SchedModel->hasInstrSchedModel())
1601 return;
1602 RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
1603 for (std::vector<SUnit>::iterator
1604 I = DAG->SUnits.begin(), E = DAG->SUnits.end(); I != E; ++I) {
1605 const MCSchedClassDesc *SC = DAG->getSchedClass(&*I);
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001606 RemIssueCount += SchedModel->getNumMicroOps(I->getInstr(), SC)
1607 * SchedModel->getMicroOpFactor();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001608 for (TargetSchedModel::ProcResIter
1609 PI = SchedModel->getWriteProcResBegin(SC),
1610 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1611 unsigned PIdx = PI->ProcResourceIdx;
1612 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1613 RemainingCounts[PIdx] += (Factor * PI->Cycles);
1614 }
1615 }
1616}
1617
Andrew Trickfc127d12013-12-07 05:59:44 +00001618void SchedBoundary::
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001619init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
1620 reset();
1621 DAG = dag;
1622 SchedModel = smodel;
1623 Rem = rem;
Andrew Trick5a22df42013-12-05 17:56:02 +00001624 if (SchedModel->hasInstrSchedModel()) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001625 ExecutedResCounts.resize(SchedModel->getNumProcResourceKinds());
Andrew Trick5a22df42013-12-05 17:56:02 +00001626 ReservedCycles.resize(SchedModel->getNumProcResourceKinds(), InvalidCycle);
1627 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001628}
1629
Andrew Trick880e5732013-12-05 17:55:58 +00001630/// Compute the stall cycles based on this SUnit's ready time. Heuristics treat
1631/// these "soft stalls" differently than the hard stall cycles based on CPU
1632/// resources and computed by checkHazard(). A fully in-order model
1633/// (MicroOpBufferSize==0) will not make use of this since instructions are not
1634/// available for scheduling until they are ready. However, a weaker in-order
1635/// model may use this for heuristics. For example, if a processor has in-order
1636/// behavior when reading certain resources, this may come into play.
Andrew Trickfc127d12013-12-07 05:59:44 +00001637unsigned SchedBoundary::getLatencyStallCycles(SUnit *SU) {
Andrew Trick880e5732013-12-05 17:55:58 +00001638 if (!SU->isUnbuffered)
1639 return 0;
1640
1641 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
1642 if (ReadyCycle > CurrCycle)
1643 return ReadyCycle - CurrCycle;
1644 return 0;
1645}
1646
Andrew Trick5a22df42013-12-05 17:56:02 +00001647/// Compute the next cycle at which the given processor resource can be
1648/// scheduled.
Andrew Trickfc127d12013-12-07 05:59:44 +00001649unsigned SchedBoundary::
Andrew Trick5a22df42013-12-05 17:56:02 +00001650getNextResourceCycle(unsigned PIdx, unsigned Cycles) {
1651 unsigned NextUnreserved = ReservedCycles[PIdx];
1652 // If this resource has never been used, always return cycle zero.
1653 if (NextUnreserved == InvalidCycle)
1654 return 0;
1655 // For bottom-up scheduling add the cycles needed for the current operation.
1656 if (!isTop())
1657 NextUnreserved += Cycles;
1658 return NextUnreserved;
1659}
1660
Andrew Trick8c9e6722012-06-29 03:23:24 +00001661/// Does this SU have a hazard within the current instruction group.
1662///
1663/// The scheduler supports two modes of hazard recognition. The first is the
1664/// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
1665/// supports highly complicated in-order reservation tables
1666/// (ScoreboardHazardRecognizer) and arbitraty target-specific logic.
1667///
1668/// The second is a streamlined mechanism that checks for hazards based on
1669/// simple counters that the scheduler itself maintains. It explicitly checks
1670/// for instruction dispatch limitations, including the number of micro-ops that
1671/// can dispatch per cycle.
1672///
1673/// TODO: Also check whether the SU must start a new group.
Andrew Trickfc127d12013-12-07 05:59:44 +00001674bool SchedBoundary::checkHazard(SUnit *SU) {
Andrew Trickd14d7c22013-12-28 21:56:57 +00001675 if (HazardRec->isEnabled()
1676 && HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard) {
1677 return true;
1678 }
Andrew Trickdd79f0f2012-10-10 05:43:09 +00001679 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
Andrew Tricke2ff5752013-06-15 04:49:49 +00001680 if ((CurrMOps > 0) && (CurrMOps + uops > SchedModel->getIssueWidth())) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001681 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") uops="
1682 << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
Andrew Trick8c9e6722012-06-29 03:23:24 +00001683 return true;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001684 }
Andrew Trick5a22df42013-12-05 17:56:02 +00001685 if (SchedModel->hasInstrSchedModel() && SU->hasReservedResource) {
1686 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1687 for (TargetSchedModel::ProcResIter
1688 PI = SchedModel->getWriteProcResBegin(SC),
1689 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1690 if (getNextResourceCycle(PI->ProcResourceIdx, PI->Cycles) > CurrCycle)
1691 return true;
1692 }
1693 }
Andrew Trick8c9e6722012-06-29 03:23:24 +00001694 return false;
1695}
1696
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001697// Find the unscheduled node in ReadySUs with the highest latency.
Andrew Trickfc127d12013-12-07 05:59:44 +00001698unsigned SchedBoundary::
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001699findMaxLatency(ArrayRef<SUnit*> ReadySUs) {
Craig Topperc0196b12014-04-14 00:51:57 +00001700 SUnit *LateSU = nullptr;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001701 unsigned RemLatency = 0;
1702 for (ArrayRef<SUnit*>::iterator I = ReadySUs.begin(), E = ReadySUs.end();
Andrew Trickd6d5ad32012-12-18 20:52:56 +00001703 I != E; ++I) {
1704 unsigned L = getUnscheduledLatency(*I);
Andrew Trickf5b8ef22013-06-15 04:49:44 +00001705 if (L > RemLatency) {
Andrew Trickd6d5ad32012-12-18 20:52:56 +00001706 RemLatency = L;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001707 LateSU = *I;
Andrew Trickf5b8ef22013-06-15 04:49:44 +00001708 }
Andrew Trickd6d5ad32012-12-18 20:52:56 +00001709 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001710 if (LateSU) {
1711 DEBUG(dbgs() << Available.getName() << " RemLatency SU("
1712 << LateSU->NodeNum << ") " << RemLatency << "c\n");
Andrew Trickd6d5ad32012-12-18 20:52:56 +00001713 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001714 return RemLatency;
1715}
Andrew Trickf5b8ef22013-06-15 04:49:44 +00001716
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001717// Count resources in this zone and the remaining unscheduled
1718// instruction. Return the max count, scaled. Set OtherCritIdx to the critical
1719// resource index, or zero if the zone is issue limited.
Andrew Trickfc127d12013-12-07 05:59:44 +00001720unsigned SchedBoundary::
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001721getOtherResourceCount(unsigned &OtherCritIdx) {
Alexey Samsonov64c391d2013-07-19 08:55:18 +00001722 OtherCritIdx = 0;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001723 if (!SchedModel->hasInstrSchedModel())
1724 return 0;
1725
1726 unsigned OtherCritCount = Rem->RemIssueCount
1727 + (RetiredMOps * SchedModel->getMicroOpFactor());
1728 DEBUG(dbgs() << " " << Available.getName() << " + Remain MOps: "
1729 << OtherCritCount / SchedModel->getMicroOpFactor() << '\n');
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001730 for (unsigned PIdx = 1, PEnd = SchedModel->getNumProcResourceKinds();
1731 PIdx != PEnd; ++PIdx) {
1732 unsigned OtherCount = getResourceCount(PIdx) + Rem->RemainingCounts[PIdx];
1733 if (OtherCount > OtherCritCount) {
1734 OtherCritCount = OtherCount;
1735 OtherCritIdx = PIdx;
1736 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001737 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001738 if (OtherCritIdx) {
1739 DEBUG(dbgs() << " " << Available.getName() << " + Remain CritRes: "
1740 << OtherCritCount / SchedModel->getResourceFactor(OtherCritIdx)
Andrew Trickfc127d12013-12-07 05:59:44 +00001741 << " " << SchedModel->getResourceName(OtherCritIdx) << "\n");
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001742 }
1743 return OtherCritCount;
1744}
1745
Andrew Trickfc127d12013-12-07 05:59:44 +00001746void SchedBoundary::releaseNode(SUnit *SU, unsigned ReadyCycle) {
Andrew Trick7f1ebbe2014-06-07 01:48:43 +00001747 assert(SU->getInstr() && "Scheduled SUnit must have instr");
1748
1749#ifndef NDEBUG
1750 MaxObservedStall = std::max(ReadyCycle - CurrCycle, MaxObservedStall);
1751#endif
1752
Andrew Trick61f1a272012-05-24 22:11:09 +00001753 if (ReadyCycle < MinReadyCycle)
1754 MinReadyCycle = ReadyCycle;
1755
1756 // Check for interlocks first. For the purpose of other heuristics, an
1757 // instruction that cannot issue appears as if it's not in the ReadyQueue.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001758 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
1759 if ((!IsBuffered && ReadyCycle > CurrCycle) || checkHazard(SU))
Andrew Trick61f1a272012-05-24 22:11:09 +00001760 Pending.push(SU);
1761 else
1762 Available.push(SU);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001763
1764 // Record this node as an immediate dependent of the scheduled node.
1765 NextSUs.insert(SU);
Andrew Trick61f1a272012-05-24 22:11:09 +00001766}
1767
Andrew Trickfc127d12013-12-07 05:59:44 +00001768void SchedBoundary::releaseTopNode(SUnit *SU) {
1769 if (SU->isScheduled)
1770 return;
1771
Andrew Trickfc127d12013-12-07 05:59:44 +00001772 releaseNode(SU, SU->TopReadyCycle);
1773}
1774
1775void SchedBoundary::releaseBottomNode(SUnit *SU) {
1776 if (SU->isScheduled)
1777 return;
1778
Andrew Trickfc127d12013-12-07 05:59:44 +00001779 releaseNode(SU, SU->BotReadyCycle);
1780}
1781
Andrew Trick61f1a272012-05-24 22:11:09 +00001782/// Move the boundary of scheduled code by one cycle.
Andrew Trickfc127d12013-12-07 05:59:44 +00001783void SchedBoundary::bumpCycle(unsigned NextCycle) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001784 if (SchedModel->getMicroOpBufferSize() == 0) {
1785 assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
1786 if (MinReadyCycle > NextCycle)
1787 NextCycle = MinReadyCycle;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001788 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001789 // Update the current micro-ops, which will issue in the next cycle.
1790 unsigned DecMOps = SchedModel->getIssueWidth() * (NextCycle - CurrCycle);
1791 CurrMOps = (CurrMOps <= DecMOps) ? 0 : CurrMOps - DecMOps;
1792
1793 // Decrement DependentLatency based on the next cycle.
Andrew Trickf5b8ef22013-06-15 04:49:44 +00001794 if ((NextCycle - CurrCycle) > DependentLatency)
1795 DependentLatency = 0;
1796 else
1797 DependentLatency -= (NextCycle - CurrCycle);
Andrew Trick61f1a272012-05-24 22:11:09 +00001798
1799 if (!HazardRec->isEnabled()) {
Andrew Trick45446062012-06-05 21:11:27 +00001800 // Bypass HazardRec virtual calls.
Andrew Trick61f1a272012-05-24 22:11:09 +00001801 CurrCycle = NextCycle;
1802 }
1803 else {
Andrew Trick45446062012-06-05 21:11:27 +00001804 // Bypass getHazardType calls in case of long latency.
Andrew Trick61f1a272012-05-24 22:11:09 +00001805 for (; CurrCycle != NextCycle; ++CurrCycle) {
1806 if (isTop())
1807 HazardRec->AdvanceCycle();
1808 else
1809 HazardRec->RecedeCycle();
1810 }
1811 }
1812 CheckPending = true;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001813 unsigned LFactor = SchedModel->getLatencyFactor();
1814 IsResourceLimited =
1815 (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
1816 > (int)LFactor;
Andrew Trick61f1a272012-05-24 22:11:09 +00001817
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001818 DEBUG(dbgs() << "Cycle: " << CurrCycle << ' ' << Available.getName() << '\n');
1819}
1820
Andrew Trickfc127d12013-12-07 05:59:44 +00001821void SchedBoundary::incExecutedResources(unsigned PIdx, unsigned Count) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001822 ExecutedResCounts[PIdx] += Count;
1823 if (ExecutedResCounts[PIdx] > MaxExecutedResCount)
1824 MaxExecutedResCount = ExecutedResCounts[PIdx];
Andrew Trick61f1a272012-05-24 22:11:09 +00001825}
1826
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001827/// Add the given processor resource to this scheduled zone.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001828///
1829/// \param Cycles indicates the number of consecutive (non-pipelined) cycles
1830/// during which this resource is consumed.
1831///
1832/// \return the next cycle at which the instruction may execute without
1833/// oversubscribing resources.
Andrew Trickfc127d12013-12-07 05:59:44 +00001834unsigned SchedBoundary::
Andrew Trick5a22df42013-12-05 17:56:02 +00001835countResource(unsigned PIdx, unsigned Cycles, unsigned NextCycle) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001836 unsigned Factor = SchedModel->getResourceFactor(PIdx);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001837 unsigned Count = Factor * Cycles;
Andrew Trickfc127d12013-12-07 05:59:44 +00001838 DEBUG(dbgs() << " " << SchedModel->getResourceName(PIdx)
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001839 << " +" << Cycles << "x" << Factor << "u\n");
1840
1841 // Update Executed resources counts.
1842 incExecutedResources(PIdx, Count);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001843 assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
1844 Rem->RemainingCounts[PIdx] -= Count;
1845
Andrew Trickb13ef172013-07-19 00:20:07 +00001846 // Check if this resource exceeds the current critical resource. If so, it
1847 // becomes the critical resource.
1848 if (ZoneCritResIdx != PIdx && (getResourceCount(PIdx) > getCriticalCount())) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001849 ZoneCritResIdx = PIdx;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001850 DEBUG(dbgs() << " *** Critical resource "
Andrew Trickfc127d12013-12-07 05:59:44 +00001851 << SchedModel->getResourceName(PIdx) << ": "
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001852 << getResourceCount(PIdx) / SchedModel->getLatencyFactor() << "c\n");
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001853 }
Andrew Trick5a22df42013-12-05 17:56:02 +00001854 // For reserved resources, record the highest cycle using the resource.
1855 unsigned NextAvailable = getNextResourceCycle(PIdx, Cycles);
1856 if (NextAvailable > CurrCycle) {
1857 DEBUG(dbgs() << " Resource conflict: "
1858 << SchedModel->getProcResource(PIdx)->Name << " reserved until @"
1859 << NextAvailable << "\n");
1860 }
1861 return NextAvailable;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001862}
1863
Andrew Trick45446062012-06-05 21:11:27 +00001864/// Move the boundary of scheduled code by one SUnit.
Andrew Trickfc127d12013-12-07 05:59:44 +00001865void SchedBoundary::bumpNode(SUnit *SU) {
Andrew Trick45446062012-06-05 21:11:27 +00001866 // Update the reservation table.
1867 if (HazardRec->isEnabled()) {
1868 if (!isTop() && SU->isCall) {
1869 // Calls are scheduled with their preceding instructions. For bottom-up
1870 // scheduling, clear the pipeline state before emitting.
1871 HazardRec->Reset();
1872 }
1873 HazardRec->EmitInstruction(SU);
1874 }
Andrew Trick5a22df42013-12-05 17:56:02 +00001875 // checkHazard should prevent scheduling multiple instructions per cycle that
1876 // exceed the issue width.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001877 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1878 unsigned IncMOps = SchedModel->getNumMicroOps(SU->getInstr());
Daniel Jasper0d92abd2013-12-06 08:58:22 +00001879 assert(
1880 (CurrMOps == 0 || (CurrMOps + IncMOps) <= SchedModel->getIssueWidth()) &&
Andrew Trickf7760a22013-12-06 17:19:20 +00001881 "Cannot schedule this instruction's MicroOps in the current cycle.");
Andrew Trick5a22df42013-12-05 17:56:02 +00001882
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001883 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
1884 DEBUG(dbgs() << " Ready @" << ReadyCycle << "c\n");
1885
Andrew Trick5a22df42013-12-05 17:56:02 +00001886 unsigned NextCycle = CurrCycle;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001887 switch (SchedModel->getMicroOpBufferSize()) {
1888 case 0:
1889 assert(ReadyCycle <= CurrCycle && "Broken PendingQueue");
1890 break;
1891 case 1:
1892 if (ReadyCycle > NextCycle) {
1893 NextCycle = ReadyCycle;
1894 DEBUG(dbgs() << " *** Stall until: " << ReadyCycle << "\n");
1895 }
1896 break;
1897 default:
1898 // We don't currently model the OOO reorder buffer, so consider all
Andrew Trick880e5732013-12-05 17:55:58 +00001899 // scheduled MOps to be "retired". We do loosely model in-order resource
1900 // latency. If this instruction uses an in-order resource, account for any
1901 // likely stall cycles.
1902 if (SU->isUnbuffered && ReadyCycle > NextCycle)
1903 NextCycle = ReadyCycle;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001904 break;
1905 }
1906 RetiredMOps += IncMOps;
1907
1908 // Update resource counts and critical resource.
1909 if (SchedModel->hasInstrSchedModel()) {
1910 unsigned DecRemIssue = IncMOps * SchedModel->getMicroOpFactor();
1911 assert(Rem->RemIssueCount >= DecRemIssue && "MOps double counted");
1912 Rem->RemIssueCount -= DecRemIssue;
1913 if (ZoneCritResIdx) {
1914 // Scale scheduled micro-ops for comparing with the critical resource.
1915 unsigned ScaledMOps =
1916 RetiredMOps * SchedModel->getMicroOpFactor();
1917
1918 // If scaled micro-ops are now more than the previous critical resource by
1919 // a full cycle, then micro-ops issue becomes critical.
1920 if ((int)(ScaledMOps - getResourceCount(ZoneCritResIdx))
1921 >= (int)SchedModel->getLatencyFactor()) {
1922 ZoneCritResIdx = 0;
1923 DEBUG(dbgs() << " *** Critical resource NumMicroOps: "
1924 << ScaledMOps / SchedModel->getLatencyFactor() << "c\n");
1925 }
1926 }
1927 for (TargetSchedModel::ProcResIter
1928 PI = SchedModel->getWriteProcResBegin(SC),
1929 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1930 unsigned RCycle =
Andrew Trick5a22df42013-12-05 17:56:02 +00001931 countResource(PI->ProcResourceIdx, PI->Cycles, NextCycle);
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001932 if (RCycle > NextCycle)
1933 NextCycle = RCycle;
1934 }
Andrew Trick5a22df42013-12-05 17:56:02 +00001935 if (SU->hasReservedResource) {
1936 // For reserved resources, record the highest cycle using the resource.
1937 // For top-down scheduling, this is the cycle in which we schedule this
1938 // instruction plus the number of cycles the operations reserves the
1939 // resource. For bottom-up is it simply the instruction's cycle.
1940 for (TargetSchedModel::ProcResIter
1941 PI = SchedModel->getWriteProcResBegin(SC),
1942 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1943 unsigned PIdx = PI->ProcResourceIdx;
Andrew Trickd14d7c22013-12-28 21:56:57 +00001944 if (SchedModel->getProcResource(PIdx)->BufferSize == 0) {
Andrew Trick5a22df42013-12-05 17:56:02 +00001945 ReservedCycles[PIdx] = isTop() ? NextCycle + PI->Cycles : NextCycle;
Andrew Trickd14d7c22013-12-28 21:56:57 +00001946#ifndef NDEBUG
Andrew Trick7f1ebbe2014-06-07 01:48:43 +00001947 MaxObservedStall = std::max(PI->Cycles, MaxObservedStall);
Andrew Trickd14d7c22013-12-28 21:56:57 +00001948#endif
1949 }
Andrew Trick5a22df42013-12-05 17:56:02 +00001950 }
1951 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001952 }
1953 // Update ExpectedLatency and DependentLatency.
1954 unsigned &TopLatency = isTop() ? ExpectedLatency : DependentLatency;
1955 unsigned &BotLatency = isTop() ? DependentLatency : ExpectedLatency;
1956 if (SU->getDepth() > TopLatency) {
1957 TopLatency = SU->getDepth();
1958 DEBUG(dbgs() << " " << Available.getName()
1959 << " TopLatency SU(" << SU->NodeNum << ") " << TopLatency << "c\n");
1960 }
1961 if (SU->getHeight() > BotLatency) {
1962 BotLatency = SU->getHeight();
1963 DEBUG(dbgs() << " " << Available.getName()
1964 << " BotLatency SU(" << SU->NodeNum << ") " << BotLatency << "c\n");
1965 }
1966 // If we stall for any reason, bump the cycle.
1967 if (NextCycle > CurrCycle) {
1968 bumpCycle(NextCycle);
1969 }
1970 else {
1971 // After updating ZoneCritResIdx and ExpectedLatency, check if we're
Alp Tokercb402912014-01-24 17:20:08 +00001972 // resource limited. If a stall occurred, bumpCycle does this.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001973 unsigned LFactor = SchedModel->getLatencyFactor();
1974 IsResourceLimited =
1975 (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
1976 > (int)LFactor;
1977 }
Andrew Trick5a22df42013-12-05 17:56:02 +00001978 // Update CurrMOps after calling bumpCycle to handle stalls, since bumpCycle
1979 // resets CurrMOps. Loop to handle instructions with more MOps than issue in
1980 // one cycle. Since we commonly reach the max MOps here, opportunistically
1981 // bump the cycle to avoid uselessly checking everything in the readyQ.
1982 CurrMOps += IncMOps;
1983 while (CurrMOps >= SchedModel->getIssueWidth()) {
Andrew Trick5a22df42013-12-05 17:56:02 +00001984 DEBUG(dbgs() << " *** Max MOps " << CurrMOps
1985 << " at cycle " << CurrCycle << '\n');
Andrew Trickd14d7c22013-12-28 21:56:57 +00001986 bumpCycle(++NextCycle);
Andrew Trick5a22df42013-12-05 17:56:02 +00001987 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001988 DEBUG(dumpScheduledState());
Andrew Trick45446062012-06-05 21:11:27 +00001989}
1990
Andrew Trick61f1a272012-05-24 22:11:09 +00001991/// Release pending ready nodes in to the available queue. This makes them
1992/// visible to heuristics.
Andrew Trickfc127d12013-12-07 05:59:44 +00001993void SchedBoundary::releasePending() {
Andrew Trick61f1a272012-05-24 22:11:09 +00001994 // If the available queue is empty, it is safe to reset MinReadyCycle.
1995 if (Available.empty())
1996 MinReadyCycle = UINT_MAX;
1997
1998 // Check to see if any of the pending instructions are ready to issue. If
1999 // so, add them to the available queue.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002000 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
Andrew Trick61f1a272012-05-24 22:11:09 +00002001 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
2002 SUnit *SU = *(Pending.begin()+i);
Andrew Trick45446062012-06-05 21:11:27 +00002003 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
Andrew Trick61f1a272012-05-24 22:11:09 +00002004
2005 if (ReadyCycle < MinReadyCycle)
2006 MinReadyCycle = ReadyCycle;
2007
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002008 if (!IsBuffered && ReadyCycle > CurrCycle)
Andrew Trick61f1a272012-05-24 22:11:09 +00002009 continue;
2010
Andrew Trick8c9e6722012-06-29 03:23:24 +00002011 if (checkHazard(SU))
Andrew Trick61f1a272012-05-24 22:11:09 +00002012 continue;
2013
2014 Available.push(SU);
2015 Pending.remove(Pending.begin()+i);
2016 --i; --e;
2017 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002018 DEBUG(if (!Pending.empty()) Pending.dump());
Andrew Trick61f1a272012-05-24 22:11:09 +00002019 CheckPending = false;
2020}
2021
2022/// Remove SU from the ready set for this boundary.
Andrew Trickfc127d12013-12-07 05:59:44 +00002023void SchedBoundary::removeReady(SUnit *SU) {
Andrew Trick61f1a272012-05-24 22:11:09 +00002024 if (Available.isInQueue(SU))
2025 Available.remove(Available.find(SU));
2026 else {
2027 assert(Pending.isInQueue(SU) && "bad ready count");
2028 Pending.remove(Pending.find(SU));
2029 }
2030}
2031
2032/// If this queue only has one ready candidate, return it. As a side effect,
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002033/// defer any nodes that now hit a hazard, and advance the cycle until at least
2034/// one node is ready. If multiple instructions are ready, return NULL.
Andrew Trickfc127d12013-12-07 05:59:44 +00002035SUnit *SchedBoundary::pickOnlyChoice() {
Andrew Trick61f1a272012-05-24 22:11:09 +00002036 if (CheckPending)
2037 releasePending();
2038
Andrew Tricke2ff5752013-06-15 04:49:49 +00002039 if (CurrMOps > 0) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002040 // Defer any ready instrs that now have a hazard.
2041 for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
2042 if (checkHazard(*I)) {
2043 Pending.push(*I);
2044 I = Available.remove(I);
2045 continue;
2046 }
2047 ++I;
2048 }
2049 }
Andrew Trick61f1a272012-05-24 22:11:09 +00002050 for (unsigned i = 0; Available.empty(); ++i) {
Andrew Trick7f1ebbe2014-06-07 01:48:43 +00002051 assert(i <= (HazardRec->getMaxLookAhead() + MaxObservedStall) &&
Andrew Trick45446062012-06-05 21:11:27 +00002052 "permanent hazard"); (void)i;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002053 bumpCycle(CurrCycle + 1);
Andrew Trick61f1a272012-05-24 22:11:09 +00002054 releasePending();
2055 }
2056 if (Available.size() == 1)
2057 return *Available.begin();
Craig Topperc0196b12014-04-14 00:51:57 +00002058 return nullptr;
Andrew Trick61f1a272012-05-24 22:11:09 +00002059}
2060
Andrew Trick8e8415f2013-06-15 05:46:47 +00002061#ifndef NDEBUG
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002062// This is useful information to dump after bumpNode.
2063// Note that the Queue contents are more useful before pickNodeFromQueue.
Andrew Trickfc127d12013-12-07 05:59:44 +00002064void SchedBoundary::dumpScheduledState() {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002065 unsigned ResFactor;
2066 unsigned ResCount;
2067 if (ZoneCritResIdx) {
2068 ResFactor = SchedModel->getResourceFactor(ZoneCritResIdx);
2069 ResCount = getResourceCount(ZoneCritResIdx);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002070 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002071 else {
2072 ResFactor = SchedModel->getMicroOpFactor();
2073 ResCount = RetiredMOps * SchedModel->getMicroOpFactor();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002074 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002075 unsigned LFactor = SchedModel->getLatencyFactor();
2076 dbgs() << Available.getName() << " @" << CurrCycle << "c\n"
2077 << " Retired: " << RetiredMOps;
2078 dbgs() << "\n Executed: " << getExecutedCount() / LFactor << "c";
2079 dbgs() << "\n Critical: " << ResCount / LFactor << "c, "
Andrew Trickfc127d12013-12-07 05:59:44 +00002080 << ResCount / ResFactor << " "
2081 << SchedModel->getResourceName(ZoneCritResIdx)
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002082 << "\n ExpectedLatency: " << ExpectedLatency << "c\n"
2083 << (IsResourceLimited ? " - Resource" : " - Latency")
2084 << " limited.\n";
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002085}
Andrew Trick8e8415f2013-06-15 05:46:47 +00002086#endif
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002087
Andrew Trickfc127d12013-12-07 05:59:44 +00002088//===----------------------------------------------------------------------===//
Andrew Trickd14d7c22013-12-28 21:56:57 +00002089// GenericScheduler - Generic implementation of MachineSchedStrategy.
Andrew Trickfc127d12013-12-07 05:59:44 +00002090//===----------------------------------------------------------------------===//
2091
Andrew Trickd14d7c22013-12-28 21:56:57 +00002092void GenericSchedulerBase::SchedCandidate::
2093initResourceDelta(const ScheduleDAGMI *DAG,
2094 const TargetSchedModel *SchedModel) {
2095 if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
2096 return;
2097
2098 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
2099 for (TargetSchedModel::ProcResIter
2100 PI = SchedModel->getWriteProcResBegin(SC),
2101 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2102 if (PI->ProcResourceIdx == Policy.ReduceResIdx)
2103 ResDelta.CritResources += PI->Cycles;
2104 if (PI->ProcResourceIdx == Policy.DemandResIdx)
2105 ResDelta.DemandedResources += PI->Cycles;
2106 }
2107}
2108
2109/// Set the CandPolicy given a scheduling zone given the current resources and
2110/// latencies inside and outside the zone.
2111void GenericSchedulerBase::setPolicy(CandPolicy &Policy,
2112 bool IsPostRA,
2113 SchedBoundary &CurrZone,
2114 SchedBoundary *OtherZone) {
2115 // Apply preemptive heuristics based on the the total latency and resources
2116 // inside and outside this zone. Potential stalls should be considered before
2117 // following this policy.
2118
2119 // Compute remaining latency. We need this both to determine whether the
2120 // overall schedule has become latency-limited and whether the instructions
2121 // outside this zone are resource or latency limited.
2122 //
2123 // The "dependent" latency is updated incrementally during scheduling as the
2124 // max height/depth of scheduled nodes minus the cycles since it was
2125 // scheduled:
2126 // DLat = max (N.depth - (CurrCycle - N.ReadyCycle) for N in Zone
2127 //
2128 // The "independent" latency is the max ready queue depth:
2129 // ILat = max N.depth for N in Available|Pending
2130 //
2131 // RemainingLatency is the greater of independent and dependent latency.
2132 unsigned RemLatency = CurrZone.getDependentLatency();
2133 RemLatency = std::max(RemLatency,
2134 CurrZone.findMaxLatency(CurrZone.Available.elements()));
2135 RemLatency = std::max(RemLatency,
2136 CurrZone.findMaxLatency(CurrZone.Pending.elements()));
2137
2138 // Compute the critical resource outside the zone.
Andrew Trick7afe4812013-12-28 22:25:57 +00002139 unsigned OtherCritIdx = 0;
Andrew Trickd14d7c22013-12-28 21:56:57 +00002140 unsigned OtherCount =
2141 OtherZone ? OtherZone->getOtherResourceCount(OtherCritIdx) : 0;
2142
2143 bool OtherResLimited = false;
2144 if (SchedModel->hasInstrSchedModel()) {
2145 unsigned LFactor = SchedModel->getLatencyFactor();
2146 OtherResLimited = (int)(OtherCount - (RemLatency * LFactor)) > (int)LFactor;
2147 }
2148 // Schedule aggressively for latency in PostRA mode. We don't check for
2149 // acyclic latency during PostRA, and highly out-of-order processors will
2150 // skip PostRA scheduling.
2151 if (!OtherResLimited) {
2152 if (IsPostRA || (RemLatency + CurrZone.getCurrCycle() > Rem.CriticalPath)) {
2153 Policy.ReduceLatency |= true;
2154 DEBUG(dbgs() << " " << CurrZone.Available.getName()
2155 << " RemainingLatency " << RemLatency << " + "
2156 << CurrZone.getCurrCycle() << "c > CritPath "
2157 << Rem.CriticalPath << "\n");
2158 }
2159 }
2160 // If the same resource is limiting inside and outside the zone, do nothing.
2161 if (CurrZone.getZoneCritResIdx() == OtherCritIdx)
2162 return;
2163
2164 DEBUG(
2165 if (CurrZone.isResourceLimited()) {
2166 dbgs() << " " << CurrZone.Available.getName() << " ResourceLimited: "
2167 << SchedModel->getResourceName(CurrZone.getZoneCritResIdx())
2168 << "\n";
2169 }
2170 if (OtherResLimited)
2171 dbgs() << " RemainingLimit: "
2172 << SchedModel->getResourceName(OtherCritIdx) << "\n";
2173 if (!CurrZone.isResourceLimited() && !OtherResLimited)
2174 dbgs() << " Latency limited both directions.\n");
2175
2176 if (CurrZone.isResourceLimited() && !Policy.ReduceResIdx)
2177 Policy.ReduceResIdx = CurrZone.getZoneCritResIdx();
2178
2179 if (OtherResLimited)
2180 Policy.DemandResIdx = OtherCritIdx;
2181}
2182
2183#ifndef NDEBUG
2184const char *GenericSchedulerBase::getReasonStr(
2185 GenericSchedulerBase::CandReason Reason) {
2186 switch (Reason) {
2187 case NoCand: return "NOCAND ";
2188 case PhysRegCopy: return "PREG-COPY";
2189 case RegExcess: return "REG-EXCESS";
2190 case RegCritical: return "REG-CRIT ";
2191 case Stall: return "STALL ";
2192 case Cluster: return "CLUSTER ";
2193 case Weak: return "WEAK ";
2194 case RegMax: return "REG-MAX ";
2195 case ResourceReduce: return "RES-REDUCE";
2196 case ResourceDemand: return "RES-DEMAND";
2197 case TopDepthReduce: return "TOP-DEPTH ";
2198 case TopPathReduce: return "TOP-PATH ";
2199 case BotHeightReduce:return "BOT-HEIGHT";
2200 case BotPathReduce: return "BOT-PATH ";
2201 case NextDefUse: return "DEF-USE ";
2202 case NodeOrder: return "ORDER ";
2203 };
2204 llvm_unreachable("Unknown reason!");
2205}
2206
2207void GenericSchedulerBase::traceCandidate(const SchedCandidate &Cand) {
2208 PressureChange P;
2209 unsigned ResIdx = 0;
2210 unsigned Latency = 0;
2211 switch (Cand.Reason) {
2212 default:
2213 break;
2214 case RegExcess:
2215 P = Cand.RPDelta.Excess;
2216 break;
2217 case RegCritical:
2218 P = Cand.RPDelta.CriticalMax;
2219 break;
2220 case RegMax:
2221 P = Cand.RPDelta.CurrentMax;
2222 break;
2223 case ResourceReduce:
2224 ResIdx = Cand.Policy.ReduceResIdx;
2225 break;
2226 case ResourceDemand:
2227 ResIdx = Cand.Policy.DemandResIdx;
2228 break;
2229 case TopDepthReduce:
2230 Latency = Cand.SU->getDepth();
2231 break;
2232 case TopPathReduce:
2233 Latency = Cand.SU->getHeight();
2234 break;
2235 case BotHeightReduce:
2236 Latency = Cand.SU->getHeight();
2237 break;
2238 case BotPathReduce:
2239 Latency = Cand.SU->getDepth();
2240 break;
2241 }
2242 dbgs() << " SU(" << Cand.SU->NodeNum << ") " << getReasonStr(Cand.Reason);
2243 if (P.isValid())
2244 dbgs() << " " << TRI->getRegPressureSetName(P.getPSet())
2245 << ":" << P.getUnitInc() << " ";
2246 else
2247 dbgs() << " ";
2248 if (ResIdx)
2249 dbgs() << " " << SchedModel->getProcResource(ResIdx)->Name << " ";
2250 else
2251 dbgs() << " ";
2252 if (Latency)
2253 dbgs() << " " << Latency << " cycles ";
2254 else
2255 dbgs() << " ";
2256 dbgs() << '\n';
2257}
2258#endif
2259
2260/// Return true if this heuristic determines order.
2261static bool tryLess(int TryVal, int CandVal,
2262 GenericSchedulerBase::SchedCandidate &TryCand,
2263 GenericSchedulerBase::SchedCandidate &Cand,
2264 GenericSchedulerBase::CandReason Reason) {
2265 if (TryVal < CandVal) {
2266 TryCand.Reason = Reason;
2267 return true;
2268 }
2269 if (TryVal > CandVal) {
2270 if (Cand.Reason > Reason)
2271 Cand.Reason = Reason;
2272 return true;
2273 }
2274 Cand.setRepeat(Reason);
2275 return false;
2276}
2277
2278static bool tryGreater(int TryVal, int CandVal,
2279 GenericSchedulerBase::SchedCandidate &TryCand,
2280 GenericSchedulerBase::SchedCandidate &Cand,
2281 GenericSchedulerBase::CandReason Reason) {
2282 if (TryVal > CandVal) {
2283 TryCand.Reason = Reason;
2284 return true;
2285 }
2286 if (TryVal < CandVal) {
2287 if (Cand.Reason > Reason)
2288 Cand.Reason = Reason;
2289 return true;
2290 }
2291 Cand.setRepeat(Reason);
2292 return false;
2293}
2294
2295static bool tryLatency(GenericSchedulerBase::SchedCandidate &TryCand,
2296 GenericSchedulerBase::SchedCandidate &Cand,
2297 SchedBoundary &Zone) {
2298 if (Zone.isTop()) {
2299 if (Cand.SU->getDepth() > Zone.getScheduledLatency()) {
2300 if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2301 TryCand, Cand, GenericSchedulerBase::TopDepthReduce))
2302 return true;
2303 }
2304 if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2305 TryCand, Cand, GenericSchedulerBase::TopPathReduce))
2306 return true;
2307 }
2308 else {
2309 if (Cand.SU->getHeight() > Zone.getScheduledLatency()) {
2310 if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2311 TryCand, Cand, GenericSchedulerBase::BotHeightReduce))
2312 return true;
2313 }
2314 if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2315 TryCand, Cand, GenericSchedulerBase::BotPathReduce))
2316 return true;
2317 }
2318 return false;
2319}
2320
2321static void tracePick(const GenericSchedulerBase::SchedCandidate &Cand,
2322 bool IsTop) {
2323 DEBUG(dbgs() << "Pick " << (IsTop ? "Top " : "Bot ")
2324 << GenericSchedulerBase::getReasonStr(Cand.Reason) << '\n');
2325}
2326
Andrew Trickfc127d12013-12-07 05:59:44 +00002327void GenericScheduler::initialize(ScheduleDAGMI *dag) {
Andrew Trickd7f890e2013-12-28 21:56:47 +00002328 assert(dag->hasVRegLiveness() &&
2329 "(PreRA)GenericScheduler needs vreg liveness");
2330 DAG = static_cast<ScheduleDAGMILive*>(dag);
Andrew Trickfc127d12013-12-07 05:59:44 +00002331 SchedModel = DAG->getSchedModel();
2332 TRI = DAG->TRI;
2333
2334 Rem.init(DAG, SchedModel);
2335 Top.init(DAG, SchedModel, &Rem);
2336 Bot.init(DAG, SchedModel, &Rem);
2337
2338 // Initialize resource counts.
2339
2340 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
2341 // are disabled, then these HazardRecs will be disabled.
2342 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
2343 const TargetMachine &TM = DAG->MF.getTarget();
2344 if (!Top.HazardRec) {
2345 Top.HazardRec =
2346 TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
2347 }
2348 if (!Bot.HazardRec) {
2349 Bot.HazardRec =
2350 TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
2351 }
2352}
2353
2354/// Initialize the per-region scheduling policy.
2355void GenericScheduler::initPolicy(MachineBasicBlock::iterator Begin,
2356 MachineBasicBlock::iterator End,
2357 unsigned NumRegionInstrs) {
2358 const TargetMachine &TM = Context->MF->getTarget();
Andrew Trick46753512014-01-22 03:38:55 +00002359 const TargetLowering *TLI = TM.getTargetLowering();
Andrew Trickfc127d12013-12-07 05:59:44 +00002360
2361 // Avoid setting up the register pressure tracker for small regions to save
2362 // compile time. As a rough heuristic, only track pressure when the number of
2363 // schedulable instructions exceeds half the integer register file.
Andrew Trick350ff2c2014-01-21 21:27:37 +00002364 RegionPolicy.ShouldTrackPressure = true;
Andrew Trick46753512014-01-22 03:38:55 +00002365 for (unsigned VT = MVT::i32; VT > (unsigned)MVT::i1; --VT) {
2366 MVT::SimpleValueType LegalIntVT = (MVT::SimpleValueType)VT;
2367 if (TLI->isTypeLegal(LegalIntVT)) {
Andrew Trick350ff2c2014-01-21 21:27:37 +00002368 unsigned NIntRegs = Context->RegClassInfo->getNumAllocatableRegs(
Andrew Trick46753512014-01-22 03:38:55 +00002369 TLI->getRegClassFor(LegalIntVT));
Andrew Trick350ff2c2014-01-21 21:27:37 +00002370 RegionPolicy.ShouldTrackPressure = NumRegionInstrs > (NIntRegs / 2);
2371 }
2372 }
Andrew Trickfc127d12013-12-07 05:59:44 +00002373
2374 // For generic targets, we default to bottom-up, because it's simpler and more
2375 // compile-time optimizations have been implemented in that direction.
2376 RegionPolicy.OnlyBottomUp = true;
2377
2378 // Allow the subtarget to override default policy.
2379 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
2380 ST.overrideSchedPolicy(RegionPolicy, Begin, End, NumRegionInstrs);
2381
2382 // After subtarget overrides, apply command line options.
2383 if (!EnableRegPressure)
2384 RegionPolicy.ShouldTrackPressure = false;
2385
2386 // Check -misched-topdown/bottomup can force or unforce scheduling direction.
2387 // e.g. -misched-bottomup=false allows scheduling in both directions.
2388 assert((!ForceTopDown || !ForceBottomUp) &&
2389 "-misched-topdown incompatible with -misched-bottomup");
2390 if (ForceBottomUp.getNumOccurrences() > 0) {
2391 RegionPolicy.OnlyBottomUp = ForceBottomUp;
2392 if (RegionPolicy.OnlyBottomUp)
2393 RegionPolicy.OnlyTopDown = false;
2394 }
2395 if (ForceTopDown.getNumOccurrences() > 0) {
2396 RegionPolicy.OnlyTopDown = ForceTopDown;
2397 if (RegionPolicy.OnlyTopDown)
2398 RegionPolicy.OnlyBottomUp = false;
2399 }
2400}
2401
2402/// Set IsAcyclicLatencyLimited if the acyclic path is longer than the cyclic
2403/// critical path by more cycles than it takes to drain the instruction buffer.
2404/// We estimate an upper bounds on in-flight instructions as:
2405///
2406/// CyclesPerIteration = max( CyclicPath, Loop-Resource-Height )
2407/// InFlightIterations = AcyclicPath / CyclesPerIteration
2408/// InFlightResources = InFlightIterations * LoopResources
2409///
2410/// TODO: Check execution resources in addition to IssueCount.
2411void GenericScheduler::checkAcyclicLatency() {
2412 if (Rem.CyclicCritPath == 0 || Rem.CyclicCritPath >= Rem.CriticalPath)
2413 return;
2414
2415 // Scaled number of cycles per loop iteration.
2416 unsigned IterCount =
2417 std::max(Rem.CyclicCritPath * SchedModel->getLatencyFactor(),
2418 Rem.RemIssueCount);
2419 // Scaled acyclic critical path.
2420 unsigned AcyclicCount = Rem.CriticalPath * SchedModel->getLatencyFactor();
2421 // InFlightCount = (AcyclicPath / IterCycles) * InstrPerLoop
2422 unsigned InFlightCount =
2423 (AcyclicCount * Rem.RemIssueCount + IterCount-1) / IterCount;
2424 unsigned BufferLimit =
2425 SchedModel->getMicroOpBufferSize() * SchedModel->getMicroOpFactor();
2426
2427 Rem.IsAcyclicLatencyLimited = InFlightCount > BufferLimit;
2428
2429 DEBUG(dbgs() << "IssueCycles="
2430 << Rem.RemIssueCount / SchedModel->getLatencyFactor() << "c "
2431 << "IterCycles=" << IterCount / SchedModel->getLatencyFactor()
2432 << "c NumIters=" << (AcyclicCount + IterCount-1) / IterCount
2433 << " InFlight=" << InFlightCount / SchedModel->getMicroOpFactor()
2434 << "m BufferLim=" << SchedModel->getMicroOpBufferSize() << "m\n";
2435 if (Rem.IsAcyclicLatencyLimited)
2436 dbgs() << " ACYCLIC LATENCY LIMIT\n");
2437}
2438
2439void GenericScheduler::registerRoots() {
2440 Rem.CriticalPath = DAG->ExitSU.getDepth();
2441
2442 // Some roots may not feed into ExitSU. Check all of them in case.
2443 for (std::vector<SUnit*>::const_iterator
2444 I = Bot.Available.begin(), E = Bot.Available.end(); I != E; ++I) {
2445 if ((*I)->getDepth() > Rem.CriticalPath)
2446 Rem.CriticalPath = (*I)->getDepth();
2447 }
2448 DEBUG(dbgs() << "Critical Path: " << Rem.CriticalPath << '\n');
2449
2450 if (EnableCyclicPath) {
2451 Rem.CyclicCritPath = DAG->computeCyclicCriticalPath();
2452 checkAcyclicLatency();
2453 }
2454}
2455
Andrew Trick1a831342013-08-30 03:49:48 +00002456static bool tryPressure(const PressureChange &TryP,
2457 const PressureChange &CandP,
Andrew Trickd14d7c22013-12-28 21:56:57 +00002458 GenericSchedulerBase::SchedCandidate &TryCand,
2459 GenericSchedulerBase::SchedCandidate &Cand,
2460 GenericSchedulerBase::CandReason Reason) {
Andrew Trickb1a45b62013-08-30 04:27:29 +00002461 int TryRank = TryP.getPSetOrMax();
2462 int CandRank = CandP.getPSetOrMax();
2463 // If both candidates affect the same set, go with the smallest increase.
2464 if (TryRank == CandRank) {
2465 return tryLess(TryP.getUnitInc(), CandP.getUnitInc(), TryCand, Cand,
2466 Reason);
Andrew Trick401b6952013-07-25 07:26:35 +00002467 }
Andrew Trickb1a45b62013-08-30 04:27:29 +00002468 // If one candidate decreases and the other increases, go with it.
2469 // Invalid candidates have UnitInc==0.
2470 if (tryLess(TryP.getUnitInc() < 0, CandP.getUnitInc() < 0, TryCand, Cand,
2471 Reason)) {
2472 return true;
2473 }
Andrew Trick401b6952013-07-25 07:26:35 +00002474 // If the candidates are decreasing pressure, reverse priority.
Andrew Trick1a831342013-08-30 03:49:48 +00002475 if (TryP.getUnitInc() < 0)
Andrew Trick401b6952013-07-25 07:26:35 +00002476 std::swap(TryRank, CandRank);
2477 return tryGreater(TryRank, CandRank, TryCand, Cand, Reason);
2478}
2479
Andrew Tricka7714a02012-11-12 19:40:10 +00002480static unsigned getWeakLeft(const SUnit *SU, bool isTop) {
2481 return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
2482}
2483
Andrew Tricke833e1c2013-04-13 06:07:40 +00002484/// Minimize physical register live ranges. Regalloc wants them adjacent to
2485/// their physreg def/use.
2486///
2487/// FIXME: This is an unnecessary check on the critical path. Most are root/leaf
2488/// copies which can be prescheduled. The rest (e.g. x86 MUL) could be bundled
2489/// with the operation that produces or consumes the physreg. We'll do this when
2490/// regalloc has support for parallel copies.
2491static int biasPhysRegCopy(const SUnit *SU, bool isTop) {
2492 const MachineInstr *MI = SU->getInstr();
2493 if (!MI->isCopy())
2494 return 0;
2495
2496 unsigned ScheduledOper = isTop ? 1 : 0;
2497 unsigned UnscheduledOper = isTop ? 0 : 1;
2498 // If we have already scheduled the physreg produce/consumer, immediately
2499 // schedule the copy.
2500 if (TargetRegisterInfo::isPhysicalRegister(
2501 MI->getOperand(ScheduledOper).getReg()))
2502 return 1;
2503 // If the physreg is at the boundary, defer it. Otherwise schedule it
2504 // immediately to free the dependent. We can hoist the copy later.
2505 bool AtBoundary = isTop ? !SU->NumSuccsLeft : !SU->NumPredsLeft;
2506 if (TargetRegisterInfo::isPhysicalRegister(
2507 MI->getOperand(UnscheduledOper).getReg()))
2508 return AtBoundary ? -1 : 1;
2509 return 0;
2510}
2511
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002512/// Apply a set of heursitics to a new candidate. Heuristics are currently
2513/// hierarchical. This may be more efficient than a graduated cost model because
2514/// we don't need to evaluate all aspects of the model for each node in the
2515/// queue. But it's really done to make the heuristics easier to debug and
2516/// statistically analyze.
2517///
2518/// \param Cand provides the policy and current best candidate.
2519/// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
2520/// \param Zone describes the scheduled zone that we are extending.
2521/// \param RPTracker describes reg pressure within the scheduled zone.
2522/// \param TempTracker is a scratch pressure tracker to reuse in queries.
Andrew Trick665d3ec2013-09-19 23:10:59 +00002523void GenericScheduler::tryCandidate(SchedCandidate &Cand,
Andrew Trickbb1247b2013-12-05 17:55:47 +00002524 SchedCandidate &TryCand,
2525 SchedBoundary &Zone,
2526 const RegPressureTracker &RPTracker,
2527 RegPressureTracker &TempTracker) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002528
Andrew Trick66c3dfb2013-09-04 21:00:11 +00002529 if (DAG->isTrackingPressure()) {
Andrew Trick310190e2013-09-04 21:00:02 +00002530 // Always initialize TryCand's RPDelta.
2531 if (Zone.isTop()) {
2532 TempTracker.getMaxDownwardPressureDelta(
Andrew Trick1a831342013-08-30 03:49:48 +00002533 TryCand.SU->getInstr(),
Andrew Trick1a831342013-08-30 03:49:48 +00002534 TryCand.RPDelta,
2535 DAG->getRegionCriticalPSets(),
2536 DAG->getRegPressure().MaxSetPressure);
2537 }
2538 else {
Andrew Trick310190e2013-09-04 21:00:02 +00002539 if (VerifyScheduling) {
2540 TempTracker.getMaxUpwardPressureDelta(
2541 TryCand.SU->getInstr(),
2542 &DAG->getPressureDiff(TryCand.SU),
2543 TryCand.RPDelta,
2544 DAG->getRegionCriticalPSets(),
2545 DAG->getRegPressure().MaxSetPressure);
2546 }
2547 else {
2548 RPTracker.getUpwardPressureDelta(
2549 TryCand.SU->getInstr(),
2550 DAG->getPressureDiff(TryCand.SU),
2551 TryCand.RPDelta,
2552 DAG->getRegionCriticalPSets(),
2553 DAG->getRegPressure().MaxSetPressure);
2554 }
Andrew Trick1a831342013-08-30 03:49:48 +00002555 }
2556 }
Andrew Trickc573cd92013-09-06 17:32:44 +00002557 DEBUG(if (TryCand.RPDelta.Excess.isValid())
2558 dbgs() << " SU(" << TryCand.SU->NodeNum << ") "
2559 << TRI->getRegPressureSetName(TryCand.RPDelta.Excess.getPSet())
2560 << ":" << TryCand.RPDelta.Excess.getUnitInc() << "\n");
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002561
2562 // Initialize the candidate if needed.
2563 if (!Cand.isValid()) {
2564 TryCand.Reason = NodeOrder;
2565 return;
2566 }
Andrew Tricke833e1c2013-04-13 06:07:40 +00002567
2568 if (tryGreater(biasPhysRegCopy(TryCand.SU, Zone.isTop()),
2569 biasPhysRegCopy(Cand.SU, Zone.isTop()),
2570 TryCand, Cand, PhysRegCopy))
2571 return;
2572
Andrew Trick401b6952013-07-25 07:26:35 +00002573 // Avoid exceeding the target's limit. If signed PSetID is negative, it is
2574 // invalid; convert it to INT_MAX to give it lowest priority.
Andrew Trick66c3dfb2013-09-04 21:00:11 +00002575 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.Excess,
2576 Cand.RPDelta.Excess,
2577 TryCand, Cand, RegExcess))
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002578 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002579
2580 // Avoid increasing the max critical pressure in the scheduled region.
Andrew Trick66c3dfb2013-09-04 21:00:11 +00002581 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CriticalMax,
2582 Cand.RPDelta.CriticalMax,
2583 TryCand, Cand, RegCritical))
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002584 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002585
Andrew Trickddffae92013-09-06 17:32:36 +00002586 // For loops that are acyclic path limited, aggressively schedule for latency.
Andrew Tricke1f7bf22013-09-09 22:28:08 +00002587 // This can result in very long dependence chains scheduled in sequence, so
2588 // once every cycle (when CurrMOps == 0), switch to normal heuristics.
Andrew Trickfc127d12013-12-07 05:59:44 +00002589 if (Rem.IsAcyclicLatencyLimited && !Zone.getCurrMOps()
Andrew Tricke1f7bf22013-09-09 22:28:08 +00002590 && tryLatency(TryCand, Cand, Zone))
Andrew Trickddffae92013-09-06 17:32:36 +00002591 return;
2592
Andrew Trick880e5732013-12-05 17:55:58 +00002593 // Prioritize instructions that read unbuffered resources by stall cycles.
2594 if (tryLess(Zone.getLatencyStallCycles(TryCand.SU),
2595 Zone.getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
2596 return;
2597
Andrew Tricka7714a02012-11-12 19:40:10 +00002598 // Keep clustered nodes together to encourage downstream peephole
2599 // optimizations which may reduce resource requirements.
2600 //
2601 // This is a best effort to set things up for a post-RA pass. Optimizations
2602 // like generating loads of multiple registers should ideally be done within
2603 // the scheduler pass by combining the loads during DAG postprocessing.
2604 const SUnit *NextClusterSU =
2605 Zone.isTop() ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
2606 if (tryGreater(TryCand.SU == NextClusterSU, Cand.SU == NextClusterSU,
2607 TryCand, Cand, Cluster))
2608 return;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00002609
2610 // Weak edges are for clustering and other constraints.
Andrew Tricka7714a02012-11-12 19:40:10 +00002611 if (tryLess(getWeakLeft(TryCand.SU, Zone.isTop()),
2612 getWeakLeft(Cand.SU, Zone.isTop()),
Andrew Trick85a1d4c2013-04-24 15:54:43 +00002613 TryCand, Cand, Weak)) {
Andrew Tricka7714a02012-11-12 19:40:10 +00002614 return;
2615 }
Andrew Trick71f08a32013-06-17 21:45:13 +00002616 // Avoid increasing the max pressure of the entire region.
Andrew Trick66c3dfb2013-09-04 21:00:11 +00002617 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CurrentMax,
2618 Cand.RPDelta.CurrentMax,
2619 TryCand, Cand, RegMax))
Andrew Trick71f08a32013-06-17 21:45:13 +00002620 return;
2621
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002622 // Avoid critical resource consumption and balance the schedule.
2623 TryCand.initResourceDelta(DAG, SchedModel);
2624 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
2625 TryCand, Cand, ResourceReduce))
2626 return;
2627 if (tryGreater(TryCand.ResDelta.DemandedResources,
2628 Cand.ResDelta.DemandedResources,
2629 TryCand, Cand, ResourceDemand))
2630 return;
2631
2632 // Avoid serializing long latency dependence chains.
Andrew Trickc01b0042013-08-23 17:48:43 +00002633 // For acyclic path limited loops, latency was already checked above.
2634 if (Cand.Policy.ReduceLatency && !Rem.IsAcyclicLatencyLimited
2635 && tryLatency(TryCand, Cand, Zone)) {
2636 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002637 }
2638
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002639 // Prefer immediate defs/users of the last scheduled instruction. This is a
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002640 // local pressure avoidance strategy that also makes the machine code
2641 // readable.
Andrew Trickfc127d12013-12-07 05:59:44 +00002642 if (tryGreater(Zone.isNextSU(TryCand.SU), Zone.isNextSU(Cand.SU),
Andrew Tricka7714a02012-11-12 19:40:10 +00002643 TryCand, Cand, NextDefUse))
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002644 return;
Andrew Tricka7714a02012-11-12 19:40:10 +00002645
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002646 // Fall through to original instruction order.
2647 if ((Zone.isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
2648 || (!Zone.isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
2649 TryCand.Reason = NodeOrder;
2650 }
2651}
Andrew Trick419eae22012-05-10 21:06:19 +00002652
Andrew Trickc573cd92013-09-06 17:32:44 +00002653/// Pick the best candidate from the queue.
Andrew Trick7ee9de52012-05-10 21:06:16 +00002654///
2655/// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
2656/// DAG building. To adjust for the current scheduling location we need to
2657/// maintain the number of vreg uses remaining to be top-scheduled.
Andrew Trick665d3ec2013-09-19 23:10:59 +00002658void GenericScheduler::pickNodeFromQueue(SchedBoundary &Zone,
Andrew Trickbb1247b2013-12-05 17:55:47 +00002659 const RegPressureTracker &RPTracker,
2660 SchedCandidate &Cand) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002661 ReadyQueue &Q = Zone.Available;
2662
Andrew Tricka8ad5f72012-05-24 22:11:12 +00002663 DEBUG(Q.dump());
Andrew Trick22025772012-05-17 18:35:10 +00002664
Andrew Trick7ee9de52012-05-10 21:06:16 +00002665 // getMaxPressureDelta temporarily modifies the tracker.
2666 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
2667
Andrew Trickdd375dd2012-05-24 22:11:03 +00002668 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
Andrew Trick7ee9de52012-05-10 21:06:16 +00002669
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002670 SchedCandidate TryCand(Cand.Policy);
2671 TryCand.SU = *I;
2672 tryCandidate(Cand, TryCand, Zone, RPTracker, TempTracker);
2673 if (TryCand.Reason != NoCand) {
2674 // Initialize resource delta if needed in case future heuristics query it.
2675 if (TryCand.ResDelta == SchedResourceDelta())
2676 TryCand.initResourceDelta(DAG, SchedModel);
2677 Cand.setBest(TryCand);
Andrew Trick419d4912013-04-05 00:31:29 +00002678 DEBUG(traceCandidate(Cand));
Andrew Trick22025772012-05-17 18:35:10 +00002679 }
Andrew Trick7ee9de52012-05-10 21:06:16 +00002680 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002681}
2682
Andrew Trick22025772012-05-17 18:35:10 +00002683/// Pick the best candidate node from either the top or bottom queue.
Andrew Trick665d3ec2013-09-19 23:10:59 +00002684SUnit *GenericScheduler::pickNodeBidirectional(bool &IsTopNode) {
Andrew Trick22025772012-05-17 18:35:10 +00002685 // Schedule as far as possible in the direction of no choice. This is most
2686 // efficient, but also provides the best heuristics for CriticalPSets.
Andrew Trick61f1a272012-05-24 22:11:09 +00002687 if (SUnit *SU = Bot.pickOnlyChoice()) {
Andrew Trick22025772012-05-17 18:35:10 +00002688 IsTopNode = false;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002689 DEBUG(dbgs() << "Pick Bot NOCAND\n");
Andrew Trick61f1a272012-05-24 22:11:09 +00002690 return SU;
Andrew Trick22025772012-05-17 18:35:10 +00002691 }
Andrew Trick61f1a272012-05-24 22:11:09 +00002692 if (SUnit *SU = Top.pickOnlyChoice()) {
Andrew Trick22025772012-05-17 18:35:10 +00002693 IsTopNode = true;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002694 DEBUG(dbgs() << "Pick Top NOCAND\n");
Andrew Trick61f1a272012-05-24 22:11:09 +00002695 return SU;
Andrew Trick22025772012-05-17 18:35:10 +00002696 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002697 CandPolicy NoPolicy;
2698 SchedCandidate BotCand(NoPolicy);
2699 SchedCandidate TopCand(NoPolicy);
Andrew Trickfc127d12013-12-07 05:59:44 +00002700 // Set the bottom-up policy based on the state of the current bottom zone and
2701 // the instructions outside the zone, including the top zone.
Andrew Trickd14d7c22013-12-28 21:56:57 +00002702 setPolicy(BotCand.Policy, /*IsPostRA=*/false, Bot, &Top);
Andrew Trickfc127d12013-12-07 05:59:44 +00002703 // Set the top-down policy based on the state of the current top zone and
2704 // the instructions outside the zone, including the bottom zone.
Andrew Trickd14d7c22013-12-28 21:56:57 +00002705 setPolicy(TopCand.Policy, /*IsPostRA=*/false, Top, &Bot);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002706
Andrew Trick22025772012-05-17 18:35:10 +00002707 // Prefer bottom scheduling when heuristics are silent.
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002708 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
2709 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick22025772012-05-17 18:35:10 +00002710
2711 // If either Q has a single candidate that provides the least increase in
2712 // Excess pressure, we can immediately schedule from that Q.
2713 //
2714 // RegionCriticalPSets summarizes the pressure within the scheduled region and
2715 // affects picking from either Q. If scheduling in one direction must
2716 // increase pressure for one of the excess PSets, then schedule in that
2717 // direction first to provide more freedom in the other direction.
Andrew Trickd40d0f22013-06-17 21:45:05 +00002718 if ((BotCand.Reason == RegExcess && !BotCand.isRepeat(RegExcess))
2719 || (BotCand.Reason == RegCritical
2720 && !BotCand.isRepeat(RegCritical)))
2721 {
Andrew Trick22025772012-05-17 18:35:10 +00002722 IsTopNode = false;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002723 tracePick(BotCand, IsTopNode);
Andrew Trick61f1a272012-05-24 22:11:09 +00002724 return BotCand.SU;
Andrew Trick22025772012-05-17 18:35:10 +00002725 }
2726 // Check if the top Q has a better candidate.
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002727 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
2728 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick22025772012-05-17 18:35:10 +00002729
Andrew Trickd40d0f22013-06-17 21:45:05 +00002730 // Choose the queue with the most important (lowest enum) reason.
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002731 if (TopCand.Reason < BotCand.Reason) {
2732 IsTopNode = true;
2733 tracePick(TopCand, IsTopNode);
2734 return TopCand.SU;
2735 }
Andrew Trickd40d0f22013-06-17 21:45:05 +00002736 // Otherwise prefer the bottom candidate, in node order if all else failed.
Andrew Trick22025772012-05-17 18:35:10 +00002737 IsTopNode = false;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002738 tracePick(BotCand, IsTopNode);
Andrew Trick61f1a272012-05-24 22:11:09 +00002739 return BotCand.SU;
Andrew Trick22025772012-05-17 18:35:10 +00002740}
2741
2742/// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
Andrew Trick665d3ec2013-09-19 23:10:59 +00002743SUnit *GenericScheduler::pickNode(bool &IsTopNode) {
Andrew Trick7ee9de52012-05-10 21:06:16 +00002744 if (DAG->top() == DAG->bottom()) {
Andrew Trick61f1a272012-05-24 22:11:09 +00002745 assert(Top.Available.empty() && Top.Pending.empty() &&
2746 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
Craig Topperc0196b12014-04-14 00:51:57 +00002747 return nullptr;
Andrew Trick7ee9de52012-05-10 21:06:16 +00002748 }
Andrew Trick7ee9de52012-05-10 21:06:16 +00002749 SUnit *SU;
Andrew Trick984d98b2012-10-08 18:53:53 +00002750 do {
Andrew Trick75e411c2013-09-06 17:32:34 +00002751 if (RegionPolicy.OnlyTopDown) {
Andrew Trick984d98b2012-10-08 18:53:53 +00002752 SU = Top.pickOnlyChoice();
2753 if (!SU) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002754 CandPolicy NoPolicy;
2755 SchedCandidate TopCand(NoPolicy);
2756 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
Andrew Trick1ab16d92013-09-04 21:00:13 +00002757 assert(TopCand.Reason != NoCand && "failed to find a candidate");
Andrew Trickef54c592013-09-04 21:00:16 +00002758 tracePick(TopCand, true);
Andrew Trick984d98b2012-10-08 18:53:53 +00002759 SU = TopCand.SU;
2760 }
2761 IsTopNode = true;
Andrew Tricka306a8a2012-05-24 23:11:17 +00002762 }
Andrew Trick75e411c2013-09-06 17:32:34 +00002763 else if (RegionPolicy.OnlyBottomUp) {
Andrew Trick984d98b2012-10-08 18:53:53 +00002764 SU = Bot.pickOnlyChoice();
2765 if (!SU) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002766 CandPolicy NoPolicy;
2767 SchedCandidate BotCand(NoPolicy);
2768 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
Andrew Trick1ab16d92013-09-04 21:00:13 +00002769 assert(BotCand.Reason != NoCand && "failed to find a candidate");
Andrew Trickef54c592013-09-04 21:00:16 +00002770 tracePick(BotCand, false);
Andrew Trick984d98b2012-10-08 18:53:53 +00002771 SU = BotCand.SU;
2772 }
2773 IsTopNode = false;
Andrew Tricka306a8a2012-05-24 23:11:17 +00002774 }
Andrew Trick984d98b2012-10-08 18:53:53 +00002775 else {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002776 SU = pickNodeBidirectional(IsTopNode);
Andrew Trick984d98b2012-10-08 18:53:53 +00002777 }
2778 } while (SU->isScheduled);
2779
Andrew Trick61f1a272012-05-24 22:11:09 +00002780 if (SU->isTopReady())
2781 Top.removeReady(SU);
2782 if (SU->isBottomReady())
2783 Bot.removeReady(SU);
Andrew Trick4e7f6a72012-05-25 02:02:39 +00002784
Andrew Trick1f0bb692013-04-13 06:07:49 +00002785 DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " << *SU->getInstr());
Andrew Trick7ee9de52012-05-10 21:06:16 +00002786 return SU;
2787}
2788
Andrew Trick665d3ec2013-09-19 23:10:59 +00002789void GenericScheduler::reschedulePhysRegCopies(SUnit *SU, bool isTop) {
Andrew Tricke833e1c2013-04-13 06:07:40 +00002790
2791 MachineBasicBlock::iterator InsertPos = SU->getInstr();
2792 if (!isTop)
2793 ++InsertPos;
2794 SmallVectorImpl<SDep> &Deps = isTop ? SU->Preds : SU->Succs;
2795
2796 // Find already scheduled copies with a single physreg dependence and move
2797 // them just above the scheduled instruction.
2798 for (SmallVectorImpl<SDep>::iterator I = Deps.begin(), E = Deps.end();
2799 I != E; ++I) {
2800 if (I->getKind() != SDep::Data || !TRI->isPhysicalRegister(I->getReg()))
2801 continue;
2802 SUnit *DepSU = I->getSUnit();
2803 if (isTop ? DepSU->Succs.size() > 1 : DepSU->Preds.size() > 1)
2804 continue;
2805 MachineInstr *Copy = DepSU->getInstr();
2806 if (!Copy->isCopy())
2807 continue;
2808 DEBUG(dbgs() << " Rescheduling physreg copy ";
2809 I->getSUnit()->dump(DAG));
2810 DAG->moveInstruction(Copy, InsertPos);
2811 }
2812}
2813
Andrew Trick61f1a272012-05-24 22:11:09 +00002814/// Update the scheduler's state after scheduling a node. This is the same node
Andrew Trickd14d7c22013-12-28 21:56:57 +00002815/// that was just returned by pickNode(). However, ScheduleDAGMILive needs to
2816/// update it's state based on the current cycle before MachineSchedStrategy
2817/// does.
Andrew Tricke833e1c2013-04-13 06:07:40 +00002818///
2819/// FIXME: Eventually, we may bundle physreg copies rather than rescheduling
2820/// them here. See comments in biasPhysRegCopy.
Andrew Trick665d3ec2013-09-19 23:10:59 +00002821void GenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
Andrew Trick45446062012-06-05 21:11:27 +00002822 if (IsTopNode) {
Andrew Trickfc127d12013-12-07 05:59:44 +00002823 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
Andrew Trickce27bb92012-06-29 03:23:22 +00002824 Top.bumpNode(SU);
Andrew Tricke833e1c2013-04-13 06:07:40 +00002825 if (SU->hasPhysRegUses)
2826 reschedulePhysRegCopies(SU, true);
Andrew Trick61f1a272012-05-24 22:11:09 +00002827 }
Andrew Trick45446062012-06-05 21:11:27 +00002828 else {
Andrew Trickfc127d12013-12-07 05:59:44 +00002829 SU->BotReadyCycle = std::max(SU->BotReadyCycle, Bot.getCurrCycle());
Andrew Trickce27bb92012-06-29 03:23:22 +00002830 Bot.bumpNode(SU);
Andrew Tricke833e1c2013-04-13 06:07:40 +00002831 if (SU->hasPhysRegDefs)
2832 reschedulePhysRegCopies(SU, false);
Andrew Trick61f1a272012-05-24 22:11:09 +00002833 }
2834}
2835
Andrew Trick8823dec2012-03-14 04:00:41 +00002836/// Create the standard converging machine scheduler. This will be used as the
2837/// default scheduler if the target does not set a default.
Andrew Trickd14d7c22013-12-28 21:56:57 +00002838static ScheduleDAGInstrs *createGenericSchedLive(MachineSchedContext *C) {
David Blaikie422b93d2014-04-21 20:32:32 +00002839 ScheduleDAGMILive *DAG = new ScheduleDAGMILive(C, make_unique<GenericScheduler>(C));
Andrew Tricka7714a02012-11-12 19:40:10 +00002840 // Register DAG post-processors.
Andrew Trick85a1d4c2013-04-24 15:54:43 +00002841 //
2842 // FIXME: extend the mutation API to allow earlier mutations to instantiate
2843 // data and pass it to later mutations. Have a single mutation that gathers
2844 // the interesting nodes in one pass.
David Blaikie422b93d2014-04-21 20:32:32 +00002845 DAG->addMutation(make_unique<CopyConstrain>(DAG->TII, DAG->TRI));
Andrew Tricka6e87772013-09-04 21:00:08 +00002846 if (EnableLoadCluster && DAG->TII->enableClusterLoads())
David Blaikie422b93d2014-04-21 20:32:32 +00002847 DAG->addMutation(make_unique<LoadClusterMutation>(DAG->TII, DAG->TRI));
Andrew Trick263280242012-11-12 19:52:20 +00002848 if (EnableMacroFusion)
David Blaikie422b93d2014-04-21 20:32:32 +00002849 DAG->addMutation(make_unique<MacroFusion>(DAG->TII));
Andrew Tricka7714a02012-11-12 19:40:10 +00002850 return DAG;
Andrew Tricke1c034f2012-01-17 06:55:03 +00002851}
Andrew Trickd14d7c22013-12-28 21:56:57 +00002852
Andrew Tricke1c034f2012-01-17 06:55:03 +00002853static MachineSchedRegistry
Andrew Trick665d3ec2013-09-19 23:10:59 +00002854GenericSchedRegistry("converge", "Standard converging scheduler.",
Andrew Trickd14d7c22013-12-28 21:56:57 +00002855 createGenericSchedLive);
2856
2857//===----------------------------------------------------------------------===//
2858// PostGenericScheduler - Generic PostRA implementation of MachineSchedStrategy.
2859//===----------------------------------------------------------------------===//
2860
Andrew Trick3ccf71d2014-06-04 07:06:18 +00002861void PostGenericScheduler::initialize(ScheduleDAGMI *Dag) {
2862 DAG = Dag;
2863 SchedModel = DAG->getSchedModel();
2864 TRI = DAG->TRI;
Andrew Trickd14d7c22013-12-28 21:56:57 +00002865
Andrew Trick3ccf71d2014-06-04 07:06:18 +00002866 Rem.init(DAG, SchedModel);
2867 Top.init(DAG, SchedModel, &Rem);
2868 BotRoots.clear();
Andrew Trickd14d7c22013-12-28 21:56:57 +00002869
Andrew Trick3ccf71d2014-06-04 07:06:18 +00002870 // Initialize the HazardRecognizers. If itineraries don't exist, are empty,
2871 // or are disabled, then these HazardRecs will be disabled.
2872 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
2873 const TargetMachine &TM = DAG->MF.getTarget();
2874 if (!Top.HazardRec) {
2875 Top.HazardRec =
2876 TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
Andrew Trickd14d7c22013-12-28 21:56:57 +00002877 }
Andrew Trick3ccf71d2014-06-04 07:06:18 +00002878}
Andrew Trickd14d7c22013-12-28 21:56:57 +00002879
Andrew Trickd14d7c22013-12-28 21:56:57 +00002880
2881void PostGenericScheduler::registerRoots() {
2882 Rem.CriticalPath = DAG->ExitSU.getDepth();
2883
2884 // Some roots may not feed into ExitSU. Check all of them in case.
2885 for (SmallVectorImpl<SUnit*>::const_iterator
2886 I = BotRoots.begin(), E = BotRoots.end(); I != E; ++I) {
2887 if ((*I)->getDepth() > Rem.CriticalPath)
2888 Rem.CriticalPath = (*I)->getDepth();
2889 }
2890 DEBUG(dbgs() << "Critical Path: " << Rem.CriticalPath << '\n');
2891}
2892
2893/// Apply a set of heursitics to a new candidate for PostRA scheduling.
2894///
2895/// \param Cand provides the policy and current best candidate.
2896/// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
2897void PostGenericScheduler::tryCandidate(SchedCandidate &Cand,
2898 SchedCandidate &TryCand) {
2899
2900 // Initialize the candidate if needed.
2901 if (!Cand.isValid()) {
2902 TryCand.Reason = NodeOrder;
2903 return;
2904 }
2905
2906 // Prioritize instructions that read unbuffered resources by stall cycles.
2907 if (tryLess(Top.getLatencyStallCycles(TryCand.SU),
2908 Top.getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
2909 return;
2910
2911 // Avoid critical resource consumption and balance the schedule.
2912 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
2913 TryCand, Cand, ResourceReduce))
2914 return;
2915 if (tryGreater(TryCand.ResDelta.DemandedResources,
2916 Cand.ResDelta.DemandedResources,
2917 TryCand, Cand, ResourceDemand))
2918 return;
2919
2920 // Avoid serializing long latency dependence chains.
2921 if (Cand.Policy.ReduceLatency && tryLatency(TryCand, Cand, Top)) {
2922 return;
2923 }
2924
2925 // Fall through to original instruction order.
2926 if (TryCand.SU->NodeNum < Cand.SU->NodeNum)
2927 TryCand.Reason = NodeOrder;
2928}
2929
2930void PostGenericScheduler::pickNodeFromQueue(SchedCandidate &Cand) {
2931 ReadyQueue &Q = Top.Available;
2932
2933 DEBUG(Q.dump());
2934
2935 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
2936 SchedCandidate TryCand(Cand.Policy);
2937 TryCand.SU = *I;
2938 TryCand.initResourceDelta(DAG, SchedModel);
2939 tryCandidate(Cand, TryCand);
2940 if (TryCand.Reason != NoCand) {
2941 Cand.setBest(TryCand);
2942 DEBUG(traceCandidate(Cand));
2943 }
2944 }
2945}
2946
2947/// Pick the next node to schedule.
2948SUnit *PostGenericScheduler::pickNode(bool &IsTopNode) {
2949 if (DAG->top() == DAG->bottom()) {
2950 assert(Top.Available.empty() && Top.Pending.empty() && "ReadyQ garbage");
Craig Topperc0196b12014-04-14 00:51:57 +00002951 return nullptr;
Andrew Trickd14d7c22013-12-28 21:56:57 +00002952 }
2953 SUnit *SU;
2954 do {
2955 SU = Top.pickOnlyChoice();
2956 if (!SU) {
2957 CandPolicy NoPolicy;
2958 SchedCandidate TopCand(NoPolicy);
2959 // Set the top-down policy based on the state of the current top zone and
2960 // the instructions outside the zone, including the bottom zone.
Craig Topperc0196b12014-04-14 00:51:57 +00002961 setPolicy(TopCand.Policy, /*IsPostRA=*/true, Top, nullptr);
Andrew Trickd14d7c22013-12-28 21:56:57 +00002962 pickNodeFromQueue(TopCand);
2963 assert(TopCand.Reason != NoCand && "failed to find a candidate");
2964 tracePick(TopCand, true);
2965 SU = TopCand.SU;
2966 }
2967 } while (SU->isScheduled);
2968
2969 IsTopNode = true;
2970 Top.removeReady(SU);
2971
2972 DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " << *SU->getInstr());
2973 return SU;
2974}
2975
2976/// Called after ScheduleDAGMI has scheduled an instruction and updated
2977/// scheduled/remaining flags in the DAG nodes.
2978void PostGenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
2979 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
2980 Top.bumpNode(SU);
2981}
2982
2983/// Create a generic scheduler with no vreg liveness or DAG mutation passes.
2984static ScheduleDAGInstrs *createGenericSchedPostRA(MachineSchedContext *C) {
David Blaikie422b93d2014-04-21 20:32:32 +00002985 return new ScheduleDAGMI(C, make_unique<PostGenericScheduler>(C), /*IsPostRA=*/true);
Andrew Trickd14d7c22013-12-28 21:56:57 +00002986}
Andrew Tricke1c034f2012-01-17 06:55:03 +00002987
2988//===----------------------------------------------------------------------===//
Andrew Trick90f711d2012-10-15 18:02:27 +00002989// ILP Scheduler. Currently for experimental analysis of heuristics.
2990//===----------------------------------------------------------------------===//
2991
2992namespace {
2993/// \brief Order nodes by the ILP metric.
2994struct ILPOrder {
Andrew Trick44f750a2013-01-25 04:01:04 +00002995 const SchedDFSResult *DFSResult;
2996 const BitVector *ScheduledTrees;
Andrew Trick90f711d2012-10-15 18:02:27 +00002997 bool MaximizeILP;
2998
Craig Topperc0196b12014-04-14 00:51:57 +00002999 ILPOrder(bool MaxILP)
3000 : DFSResult(nullptr), ScheduledTrees(nullptr), MaximizeILP(MaxILP) {}
Andrew Trick90f711d2012-10-15 18:02:27 +00003001
3002 /// \brief Apply a less-than relation on node priority.
Andrew Trick48d392e2012-11-28 05:13:28 +00003003 ///
3004 /// (Return true if A comes after B in the Q.)
Andrew Trick90f711d2012-10-15 18:02:27 +00003005 bool operator()(const SUnit *A, const SUnit *B) const {
Andrew Trick48d392e2012-11-28 05:13:28 +00003006 unsigned SchedTreeA = DFSResult->getSubtreeID(A);
3007 unsigned SchedTreeB = DFSResult->getSubtreeID(B);
3008 if (SchedTreeA != SchedTreeB) {
3009 // Unscheduled trees have lower priority.
3010 if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
3011 return ScheduledTrees->test(SchedTreeB);
3012
3013 // Trees with shallower connections have have lower priority.
3014 if (DFSResult->getSubtreeLevel(SchedTreeA)
3015 != DFSResult->getSubtreeLevel(SchedTreeB)) {
3016 return DFSResult->getSubtreeLevel(SchedTreeA)
3017 < DFSResult->getSubtreeLevel(SchedTreeB);
3018 }
3019 }
Andrew Trick90f711d2012-10-15 18:02:27 +00003020 if (MaximizeILP)
Andrew Trick48d392e2012-11-28 05:13:28 +00003021 return DFSResult->getILP(A) < DFSResult->getILP(B);
Andrew Trick90f711d2012-10-15 18:02:27 +00003022 else
Andrew Trick48d392e2012-11-28 05:13:28 +00003023 return DFSResult->getILP(A) > DFSResult->getILP(B);
Andrew Trick90f711d2012-10-15 18:02:27 +00003024 }
3025};
3026
3027/// \brief Schedule based on the ILP metric.
3028class ILPScheduler : public MachineSchedStrategy {
Andrew Trickd7f890e2013-12-28 21:56:47 +00003029 ScheduleDAGMILive *DAG;
Andrew Trick90f711d2012-10-15 18:02:27 +00003030 ILPOrder Cmp;
3031
3032 std::vector<SUnit*> ReadyQ;
3033public:
Craig Topperc0196b12014-04-14 00:51:57 +00003034 ILPScheduler(bool MaximizeILP): DAG(nullptr), Cmp(MaximizeILP) {}
Andrew Trick90f711d2012-10-15 18:02:27 +00003035
Craig Topper4584cd52014-03-07 09:26:03 +00003036 void initialize(ScheduleDAGMI *dag) override {
Andrew Trickd7f890e2013-12-28 21:56:47 +00003037 assert(dag->hasVRegLiveness() && "ILPScheduler needs vreg liveness");
3038 DAG = static_cast<ScheduleDAGMILive*>(dag);
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00003039 DAG->computeDFSResult();
Andrew Trick44f750a2013-01-25 04:01:04 +00003040 Cmp.DFSResult = DAG->getDFSResult();
3041 Cmp.ScheduledTrees = &DAG->getScheduledTrees();
Andrew Trick90f711d2012-10-15 18:02:27 +00003042 ReadyQ.clear();
Andrew Trick90f711d2012-10-15 18:02:27 +00003043 }
3044
Craig Topper4584cd52014-03-07 09:26:03 +00003045 void registerRoots() override {
Benjamin Krameraa598b32012-11-29 14:36:26 +00003046 // Restore the heap in ReadyQ with the updated DFS results.
3047 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
Andrew Trick90f711d2012-10-15 18:02:27 +00003048 }
3049
3050 /// Implement MachineSchedStrategy interface.
3051 /// -----------------------------------------
3052
Andrew Trick48d392e2012-11-28 05:13:28 +00003053 /// Callback to select the highest priority node from the ready Q.
Craig Topper4584cd52014-03-07 09:26:03 +00003054 SUnit *pickNode(bool &IsTopNode) override {
Craig Topperc0196b12014-04-14 00:51:57 +00003055 if (ReadyQ.empty()) return nullptr;
Matt Arsenault4ab769f2013-03-21 00:57:21 +00003056 std::pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
Andrew Trick90f711d2012-10-15 18:02:27 +00003057 SUnit *SU = ReadyQ.back();
3058 ReadyQ.pop_back();
3059 IsTopNode = false;
Andrew Trick1f0bb692013-04-13 06:07:49 +00003060 DEBUG(dbgs() << "Pick node " << "SU(" << SU->NodeNum << ") "
Andrew Trick44f750a2013-01-25 04:01:04 +00003061 << " ILP: " << DAG->getDFSResult()->getILP(SU)
3062 << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU) << " @"
3063 << DAG->getDFSResult()->getSubtreeLevel(
Andrew Trick1f0bb692013-04-13 06:07:49 +00003064 DAG->getDFSResult()->getSubtreeID(SU)) << '\n'
3065 << "Scheduling " << *SU->getInstr());
Andrew Trick90f711d2012-10-15 18:02:27 +00003066 return SU;
3067 }
3068
Andrew Trick44f750a2013-01-25 04:01:04 +00003069 /// \brief Scheduler callback to notify that a new subtree is scheduled.
Craig Topper4584cd52014-03-07 09:26:03 +00003070 void scheduleTree(unsigned SubtreeID) override {
Andrew Trick44f750a2013-01-25 04:01:04 +00003071 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3072 }
3073
Andrew Trick48d392e2012-11-28 05:13:28 +00003074 /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
3075 /// DFSResults, and resort the priority Q.
Craig Topper4584cd52014-03-07 09:26:03 +00003076 void schedNode(SUnit *SU, bool IsTopNode) override {
Andrew Trick48d392e2012-11-28 05:13:28 +00003077 assert(!IsTopNode && "SchedDFSResult needs bottom-up");
Andrew Trick48d392e2012-11-28 05:13:28 +00003078 }
Andrew Trick90f711d2012-10-15 18:02:27 +00003079
Craig Topper4584cd52014-03-07 09:26:03 +00003080 void releaseTopNode(SUnit *) override { /*only called for top roots*/ }
Andrew Trick90f711d2012-10-15 18:02:27 +00003081
Craig Topper4584cd52014-03-07 09:26:03 +00003082 void releaseBottomNode(SUnit *SU) override {
Andrew Trick90f711d2012-10-15 18:02:27 +00003083 ReadyQ.push_back(SU);
3084 std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3085 }
3086};
3087} // namespace
3088
3089static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
David Blaikie422b93d2014-04-21 20:32:32 +00003090 return new ScheduleDAGMILive(C, make_unique<ILPScheduler>(true));
Andrew Trick90f711d2012-10-15 18:02:27 +00003091}
3092static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
David Blaikie422b93d2014-04-21 20:32:32 +00003093 return new ScheduleDAGMILive(C, make_unique<ILPScheduler>(false));
Andrew Trick90f711d2012-10-15 18:02:27 +00003094}
3095static MachineSchedRegistry ILPMaxRegistry(
3096 "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
3097static MachineSchedRegistry ILPMinRegistry(
3098 "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
3099
3100//===----------------------------------------------------------------------===//
Andrew Trick63440872012-01-14 02:17:06 +00003101// Machine Instruction Shuffler for Correctness Testing
3102//===----------------------------------------------------------------------===//
3103
Andrew Tricke77e84e2012-01-13 06:30:30 +00003104#ifndef NDEBUG
3105namespace {
Andrew Trick8823dec2012-03-14 04:00:41 +00003106/// Apply a less-than relation on the node order, which corresponds to the
3107/// instruction order prior to scheduling. IsReverse implements greater-than.
3108template<bool IsReverse>
3109struct SUnitOrder {
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003110 bool operator()(SUnit *A, SUnit *B) const {
Andrew Trick8823dec2012-03-14 04:00:41 +00003111 if (IsReverse)
3112 return A->NodeNum > B->NodeNum;
3113 else
3114 return A->NodeNum < B->NodeNum;
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003115 }
3116};
3117
Andrew Tricke77e84e2012-01-13 06:30:30 +00003118/// Reorder instructions as much as possible.
Andrew Trick8823dec2012-03-14 04:00:41 +00003119class InstructionShuffler : public MachineSchedStrategy {
3120 bool IsAlternating;
3121 bool IsTopDown;
3122
3123 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
3124 // gives nodes with a higher number higher priority causing the latest
3125 // instructions to be scheduled first.
3126 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
3127 TopQ;
3128 // When scheduling bottom-up, use greater-than as the queue priority.
3129 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
3130 BottomQ;
Andrew Tricke77e84e2012-01-13 06:30:30 +00003131public:
Andrew Trick8823dec2012-03-14 04:00:41 +00003132 InstructionShuffler(bool alternate, bool topdown)
3133 : IsAlternating(alternate), IsTopDown(topdown) {}
Andrew Tricke77e84e2012-01-13 06:30:30 +00003134
Craig Topper9d74a5a2014-04-29 07:58:41 +00003135 void initialize(ScheduleDAGMI*) override {
Andrew Trick8823dec2012-03-14 04:00:41 +00003136 TopQ.clear();
3137 BottomQ.clear();
3138 }
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003139
Andrew Trick8823dec2012-03-14 04:00:41 +00003140 /// Implement MachineSchedStrategy interface.
3141 /// -----------------------------------------
3142
Craig Topper9d74a5a2014-04-29 07:58:41 +00003143 SUnit *pickNode(bool &IsTopNode) override {
Andrew Trick8823dec2012-03-14 04:00:41 +00003144 SUnit *SU;
3145 if (IsTopDown) {
3146 do {
Craig Topperc0196b12014-04-14 00:51:57 +00003147 if (TopQ.empty()) return nullptr;
Andrew Trick8823dec2012-03-14 04:00:41 +00003148 SU = TopQ.top();
3149 TopQ.pop();
3150 } while (SU->isScheduled);
3151 IsTopNode = true;
3152 }
3153 else {
3154 do {
Craig Topperc0196b12014-04-14 00:51:57 +00003155 if (BottomQ.empty()) return nullptr;
Andrew Trick8823dec2012-03-14 04:00:41 +00003156 SU = BottomQ.top();
3157 BottomQ.pop();
3158 } while (SU->isScheduled);
3159 IsTopNode = false;
3160 }
3161 if (IsAlternating)
3162 IsTopDown = !IsTopDown;
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003163 return SU;
3164 }
3165
Craig Topper9d74a5a2014-04-29 07:58:41 +00003166 void schedNode(SUnit *SU, bool IsTopNode) override {}
Andrew Trick61f1a272012-05-24 22:11:09 +00003167
Craig Topper9d74a5a2014-04-29 07:58:41 +00003168 void releaseTopNode(SUnit *SU) override {
Andrew Trick8823dec2012-03-14 04:00:41 +00003169 TopQ.push(SU);
3170 }
Craig Topper9d74a5a2014-04-29 07:58:41 +00003171 void releaseBottomNode(SUnit *SU) override {
Andrew Trick8823dec2012-03-14 04:00:41 +00003172 BottomQ.push(SU);
Andrew Tricke77e84e2012-01-13 06:30:30 +00003173 }
3174};
3175} // namespace
3176
Andrew Trick02a80da2012-03-08 01:41:12 +00003177static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
Andrew Trick8823dec2012-03-14 04:00:41 +00003178 bool Alternate = !ForceTopDown && !ForceBottomUp;
3179 bool TopDown = !ForceBottomUp;
Benjamin Kramer05e7a842012-03-14 11:26:37 +00003180 assert((TopDown || !ForceTopDown) &&
Andrew Trick8823dec2012-03-14 04:00:41 +00003181 "-misched-topdown incompatible with -misched-bottomup");
David Blaikie422b93d2014-04-21 20:32:32 +00003182 return new ScheduleDAGMILive(C, make_unique<InstructionShuffler>(Alternate, TopDown));
Andrew Tricke77e84e2012-01-13 06:30:30 +00003183}
Andrew Trick8823dec2012-03-14 04:00:41 +00003184static MachineSchedRegistry ShufflerRegistry(
3185 "shuffle", "Shuffle machine instructions alternating directions",
3186 createInstructionShuffler);
Andrew Tricke77e84e2012-01-13 06:30:30 +00003187#endif // !NDEBUG
Andrew Trickea9fd952013-01-25 07:45:29 +00003188
3189//===----------------------------------------------------------------------===//
Andrew Trickd7f890e2013-12-28 21:56:47 +00003190// GraphWriter support for ScheduleDAGMILive.
Andrew Trickea9fd952013-01-25 07:45:29 +00003191//===----------------------------------------------------------------------===//
3192
3193#ifndef NDEBUG
3194namespace llvm {
3195
3196template<> struct GraphTraits<
3197 ScheduleDAGMI*> : public GraphTraits<ScheduleDAG*> {};
3198
3199template<>
3200struct DOTGraphTraits<ScheduleDAGMI*> : public DefaultDOTGraphTraits {
3201
3202 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
3203
3204 static std::string getGraphName(const ScheduleDAG *G) {
3205 return G->MF.getName();
3206 }
3207
3208 static bool renderGraphFromBottomUp() {
3209 return true;
3210 }
3211
3212 static bool isNodeHidden(const SUnit *Node) {
Andrew Trick856ecd92013-09-04 21:00:18 +00003213 return (Node->Preds.size() > 10 || Node->Succs.size() > 10);
Andrew Trickea9fd952013-01-25 07:45:29 +00003214 }
3215
3216 static bool hasNodeAddressLabel(const SUnit *Node,
3217 const ScheduleDAG *Graph) {
3218 return false;
3219 }
3220
3221 /// If you want to override the dot attributes printed for a particular
3222 /// edge, override this method.
3223 static std::string getEdgeAttributes(const SUnit *Node,
3224 SUnitIterator EI,
3225 const ScheduleDAG *Graph) {
3226 if (EI.isArtificialDep())
3227 return "color=cyan,style=dashed";
3228 if (EI.isCtrlDep())
3229 return "color=blue,style=dashed";
3230 return "";
3231 }
3232
3233 static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) {
3234 std::string Str;
3235 raw_string_ostream SS(Str);
Andrew Trickd7f890e2013-12-28 21:56:47 +00003236 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3237 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
Craig Topperc0196b12014-04-14 00:51:57 +00003238 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
Andrew Trick7609b7d2013-09-06 17:32:42 +00003239 SS << "SU:" << SU->NodeNum;
3240 if (DFS)
3241 SS << " I:" << DFS->getNumInstrs(SU);
Andrew Trickea9fd952013-01-25 07:45:29 +00003242 return SS.str();
3243 }
3244 static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G) {
3245 return G->getGraphNodeLabel(SU);
3246 }
3247
Andrew Trickd7f890e2013-12-28 21:56:47 +00003248 static std::string getNodeAttributes(const SUnit *N, const ScheduleDAG *G) {
Andrew Trickea9fd952013-01-25 07:45:29 +00003249 std::string Str("shape=Mrecord");
Andrew Trickd7f890e2013-12-28 21:56:47 +00003250 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3251 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
Craig Topperc0196b12014-04-14 00:51:57 +00003252 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
Andrew Trickea9fd952013-01-25 07:45:29 +00003253 if (DFS) {
3254 Str += ",style=filled,fillcolor=\"#";
3255 Str += DOT::getColorString(DFS->getSubtreeID(N));
3256 Str += '"';
3257 }
3258 return Str;
3259 }
3260};
3261} // namespace llvm
3262#endif // NDEBUG
3263
3264/// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
3265/// rendered using 'dot'.
3266///
3267void ScheduleDAGMI::viewGraph(const Twine &Name, const Twine &Title) {
3268#ifndef NDEBUG
3269 ViewGraph(this, Name, false, Title);
3270#else
3271 errs() << "ScheduleDAGMI::viewGraph is only available in debug builds on "
3272 << "systems with Graphviz or gv!\n";
3273#endif // NDEBUG
3274}
3275
3276/// Out-of-line implementation with no arguments is handy for gdb.
3277void ScheduleDAGMI::viewGraph() {
3278 viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName());
3279}