blob: 927a03612de30b828b5c5943748eee855db3988e [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
Andrew Tricke77e84e2012-01-13 06:30:30 +000033using namespace llvm;
34
Chandler Carruth1b9dde02014-04-22 02:02:50 +000035#define DEBUG_TYPE "misched"
36
Andrew Trick7a8e1002012-09-11 00:39:15 +000037namespace llvm {
38cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
39 cl::desc("Force top-down list scheduling"));
40cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
41 cl::desc("Force bottom-up list scheduling"));
Gerolf Hoflehnerb5220dc2014-08-07 21:49:44 +000042cl::opt<bool>
43DumpCriticalPathLength("misched-dcpl", cl::Hidden,
44 cl::desc("Print critical path length to stdout"));
Andrew Trick7a8e1002012-09-11 00:39:15 +000045}
Andrew Trick8823dec2012-03-14 04:00:41 +000046
Andrew Tricka5f19562012-03-07 00:18:25 +000047#ifndef NDEBUG
48static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
49 cl::desc("Pop up a window to show MISched dags after they are processed"));
Lang Hamesdd98c492012-03-19 18:38:38 +000050
Matthias Braund78ee542015-09-17 21:09:59 +000051/// In some situations a few uninteresting nodes depend on nearly all other
52/// nodes in the graph, provide a cutoff to hide them.
53static cl::opt<unsigned> ViewMISchedCutoff("view-misched-cutoff", cl::Hidden,
54 cl::desc("Hide nodes with more predecessor/successor than cutoff"));
55
Lang Hamesdd98c492012-03-19 18:38:38 +000056static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
57 cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
Andrew Trick33e05d72013-12-28 21:57:02 +000058
59static cl::opt<std::string> SchedOnlyFunc("misched-only-func", cl::Hidden,
60 cl::desc("Only schedule this function"));
61static cl::opt<unsigned> SchedOnlyBlock("misched-only-block", cl::Hidden,
62 cl::desc("Only schedule this MBB#"));
Andrew Tricka5f19562012-03-07 00:18:25 +000063#else
64static bool ViewMISchedDAGs = false;
65#endif // NDEBUG
66
Matthias Braun6493bc22016-04-22 19:09:17 +000067/// Avoid quadratic complexity in unusually large basic blocks by limiting the
68/// size of the ready lists.
69static cl::opt<unsigned> ReadyListLimit("misched-limit", cl::Hidden,
70 cl::desc("Limit ready list to N instructions"), cl::init(256));
71
Andrew Trickb6e74712013-09-04 20:59:59 +000072static cl::opt<bool> EnableRegPressure("misched-regpressure", cl::Hidden,
73 cl::desc("Enable register pressure scheduling."), cl::init(true));
74
Andrew Trickc01b0042013-08-23 17:48:43 +000075static cl::opt<bool> EnableCyclicPath("misched-cyclicpath", cl::Hidden,
Andrew Trick6c88b352013-09-09 23:31:14 +000076 cl::desc("Enable cyclic critical path analysis."), cl::init(true));
Andrew Trickc01b0042013-08-23 17:48:43 +000077
Jun Bum Lim4c5bd582016-04-15 14:58:38 +000078static cl::opt<bool> EnableMemOpCluster("misched-cluster", cl::Hidden,
79 cl::desc("Enable memop clustering."),
80 cl::init(true));
Andrew Tricka7714a02012-11-12 19:40:10 +000081
Andrew Trick263280242012-11-12 19:52:20 +000082// Experimental heuristics
83static cl::opt<bool> EnableMacroFusion("misched-fusion", cl::Hidden,
Andrew Trick108c88c2012-11-13 08:47:29 +000084 cl::desc("Enable scheduling for macro fusion."), cl::init(true));
Andrew Trick263280242012-11-12 19:52:20 +000085
Andrew Trick48f2a722013-03-08 05:40:34 +000086static cl::opt<bool> VerifyScheduling("verify-misched", cl::Hidden,
87 cl::desc("Verify machine instrs before and after machine scheduling"));
88
Andrew Trick44f750a2013-01-25 04:01:04 +000089// DAG subtrees must have at least this many nodes.
90static const unsigned MinSubtreeSize = 8;
91
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +000092// Pin the vtables to this file.
93void MachineSchedStrategy::anchor() {}
94void ScheduleDAGMutation::anchor() {}
95
Andrew Trick63440872012-01-14 02:17:06 +000096//===----------------------------------------------------------------------===//
97// Machine Instruction Scheduling Pass and Registry
98//===----------------------------------------------------------------------===//
99
Andrew Trick4d4b5462012-04-24 20:36:19 +0000100MachineSchedContext::MachineSchedContext():
Craig Topperc0196b12014-04-14 00:51:57 +0000101 MF(nullptr), MLI(nullptr), MDT(nullptr), PassConfig(nullptr), AA(nullptr), LIS(nullptr) {
Andrew Trick4d4b5462012-04-24 20:36:19 +0000102 RegClassInfo = new RegisterClassInfo();
103}
104
105MachineSchedContext::~MachineSchedContext() {
106 delete RegClassInfo;
107}
108
Andrew Tricke77e84e2012-01-13 06:30:30 +0000109namespace {
Andrew Trickd7f890e2013-12-28 21:56:47 +0000110/// Base class for a machine scheduler class that can run at any point.
111class MachineSchedulerBase : public MachineSchedContext,
112 public MachineFunctionPass {
113public:
114 MachineSchedulerBase(char &ID): MachineFunctionPass(ID) {}
115
Craig Topperc0196b12014-04-14 00:51:57 +0000116 void print(raw_ostream &O, const Module* = nullptr) const override;
Andrew Trickd7f890e2013-12-28 21:56:47 +0000117
118protected:
Matthias Braun93563e72015-11-03 01:53:29 +0000119 void scheduleRegions(ScheduleDAGInstrs &Scheduler, bool FixKillFlags);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000120};
121
Andrew Tricke1c034f2012-01-17 06:55:03 +0000122/// MachineScheduler runs after coalescing and before register allocation.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000123class MachineScheduler : public MachineSchedulerBase {
Andrew Tricke77e84e2012-01-13 06:30:30 +0000124public:
Andrew Tricke1c034f2012-01-17 06:55:03 +0000125 MachineScheduler();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000126
Craig Topper4584cd52014-03-07 09:26:03 +0000127 void getAnalysisUsage(AnalysisUsage &AU) const override;
Andrew Tricke77e84e2012-01-13 06:30:30 +0000128
Craig Topper4584cd52014-03-07 09:26:03 +0000129 bool runOnMachineFunction(MachineFunction&) override;
Andrew Tricke77e84e2012-01-13 06:30:30 +0000130
Andrew Tricke77e84e2012-01-13 06:30:30 +0000131 static char ID; // Class identification, replacement for typeinfo
Andrew Trick978674b2013-09-20 05:14:41 +0000132
133protected:
134 ScheduleDAGInstrs *createMachineScheduler();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000135};
Andrew Trick17080b92013-12-28 21:56:51 +0000136
137/// PostMachineScheduler runs after shortly before code emission.
138class PostMachineScheduler : public MachineSchedulerBase {
139public:
140 PostMachineScheduler();
141
Craig Topper4584cd52014-03-07 09:26:03 +0000142 void getAnalysisUsage(AnalysisUsage &AU) const override;
Andrew Trick17080b92013-12-28 21:56:51 +0000143
Craig Topper4584cd52014-03-07 09:26:03 +0000144 bool runOnMachineFunction(MachineFunction&) override;
Andrew Trick17080b92013-12-28 21:56:51 +0000145
146 static char ID; // Class identification, replacement for typeinfo
147
148protected:
149 ScheduleDAGInstrs *createPostMachineScheduler();
150};
Andrew Tricke77e84e2012-01-13 06:30:30 +0000151} // namespace
152
Andrew Tricke1c034f2012-01-17 06:55:03 +0000153char MachineScheduler::ID = 0;
Andrew Tricke77e84e2012-01-13 06:30:30 +0000154
Andrew Tricke1c034f2012-01-17 06:55:03 +0000155char &llvm::MachineSchedulerID = MachineScheduler::ID;
Andrew Tricke77e84e2012-01-13 06:30:30 +0000156
Akira Hatanaka7ba78302014-12-13 04:52:04 +0000157INITIALIZE_PASS_BEGIN(MachineScheduler, "machine-scheduler",
Andrew Tricke77e84e2012-01-13 06:30:30 +0000158 "Machine Instruction Scheduler", false, false)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000159INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Andrew Tricke77e84e2012-01-13 06:30:30 +0000160INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
161INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
Akira Hatanaka7ba78302014-12-13 04:52:04 +0000162INITIALIZE_PASS_END(MachineScheduler, "machine-scheduler",
Andrew Tricke77e84e2012-01-13 06:30:30 +0000163 "Machine Instruction Scheduler", false, false)
164
Andrew Tricke1c034f2012-01-17 06:55:03 +0000165MachineScheduler::MachineScheduler()
Andrew Trickd7f890e2013-12-28 21:56:47 +0000166: MachineSchedulerBase(ID) {
Andrew Tricke1c034f2012-01-17 06:55:03 +0000167 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Andrew Tricke77e84e2012-01-13 06:30:30 +0000168}
169
Andrew Tricke1c034f2012-01-17 06:55:03 +0000170void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
Andrew Tricke77e84e2012-01-13 06:30:30 +0000171 AU.setPreservesCFG();
172 AU.addRequiredID(MachineDominatorsID);
173 AU.addRequired<MachineLoopInfo>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000174 AU.addRequired<AAResultsWrapperPass>();
Andrew Trick45300682012-03-09 00:52:20 +0000175 AU.addRequired<TargetPassConfig>();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000176 AU.addRequired<SlotIndexes>();
177 AU.addPreserved<SlotIndexes>();
178 AU.addRequired<LiveIntervals>();
179 AU.addPreserved<LiveIntervals>();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000180 MachineFunctionPass::getAnalysisUsage(AU);
181}
182
Andrew Trick17080b92013-12-28 21:56:51 +0000183char PostMachineScheduler::ID = 0;
184
185char &llvm::PostMachineSchedulerID = PostMachineScheduler::ID;
186
187INITIALIZE_PASS(PostMachineScheduler, "postmisched",
Saleem Abdulrasool7230b372013-12-28 22:47:55 +0000188 "PostRA Machine Instruction Scheduler", false, false)
Andrew Trick17080b92013-12-28 21:56:51 +0000189
190PostMachineScheduler::PostMachineScheduler()
191: MachineSchedulerBase(ID) {
192 initializePostMachineSchedulerPass(*PassRegistry::getPassRegistry());
193}
194
195void PostMachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
196 AU.setPreservesCFG();
197 AU.addRequiredID(MachineDominatorsID);
198 AU.addRequired<MachineLoopInfo>();
199 AU.addRequired<TargetPassConfig>();
200 MachineFunctionPass::getAnalysisUsage(AU);
201}
202
Andrew Tricke77e84e2012-01-13 06:30:30 +0000203MachinePassRegistry MachineSchedRegistry::Registry;
204
Andrew Trick45300682012-03-09 00:52:20 +0000205/// A dummy default scheduler factory indicates whether the scheduler
206/// is overridden on the command line.
207static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
Craig Topperc0196b12014-04-14 00:51:57 +0000208 return nullptr;
Andrew Trick45300682012-03-09 00:52:20 +0000209}
Andrew Tricke77e84e2012-01-13 06:30:30 +0000210
211/// MachineSchedOpt allows command line selection of the scheduler.
212static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
213 RegisterPassParser<MachineSchedRegistry> >
214MachineSchedOpt("misched",
Andrew Trick45300682012-03-09 00:52:20 +0000215 cl::init(&useDefaultMachineSched), cl::Hidden,
Andrew Tricke77e84e2012-01-13 06:30:30 +0000216 cl::desc("Machine instruction scheduler to use"));
217
Andrew Trick45300682012-03-09 00:52:20 +0000218static MachineSchedRegistry
Andrew Trick8823dec2012-03-14 04:00:41 +0000219DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
Andrew Trick45300682012-03-09 00:52:20 +0000220 useDefaultMachineSched);
221
Eric Christopher5f141b02015-03-11 22:56:10 +0000222static cl::opt<bool> EnableMachineSched(
223 "enable-misched",
224 cl::desc("Enable the machine instruction scheduling pass."), cl::init(true),
225 cl::Hidden);
226
Chad Rosier816a1ab2016-01-20 23:08:32 +0000227static cl::opt<bool> EnablePostRAMachineSched(
228 "enable-post-misched",
229 cl::desc("Enable the post-ra machine instruction scheduling pass."),
230 cl::init(true), cl::Hidden);
231
Andrew Trick8823dec2012-03-14 04:00:41 +0000232/// Forward declare the standard machine scheduler. This will be used as the
Andrew Trick45300682012-03-09 00:52:20 +0000233/// default scheduler if the target does not set a default.
Andrew Trickd14d7c22013-12-28 21:56:57 +0000234static ScheduleDAGInstrs *createGenericSchedLive(MachineSchedContext *C);
235static ScheduleDAGInstrs *createGenericSchedPostRA(MachineSchedContext *C);
Andrew Trickcc45a282012-04-24 18:04:34 +0000236
237/// Decrement this iterator until reaching the top or a non-debug instr.
Andrew Trick2bc74c22013-08-30 04:36:57 +0000238static MachineBasicBlock::const_iterator
239priorNonDebug(MachineBasicBlock::const_iterator I,
240 MachineBasicBlock::const_iterator Beg) {
Andrew Trickcc45a282012-04-24 18:04:34 +0000241 assert(I != Beg && "reached the top of the region, cannot decrement");
242 while (--I != Beg) {
243 if (!I->isDebugValue())
244 break;
245 }
246 return I;
247}
248
Andrew Trick2bc74c22013-08-30 04:36:57 +0000249/// Non-const version.
250static MachineBasicBlock::iterator
251priorNonDebug(MachineBasicBlock::iterator I,
252 MachineBasicBlock::const_iterator Beg) {
253 return const_cast<MachineInstr*>(
254 &*priorNonDebug(MachineBasicBlock::const_iterator(I), Beg));
255}
256
Andrew Trickcc45a282012-04-24 18:04:34 +0000257/// If this iterator is a debug value, increment until reaching the End or a
258/// non-debug instruction.
Andrew Trick2c4f8b72013-08-31 05:17:58 +0000259static MachineBasicBlock::const_iterator
260nextIfDebug(MachineBasicBlock::const_iterator I,
261 MachineBasicBlock::const_iterator End) {
Andrew Trick463b2f12012-05-17 18:35:03 +0000262 for(; I != End; ++I) {
Andrew Trickcc45a282012-04-24 18:04:34 +0000263 if (!I->isDebugValue())
264 break;
265 }
266 return I;
267}
268
Andrew Trick2c4f8b72013-08-31 05:17:58 +0000269/// Non-const version.
270static MachineBasicBlock::iterator
271nextIfDebug(MachineBasicBlock::iterator I,
272 MachineBasicBlock::const_iterator End) {
273 // Cast the return value to nonconst MachineInstr, then cast to an
274 // instr_iterator, which does not check for null, finally return a
275 // bundle_iterator.
276 return MachineBasicBlock::instr_iterator(
277 const_cast<MachineInstr*>(
278 &*nextIfDebug(MachineBasicBlock::const_iterator(I), End)));
279}
280
Andrew Trickdc4c1ad2013-09-24 17:11:19 +0000281/// Instantiate a ScheduleDAGInstrs that will be owned by the caller.
Andrew Trick978674b2013-09-20 05:14:41 +0000282ScheduleDAGInstrs *MachineScheduler::createMachineScheduler() {
283 // Select the scheduler, or set the default.
284 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
285 if (Ctor != useDefaultMachineSched)
286 return Ctor(this);
287
288 // Get the default scheduler set by the target for this function.
289 ScheduleDAGInstrs *Scheduler = PassConfig->createMachineScheduler(this);
290 if (Scheduler)
291 return Scheduler;
292
293 // Default to GenericScheduler.
Andrew Trickd14d7c22013-12-28 21:56:57 +0000294 return createGenericSchedLive(this);
Andrew Trick978674b2013-09-20 05:14:41 +0000295}
296
Andrew Trick17080b92013-12-28 21:56:51 +0000297/// Instantiate a ScheduleDAGInstrs for PostRA scheduling that will be owned by
298/// the caller. We don't have a command line option to override the postRA
299/// scheduler. The Target must configure it.
300ScheduleDAGInstrs *PostMachineScheduler::createPostMachineScheduler() {
301 // Get the postRA scheduler set by the target for this function.
302 ScheduleDAGInstrs *Scheduler = PassConfig->createPostMachineScheduler(this);
303 if (Scheduler)
304 return Scheduler;
305
306 // Default to GenericScheduler.
Andrew Trickd14d7c22013-12-28 21:56:57 +0000307 return createGenericSchedPostRA(this);
Andrew Trick17080b92013-12-28 21:56:51 +0000308}
309
Andrew Trick72515be2012-03-14 04:00:38 +0000310/// Top-level MachineScheduler pass driver.
311///
312/// Visit blocks in function order. Divide each block into scheduling regions
Andrew Trick8823dec2012-03-14 04:00:41 +0000313/// and visit them bottom-up. Visiting regions bottom-up is not required, but is
314/// consistent with the DAG builder, which traverses the interior of the
315/// scheduling regions bottom-up.
Andrew Trick72515be2012-03-14 04:00:38 +0000316///
317/// This design avoids exposing scheduling boundaries to the DAG builder,
Andrew Trick8823dec2012-03-14 04:00:41 +0000318/// simplifying the DAG builder's support for "special" target instructions.
319/// At the same time the design allows target schedulers to operate across
Andrew Trick72515be2012-03-14 04:00:38 +0000320/// scheduling boundaries, for example to bundle the boudary instructions
321/// without reordering them. This creates complexity, because the target
322/// scheduler must update the RegionBegin and RegionEnd positions cached by
323/// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
324/// design would be to split blocks at scheduling boundaries, but LLVM has a
325/// general bias against block splitting purely for implementation simplicity.
Andrew Tricke1c034f2012-01-17 06:55:03 +0000326bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
Vedant Kumar6013f452016-04-22 06:51:37 +0000327 if (skipOptnoneFunction(*mf.getFunction()))
Chad Rosier6338d7c2016-01-20 22:38:25 +0000328 return false;
329
Eric Christopher5f141b02015-03-11 22:56:10 +0000330 if (EnableMachineSched.getNumOccurrences()) {
331 if (!EnableMachineSched)
332 return false;
333 } else if (!mf.getSubtarget().enableMachineScheduler())
334 return false;
335
Matthias Braundc7580a2015-10-29 03:57:28 +0000336 DEBUG(dbgs() << "Before MISched:\n"; mf.print(dbgs()));
Andrew Trickc5d70082012-05-10 21:06:21 +0000337
Andrew Tricke77e84e2012-01-13 06:30:30 +0000338 // Initialize the context of the pass.
339 MF = &mf;
340 MLI = &getAnalysis<MachineLoopInfo>();
341 MDT = &getAnalysis<MachineDominatorTree>();
Andrew Trick45300682012-03-09 00:52:20 +0000342 PassConfig = &getAnalysis<TargetPassConfig>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000343 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Andrew Trick02a80da2012-03-08 01:41:12 +0000344
Lang Hamesad33d5a2012-01-27 22:36:19 +0000345 LIS = &getAnalysis<LiveIntervals>();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000346
Andrew Trick48f2a722013-03-08 05:40:34 +0000347 if (VerifyScheduling) {
Andrew Trick97064962013-07-25 07:26:26 +0000348 DEBUG(LIS->dump());
Andrew Trick48f2a722013-03-08 05:40:34 +0000349 MF->verify(this, "Before machine scheduling.");
350 }
Andrew Trick4d4b5462012-04-24 20:36:19 +0000351 RegClassInfo->runOnMachineFunction(*MF);
Andrew Trick88639922012-04-24 17:56:43 +0000352
Andrew Trick978674b2013-09-20 05:14:41 +0000353 // Instantiate the selected scheduler for this target, function, and
354 // optimization level.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000355 std::unique_ptr<ScheduleDAGInstrs> Scheduler(createMachineScheduler());
Matthias Braun93563e72015-11-03 01:53:29 +0000356 scheduleRegions(*Scheduler, false);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000357
358 DEBUG(LIS->dump());
359 if (VerifyScheduling)
360 MF->verify(this, "After machine scheduling.");
361 return true;
362}
363
Andrew Trick17080b92013-12-28 21:56:51 +0000364bool PostMachineScheduler::runOnMachineFunction(MachineFunction &mf) {
Vedant Kumar6013f452016-04-22 06:51:37 +0000365 if (skipOptnoneFunction(*mf.getFunction()))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000366 return false;
367
Chad Rosier816a1ab2016-01-20 23:08:32 +0000368 if (EnablePostRAMachineSched.getNumOccurrences()) {
369 if (!EnablePostRAMachineSched)
370 return false;
371 } else if (!mf.getSubtarget().enablePostRAScheduler()) {
Andrew Trick8d2ee372014-06-04 07:06:27 +0000372 DEBUG(dbgs() << "Subtarget disables post-MI-sched.\n");
373 return false;
374 }
Andrew Trick17080b92013-12-28 21:56:51 +0000375 DEBUG(dbgs() << "Before post-MI-sched:\n"; mf.print(dbgs()));
376
377 // Initialize the context of the pass.
378 MF = &mf;
379 PassConfig = &getAnalysis<TargetPassConfig>();
380
381 if (VerifyScheduling)
382 MF->verify(this, "Before post machine scheduling.");
383
384 // Instantiate the selected scheduler for this target, function, and
385 // optimization level.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000386 std::unique_ptr<ScheduleDAGInstrs> Scheduler(createPostMachineScheduler());
Matthias Braun93563e72015-11-03 01:53:29 +0000387 scheduleRegions(*Scheduler, true);
Andrew Trick17080b92013-12-28 21:56:51 +0000388
389 if (VerifyScheduling)
390 MF->verify(this, "After post machine scheduling.");
391 return true;
392}
393
Andrew Trickd14d7c22013-12-28 21:56:57 +0000394/// Return true of the given instruction should not be included in a scheduling
395/// region.
396///
397/// MachineScheduler does not currently support scheduling across calls. To
398/// handle calls, the DAG builder needs to be modified to create register
399/// anti/output dependencies on the registers clobbered by the call's regmask
400/// operand. In PreRA scheduling, the stack pointer adjustment already prevents
401/// scheduling across calls. In PostRA scheduling, we need the isCall to enforce
402/// the boundary, but there would be no benefit to postRA scheduling across
403/// calls this late anyway.
404static bool isSchedBoundary(MachineBasicBlock::iterator MI,
405 MachineBasicBlock *MBB,
406 MachineFunction *MF,
Matthias Braun93563e72015-11-03 01:53:29 +0000407 const TargetInstrInfo *TII) {
Andrew Trickd14d7c22013-12-28 21:56:57 +0000408 return MI->isCall() || TII->isSchedulingBoundary(MI, MBB, *MF);
409}
410
Andrew Trickd7f890e2013-12-28 21:56:47 +0000411/// Main driver for both MachineScheduler and PostMachineScheduler.
Matthias Braun93563e72015-11-03 01:53:29 +0000412void MachineSchedulerBase::scheduleRegions(ScheduleDAGInstrs &Scheduler,
413 bool FixKillFlags) {
Eric Christopherfc6de422014-08-05 02:39:49 +0000414 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000415
416 // Visit all machine basic blocks.
Andrew Trick88639922012-04-24 17:56:43 +0000417 //
418 // TODO: Visit blocks in global postorder or postorder within the bottom-up
419 // loop tree. Then we can optionally compute global RegPressure.
Andrew Tricke77e84e2012-01-13 06:30:30 +0000420 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
421 MBB != MBBEnd; ++MBB) {
422
Duncan P. N. Exon Smith5ec15682015-10-09 19:40:45 +0000423 Scheduler.startBlock(&*MBB);
Andrew Trickedfe2ec2012-03-09 08:02:51 +0000424
Andrew Trick33e05d72013-12-28 21:57:02 +0000425#ifndef NDEBUG
426 if (SchedOnlyFunc.getNumOccurrences() && SchedOnlyFunc != MF->getName())
427 continue;
428 if (SchedOnlyBlock.getNumOccurrences()
429 && (int)SchedOnlyBlock != MBB->getNumber())
430 continue;
431#endif
432
Andrew Trick7e120f42012-01-14 02:17:09 +0000433 // Break the block into scheduling regions [I, RegionEnd), and schedule each
Sylvestre Ledru35521e22012-07-23 08:51:15 +0000434 // region as soon as it is discovered. RegionEnd points the scheduling
Andrew Trickaf1bee72012-03-09 22:34:56 +0000435 // boundary at the bottom of the region. The DAG does not include RegionEnd,
436 // but the region does (i.e. the next RegionEnd is above the previous
437 // RegionBegin). If the current block has no terminator then RegionEnd ==
438 // MBB->end() for the bottom region.
439 //
440 // The Scheduler may insert instructions during either schedule() or
441 // exitRegion(), even for empty regions. So the local iterators 'I' and
442 // 'RegionEnd' are invalid across these calls.
Andrew Trickd14d7c22013-12-28 21:56:57 +0000443 //
444 // MBB::size() uses instr_iterator to count. Here we need a bundle to count
445 // as a single instruction.
446 unsigned RemainingInstrs = std::distance(MBB->begin(), MBB->end());
Andrew Tricka21daf72012-03-09 03:46:39 +0000447 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
Andrew Trickd7f890e2013-12-28 21:56:47 +0000448 RegionEnd != MBB->begin(); RegionEnd = Scheduler.begin()) {
Andrew Trick88639922012-04-24 17:56:43 +0000449
Andrew Trickedfe2ec2012-03-09 08:02:51 +0000450 // Avoid decrementing RegionEnd for blocks with no terminator.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000451 if (RegionEnd != MBB->end() ||
Matthias Braun93563e72015-11-03 01:53:29 +0000452 isSchedBoundary(&*std::prev(RegionEnd), &*MBB, MF, TII)) {
Andrew Trickedfe2ec2012-03-09 08:02:51 +0000453 --RegionEnd;
454 // Count the boundary instruction.
Andrew Trick4d1fa712012-11-06 07:10:34 +0000455 --RemainingInstrs;
Andrew Trickedfe2ec2012-03-09 08:02:51 +0000456 }
457
Andrew Trick7e120f42012-01-14 02:17:09 +0000458 // The next region starts above the previous region. Look backward in the
459 // instruction stream until we find the nearest boundary.
Andrew Tricka53e1012013-08-23 17:48:33 +0000460 unsigned NumRegionInstrs = 0;
Andrew Trick7e120f42012-01-14 02:17:09 +0000461 MachineBasicBlock::iterator I = RegionEnd;
Andrea Di Biagiod65fd9f2014-12-12 15:09:58 +0000462 for(;I != MBB->begin(); --I, --RemainingInstrs) {
Matthias Braun93563e72015-11-03 01:53:29 +0000463 if (isSchedBoundary(&*std::prev(I), &*MBB, MF, TII))
Andrew Trick7e120f42012-01-14 02:17:09 +0000464 break;
Andrea Di Biagiod65fd9f2014-12-12 15:09:58 +0000465 if (!I->isDebugValue())
466 ++NumRegionInstrs;
Andrew Trick7e120f42012-01-14 02:17:09 +0000467 }
Andrew Trick60cf03e2012-03-07 05:21:52 +0000468 // Notify the scheduler of the region, even if we may skip scheduling
469 // it. Perhaps it still needs to be bundled.
Duncan P. N. Exon Smith5ec15682015-10-09 19:40:45 +0000470 Scheduler.enterRegion(&*MBB, I, RegionEnd, NumRegionInstrs);
Andrew Trick60cf03e2012-03-07 05:21:52 +0000471
472 // Skip empty scheduling regions (0 or 1 schedulable instructions).
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000473 if (I == RegionEnd || I == std::prev(RegionEnd)) {
Andrew Trick60cf03e2012-03-07 05:21:52 +0000474 // Close the current region. Bundle the terminator if needed.
Andrew Trickaf1bee72012-03-09 22:34:56 +0000475 // This invalidates 'RegionEnd' and 'I'.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000476 Scheduler.exitRegion();
Andrew Trick7ccdc5c2012-01-17 06:55:07 +0000477 continue;
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000478 }
Matthias Braun93563e72015-11-03 01:53:29 +0000479 DEBUG(dbgs() << "********** MI Scheduling **********\n");
Craig Toppera538d832012-08-22 06:07:19 +0000480 DEBUG(dbgs() << MF->getName()
Andrew Trick54b2ce32013-01-25 07:45:31 +0000481 << ":BB#" << MBB->getNumber() << " " << MBB->getName()
482 << "\n From: " << *I << " To: ";
Andrew Tricke57583a2012-02-08 02:17:21 +0000483 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
484 else dbgs() << "End";
Andrew Tricka53e1012013-08-23 17:48:33 +0000485 dbgs() << " RegionInstrs: " << NumRegionInstrs
486 << " Remaining: " << RemainingInstrs << "\n");
Gerolf Hoflehnerb5220dc2014-08-07 21:49:44 +0000487 if (DumpCriticalPathLength) {
488 errs() << MF->getName();
489 errs() << ":BB# " << MBB->getNumber();
490 errs() << " " << MBB->getName() << " \n";
491 }
Andrew Trick7ccdc5c2012-01-17 06:55:07 +0000492
Andrew Trick1c0ec452012-03-09 03:46:42 +0000493 // Schedule a region: possibly reorder instructions.
Andrew Trickaf1bee72012-03-09 22:34:56 +0000494 // This invalidates 'RegionEnd' and 'I'.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000495 Scheduler.schedule();
Andrew Trick1c0ec452012-03-09 03:46:42 +0000496
497 // Close the current region.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000498 Scheduler.exitRegion();
Andrew Trick60cf03e2012-03-07 05:21:52 +0000499
500 // Scheduling has invalidated the current iterator 'I'. Ask the
501 // scheduler for the top of it's scheduled region.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000502 RegionEnd = Scheduler.begin();
Andrew Trick7e120f42012-01-14 02:17:09 +0000503 }
Andrew Trick4d1fa712012-11-06 07:10:34 +0000504 assert(RemainingInstrs == 0 && "Instruction count mismatch!");
Andrew Trickd7f890e2013-12-28 21:56:47 +0000505 Scheduler.finishBlock();
Matthias Braun93563e72015-11-03 01:53:29 +0000506 // FIXME: Ideally, no further passes should rely on kill flags. However,
507 // thumb2 size reduction is currently an exception, so the PostMIScheduler
508 // needs to do this.
509 if (FixKillFlags)
510 Scheduler.fixupKills(&*MBB);
Andrew Tricke77e84e2012-01-13 06:30:30 +0000511 }
Andrew Trickd7f890e2013-12-28 21:56:47 +0000512 Scheduler.finalizeSchedule();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000513}
514
Andrew Trickd7f890e2013-12-28 21:56:47 +0000515void MachineSchedulerBase::print(raw_ostream &O, const Module* m) const {
Andrew Tricke77e84e2012-01-13 06:30:30 +0000516 // unimplemented
517}
518
Alp Tokerd8d510a2014-07-01 21:19:13 +0000519LLVM_DUMP_METHOD
Andrew Trick7a8e1002012-09-11 00:39:15 +0000520void ReadyQueue::dump() {
James Y Knighte72b0db2015-09-18 18:52:20 +0000521 dbgs() << "Queue " << Name << ": ";
Andrew Trick7a8e1002012-09-11 00:39:15 +0000522 for (unsigned i = 0, e = Queue.size(); i < e; ++i)
523 dbgs() << Queue[i]->NodeNum << " ";
524 dbgs() << "\n";
525}
Andrew Trick8823dec2012-03-14 04:00:41 +0000526
527//===----------------------------------------------------------------------===//
Andrew Trickd7f890e2013-12-28 21:56:47 +0000528// ScheduleDAGMI - Basic machine instruction scheduling. This is
529// independent of PreRA/PostRA scheduling and involves no extra book-keeping for
530// virtual registers.
531// ===----------------------------------------------------------------------===/
Andrew Trick8823dec2012-03-14 04:00:41 +0000532
David Blaikie422b93d2014-04-21 20:32:32 +0000533// Provide a vtable anchor.
Andrew Trick44f750a2013-01-25 04:01:04 +0000534ScheduleDAGMI::~ScheduleDAGMI() {
Andrew Trick44f750a2013-01-25 04:01:04 +0000535}
536
Andrew Trick85a1d4c2013-04-24 15:54:43 +0000537bool ScheduleDAGMI::canAddEdge(SUnit *SuccSU, SUnit *PredSU) {
538 return SuccSU == &ExitSU || !Topo.IsReachable(PredSU, SuccSU);
539}
540
Andrew Tricka7714a02012-11-12 19:40:10 +0000541bool ScheduleDAGMI::addEdge(SUnit *SuccSU, const SDep &PredDep) {
Andrew Trick263280242012-11-12 19:52:20 +0000542 if (SuccSU != &ExitSU) {
543 // Do not use WillCreateCycle, it assumes SD scheduling.
544 // If Pred is reachable from Succ, then the edge creates a cycle.
545 if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
546 return false;
547 Topo.AddPred(SuccSU, PredDep.getSUnit());
548 }
Andrew Tricka7714a02012-11-12 19:40:10 +0000549 SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
550 // Return true regardless of whether a new edge needed to be inserted.
551 return true;
552}
553
Andrew Trick02a80da2012-03-08 01:41:12 +0000554/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
555/// NumPredsLeft reaches zero, release the successor node.
Andrew Trick61f1a272012-05-24 22:11:09 +0000556///
557/// FIXME: Adjust SuccSU height based on MinLatency.
Andrew Trick8823dec2012-03-14 04:00:41 +0000558void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
Andrew Trick02a80da2012-03-08 01:41:12 +0000559 SUnit *SuccSU = SuccEdge->getSUnit();
560
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000561 if (SuccEdge->isWeak()) {
562 --SuccSU->WeakPredsLeft;
Andrew Tricka7714a02012-11-12 19:40:10 +0000563 if (SuccEdge->isCluster())
564 NextClusterSucc = SuccSU;
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000565 return;
566 }
Andrew Trick02a80da2012-03-08 01:41:12 +0000567#ifndef NDEBUG
568 if (SuccSU->NumPredsLeft == 0) {
569 dbgs() << "*** Scheduling failed! ***\n";
570 SuccSU->dump(this);
571 dbgs() << " has been released too many times!\n";
Craig Topperc0196b12014-04-14 00:51:57 +0000572 llvm_unreachable(nullptr);
Andrew Trick02a80da2012-03-08 01:41:12 +0000573 }
574#endif
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000575 // SU->TopReadyCycle was set to CurrCycle when it was scheduled. However,
576 // CurrCycle may have advanced since then.
577 if (SuccSU->TopReadyCycle < SU->TopReadyCycle + SuccEdge->getLatency())
578 SuccSU->TopReadyCycle = SU->TopReadyCycle + SuccEdge->getLatency();
579
Andrew Trick02a80da2012-03-08 01:41:12 +0000580 --SuccSU->NumPredsLeft;
581 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
Andrew Trick8823dec2012-03-14 04:00:41 +0000582 SchedImpl->releaseTopNode(SuccSU);
Andrew Trick02a80da2012-03-08 01:41:12 +0000583}
584
585/// releaseSuccessors - Call releaseSucc on each of SU's successors.
Andrew Trick8823dec2012-03-14 04:00:41 +0000586void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
Andrew Trick02a80da2012-03-08 01:41:12 +0000587 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
588 I != E; ++I) {
589 releaseSucc(SU, &*I);
590 }
591}
592
Andrew Trick8823dec2012-03-14 04:00:41 +0000593/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
594/// NumSuccsLeft reaches zero, release the predecessor node.
Andrew Trick61f1a272012-05-24 22:11:09 +0000595///
596/// FIXME: Adjust PredSU height based on MinLatency.
Andrew Trick8823dec2012-03-14 04:00:41 +0000597void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
598 SUnit *PredSU = PredEdge->getSUnit();
599
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000600 if (PredEdge->isWeak()) {
601 --PredSU->WeakSuccsLeft;
Andrew Tricka7714a02012-11-12 19:40:10 +0000602 if (PredEdge->isCluster())
603 NextClusterPred = PredSU;
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000604 return;
605 }
Andrew Trick8823dec2012-03-14 04:00:41 +0000606#ifndef NDEBUG
607 if (PredSU->NumSuccsLeft == 0) {
608 dbgs() << "*** Scheduling failed! ***\n";
609 PredSU->dump(this);
610 dbgs() << " has been released too many times!\n";
Craig Topperc0196b12014-04-14 00:51:57 +0000611 llvm_unreachable(nullptr);
Andrew Trick8823dec2012-03-14 04:00:41 +0000612 }
613#endif
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000614 // SU->BotReadyCycle was set to CurrCycle when it was scheduled. However,
615 // CurrCycle may have advanced since then.
616 if (PredSU->BotReadyCycle < SU->BotReadyCycle + PredEdge->getLatency())
617 PredSU->BotReadyCycle = SU->BotReadyCycle + PredEdge->getLatency();
618
Andrew Trick8823dec2012-03-14 04:00:41 +0000619 --PredSU->NumSuccsLeft;
620 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
621 SchedImpl->releaseBottomNode(PredSU);
622}
623
624/// releasePredecessors - Call releasePred on each of SU's predecessors.
625void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
626 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
627 I != E; ++I) {
628 releasePred(SU, &*I);
629 }
630}
631
Andrew Trickd7f890e2013-12-28 21:56:47 +0000632/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
633/// crossing a scheduling boundary. [begin, end) includes all instructions in
634/// the region, including the boundary itself and single-instruction regions
635/// that don't get scheduled.
636void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
637 MachineBasicBlock::iterator begin,
638 MachineBasicBlock::iterator end,
639 unsigned regioninstrs)
640{
641 ScheduleDAGInstrs::enterRegion(bb, begin, end, regioninstrs);
642
643 SchedImpl->initPolicy(begin, end, regioninstrs);
644}
645
Andrew Tricke833e1c2013-04-13 06:07:40 +0000646/// This is normally called from the main scheduler loop but may also be invoked
647/// by the scheduling strategy to perform additional code motion.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000648void ScheduleDAGMI::moveInstruction(
649 MachineInstr *MI, MachineBasicBlock::iterator InsertPos) {
Andrew Trick463b2f12012-05-17 18:35:03 +0000650 // Advance RegionBegin if the first instruction moves down.
Andrew Trick54f7def2012-03-21 04:12:10 +0000651 if (&*RegionBegin == MI)
Andrew Trick463b2f12012-05-17 18:35:03 +0000652 ++RegionBegin;
653
654 // Update the instruction stream.
Andrew Trick8823dec2012-03-14 04:00:41 +0000655 BB->splice(InsertPos, BB, MI);
Andrew Trick463b2f12012-05-17 18:35:03 +0000656
657 // Update LiveIntervals
Andrew Trickd7f890e2013-12-28 21:56:47 +0000658 if (LIS)
Duncan P. N. Exon Smithbe8f8c42016-02-27 20:14:29 +0000659 LIS->handleMove(*MI, /*UpdateFlags=*/true);
Andrew Trick463b2f12012-05-17 18:35:03 +0000660
661 // Recede RegionBegin if an instruction moves above the first.
Andrew Trick8823dec2012-03-14 04:00:41 +0000662 if (RegionBegin == InsertPos)
663 RegionBegin = MI;
664}
665
Andrew Trickde670c02012-03-21 04:12:07 +0000666bool ScheduleDAGMI::checkSchedLimit() {
667#ifndef NDEBUG
668 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
669 CurrentTop = CurrentBottom;
670 return false;
671 }
672 ++NumInstrsScheduled;
673#endif
674 return true;
675}
676
Andrew Trickd7f890e2013-12-28 21:56:47 +0000677/// Per-region scheduling driver, called back from
678/// MachineScheduler::runOnMachineFunction. This is a simplified driver that
679/// does not consider liveness or register pressure. It is useful for PostRA
680/// scheduling and potentially other custom schedulers.
681void ScheduleDAGMI::schedule() {
James Y Knighte72b0db2015-09-18 18:52:20 +0000682 DEBUG(dbgs() << "ScheduleDAGMI::schedule starting\n");
683 DEBUG(SchedImpl->dumpPolicy());
684
Andrew Trickd7f890e2013-12-28 21:56:47 +0000685 // Build the DAG.
686 buildSchedGraph(AA);
687
688 Topo.InitDAGTopologicalSorting();
689
690 postprocessDAG();
691
692 SmallVector<SUnit*, 8> TopRoots, BotRoots;
693 findRootsAndBiasEdges(TopRoots, BotRoots);
694
695 // Initialize the strategy before modifying the DAG.
696 // This may initialize a DFSResult to be used for queue priority.
697 SchedImpl->initialize(this);
698
699 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
700 SUnits[su].dumpAll(this));
701 if (ViewMISchedDAGs) viewGraph();
702
703 // Initialize ready queues now that the DAG and priority data are finalized.
704 initQueues(TopRoots, BotRoots);
705
706 bool IsTopNode = false;
James Y Knighte72b0db2015-09-18 18:52:20 +0000707 while (true) {
708 DEBUG(dbgs() << "** ScheduleDAGMI::schedule picking next node\n");
709 SUnit *SU = SchedImpl->pickNode(IsTopNode);
710 if (!SU) break;
711
Andrew Trickd7f890e2013-12-28 21:56:47 +0000712 assert(!SU->isScheduled && "Node already scheduled");
713 if (!checkSchedLimit())
714 break;
715
716 MachineInstr *MI = SU->getInstr();
717 if (IsTopNode) {
718 assert(SU->isTopReady() && "node still has unscheduled dependencies");
719 if (&*CurrentTop == MI)
720 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
721 else
722 moveInstruction(MI, CurrentTop);
Matthias Braunb550b762016-04-21 01:54:13 +0000723 } else {
Andrew Trickd7f890e2013-12-28 21:56:47 +0000724 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
725 MachineBasicBlock::iterator priorII =
726 priorNonDebug(CurrentBottom, CurrentTop);
727 if (&*priorII == MI)
728 CurrentBottom = priorII;
729 else {
730 if (&*CurrentTop == MI)
731 CurrentTop = nextIfDebug(++CurrentTop, priorII);
732 moveInstruction(MI, CurrentBottom);
733 CurrentBottom = MI;
734 }
735 }
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000736 // Notify the scheduling strategy before updating the DAG.
Andrew Trick491e34a2014-06-12 22:36:28 +0000737 // This sets the scheduled node's ReadyCycle to CurrCycle. When updateQueues
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000738 // runs, it can then use the accurate ReadyCycle time to determine whether
739 // newly released nodes can move to the readyQ.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000740 SchedImpl->schedNode(SU, IsTopNode);
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000741
742 updateQueues(SU, IsTopNode);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000743 }
744 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
745
746 placeDebugValues();
747
748 DEBUG({
749 unsigned BBNum = begin()->getParent()->getNumber();
750 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
751 dumpSchedule();
752 dbgs() << '\n';
753 });
754}
755
756/// Apply each ScheduleDAGMutation step in order.
757void ScheduleDAGMI::postprocessDAG() {
758 for (unsigned i = 0, e = Mutations.size(); i < e; ++i) {
759 Mutations[i]->apply(this);
760 }
761}
762
763void ScheduleDAGMI::
764findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
765 SmallVectorImpl<SUnit*> &BotRoots) {
766 for (std::vector<SUnit>::iterator
767 I = SUnits.begin(), E = SUnits.end(); I != E; ++I) {
768 SUnit *SU = &(*I);
769 assert(!SU->isBoundaryNode() && "Boundary node should not be in SUnits");
770
771 // Order predecessors so DFSResult follows the critical path.
772 SU->biasCriticalPath();
773
774 // A SUnit is ready to top schedule if it has no predecessors.
775 if (!I->NumPredsLeft)
776 TopRoots.push_back(SU);
777 // A SUnit is ready to bottom schedule if it has no successors.
778 if (!I->NumSuccsLeft)
779 BotRoots.push_back(SU);
780 }
781 ExitSU.biasCriticalPath();
782}
783
784/// Identify DAG roots and setup scheduler queues.
785void ScheduleDAGMI::initQueues(ArrayRef<SUnit*> TopRoots,
786 ArrayRef<SUnit*> BotRoots) {
Craig Topperc0196b12014-04-14 00:51:57 +0000787 NextClusterSucc = nullptr;
788 NextClusterPred = nullptr;
Andrew Trickd7f890e2013-12-28 21:56:47 +0000789
790 // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
791 //
792 // Nodes with unreleased weak edges can still be roots.
793 // Release top roots in forward order.
794 for (SmallVectorImpl<SUnit*>::const_iterator
795 I = TopRoots.begin(), E = TopRoots.end(); I != E; ++I) {
796 SchedImpl->releaseTopNode(*I);
797 }
798 // Release bottom roots in reverse order so the higher priority nodes appear
799 // first. This is more natural and slightly more efficient.
800 for (SmallVectorImpl<SUnit*>::const_reverse_iterator
801 I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I) {
802 SchedImpl->releaseBottomNode(*I);
803 }
804
805 releaseSuccessors(&EntrySU);
806 releasePredecessors(&ExitSU);
807
808 SchedImpl->registerRoots();
809
810 // Advance past initial DebugValues.
811 CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
812 CurrentBottom = RegionEnd;
813}
814
815/// Update scheduler queues after scheduling an instruction.
816void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
817 // Release dependent instructions for scheduling.
818 if (IsTopNode)
819 releaseSuccessors(SU);
820 else
821 releasePredecessors(SU);
822
823 SU->isScheduled = true;
824}
825
826/// Reinsert any remaining debug_values, just like the PostRA scheduler.
827void ScheduleDAGMI::placeDebugValues() {
828 // If first instruction was a DBG_VALUE then put it back.
829 if (FirstDbgValue) {
830 BB->splice(RegionBegin, BB, FirstDbgValue);
831 RegionBegin = FirstDbgValue;
832 }
833
834 for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
835 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000836 std::pair<MachineInstr *, MachineInstr *> P = *std::prev(DI);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000837 MachineInstr *DbgValue = P.first;
838 MachineBasicBlock::iterator OrigPrevMI = P.second;
839 if (&*RegionBegin == DbgValue)
840 ++RegionBegin;
841 BB->splice(++OrigPrevMI, BB, DbgValue);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000842 if (OrigPrevMI == std::prev(RegionEnd))
Andrew Trickd7f890e2013-12-28 21:56:47 +0000843 RegionEnd = DbgValue;
844 }
845 DbgValues.clear();
Craig Topperc0196b12014-04-14 00:51:57 +0000846 FirstDbgValue = nullptr;
Andrew Trickd7f890e2013-12-28 21:56:47 +0000847}
848
849#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
850void ScheduleDAGMI::dumpSchedule() const {
851 for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
852 if (SUnit *SU = getSUnit(&(*MI)))
853 SU->dump(this);
854 else
855 dbgs() << "Missing SUnit\n";
856 }
857}
858#endif
859
860//===----------------------------------------------------------------------===//
861// ScheduleDAGMILive - Base class for MachineInstr scheduling with LiveIntervals
862// preservation.
863//===----------------------------------------------------------------------===//
864
865ScheduleDAGMILive::~ScheduleDAGMILive() {
866 delete DFSResult;
867}
868
Andrew Trick88639922012-04-24 17:56:43 +0000869/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
870/// crossing a scheduling boundary. [begin, end) includes all instructions in
871/// the region, including the boundary itself and single-instruction regions
872/// that don't get scheduled.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000873void ScheduleDAGMILive::enterRegion(MachineBasicBlock *bb,
Andrew Trick88639922012-04-24 17:56:43 +0000874 MachineBasicBlock::iterator begin,
875 MachineBasicBlock::iterator end,
Andrew Tricka53e1012013-08-23 17:48:33 +0000876 unsigned regioninstrs)
Andrew Trick88639922012-04-24 17:56:43 +0000877{
Andrew Trickd7f890e2013-12-28 21:56:47 +0000878 // ScheduleDAGMI initializes SchedImpl's per-region policy.
879 ScheduleDAGMI::enterRegion(bb, begin, end, regioninstrs);
Andrew Trick4add42f2012-05-10 21:06:10 +0000880
881 // For convenience remember the end of the liveness region.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000882 LiveRegionEnd = (RegionEnd == bb->end()) ? RegionEnd : std::next(RegionEnd);
Andrew Trick75e411c2013-09-06 17:32:34 +0000883
Andrew Trickb248b4a2013-09-06 17:32:47 +0000884 SUPressureDiffs.clear();
885
Andrew Trick75e411c2013-09-06 17:32:34 +0000886 ShouldTrackPressure = SchedImpl->shouldTrackPressure();
Matthias Braund4f64092016-01-20 00:23:32 +0000887 ShouldTrackLaneMasks = SchedImpl->shouldTrackLaneMasks();
888
889 if (ShouldTrackLaneMasks) {
890 if (!ShouldTrackPressure)
891 report_fatal_error("ShouldTrackLaneMasks requires ShouldTrackPressure");
892 // Dead subregister defs have no users and therefore no dependencies,
893 // moving them around may cause liveintervals to degrade into multiple
894 // components. Change independent components to have their own vreg to avoid
895 // this.
896 if (!DisconnectedComponentsRenamed)
897 LIS->renameDisconnectedComponents();
898 }
Andrew Trick4add42f2012-05-10 21:06:10 +0000899}
900
901// Setup the register pressure trackers for the top scheduled top and bottom
902// scheduled regions.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000903void ScheduleDAGMILive::initRegPressure() {
Matthias Braund4f64092016-01-20 00:23:32 +0000904 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin,
905 ShouldTrackLaneMasks, false);
906 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
907 ShouldTrackLaneMasks, false);
Andrew Trick4add42f2012-05-10 21:06:10 +0000908
909 // Close the RPTracker to finalize live ins.
910 RPTracker.closeRegion();
911
Andrew Trick9c17eab2013-07-30 19:59:12 +0000912 DEBUG(RPTracker.dump());
Andrew Trick79d3eec2012-05-24 22:11:14 +0000913
Andrew Trick4add42f2012-05-10 21:06:10 +0000914 // Initialize the live ins and live outs.
Matthias Braun3e86de12015-09-17 21:12:24 +0000915 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
916 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
Andrew Trick4add42f2012-05-10 21:06:10 +0000917
918 // Close one end of the tracker so we can call
919 // getMaxUpward/DownwardPressureDelta before advancing across any
920 // instructions. This converts currently live regs into live ins/outs.
921 TopRPTracker.closeTop();
922 BotRPTracker.closeBottom();
923
Andrew Trick9c17eab2013-07-30 19:59:12 +0000924 BotRPTracker.initLiveThru(RPTracker);
925 if (!BotRPTracker.getLiveThru().empty()) {
926 TopRPTracker.initLiveThru(BotRPTracker.getLiveThru());
927 DEBUG(dbgs() << "Live Thru: ";
928 dumpRegSetPressure(BotRPTracker.getLiveThru(), TRI));
929 };
930
Andrew Trick2bc74c22013-08-30 04:36:57 +0000931 // For each live out vreg reduce the pressure change associated with other
932 // uses of the same vreg below the live-out reaching def.
Matthias Braun3e86de12015-09-17 21:12:24 +0000933 updatePressureDiffs(RPTracker.getPressure().LiveOutRegs);
Andrew Trick2bc74c22013-08-30 04:36:57 +0000934
Andrew Trick4add42f2012-05-10 21:06:10 +0000935 // Account for liveness generated by the region boundary.
Andrew Trick2bc74c22013-08-30 04:36:57 +0000936 if (LiveRegionEnd != RegionEnd) {
Matthias Braun5d458612016-01-20 00:23:26 +0000937 SmallVector<RegisterMaskPair, 8> LiveUses;
Andrew Trick2bc74c22013-08-30 04:36:57 +0000938 BotRPTracker.recede(&LiveUses);
939 updatePressureDiffs(LiveUses);
940 }
Andrew Trick4add42f2012-05-10 21:06:10 +0000941
Matthias Braune6edd482015-11-13 22:30:31 +0000942 DEBUG(
943 dbgs() << "Top Pressure:\n";
944 dumpRegSetPressure(TopRPTracker.getRegSetPressureAtPos(), TRI);
945 dbgs() << "Bottom Pressure:\n";
946 dumpRegSetPressure(BotRPTracker.getRegSetPressureAtPos(), TRI);
947 );
948
Andrew Trick4add42f2012-05-10 21:06:10 +0000949 assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
Andrew Trick22025772012-05-17 18:35:10 +0000950
951 // Cache the list of excess pressure sets in this region. This will also track
952 // the max pressure in the scheduled code for these sets.
953 RegionCriticalPSets.clear();
Jakub Staszakc641ada2013-01-25 21:44:27 +0000954 const std::vector<unsigned> &RegionPressure =
955 RPTracker.getPressure().MaxSetPressure;
Andrew Trick22025772012-05-17 18:35:10 +0000956 for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
Andrew Trick736dd9a2013-06-21 18:32:58 +0000957 unsigned Limit = RegClassInfo->getRegPressureSetLimit(i);
Andrew Trickb55db582013-06-21 18:33:01 +0000958 if (RegionPressure[i] > Limit) {
959 DEBUG(dbgs() << TRI->getRegPressureSetName(i)
960 << " Limit " << Limit
961 << " Actual " << RegionPressure[i] << "\n");
Andrew Trick1a831342013-08-30 03:49:48 +0000962 RegionCriticalPSets.push_back(PressureChange(i));
Andrew Trickb55db582013-06-21 18:33:01 +0000963 }
Andrew Trick22025772012-05-17 18:35:10 +0000964 }
965 DEBUG(dbgs() << "Excess PSets: ";
966 for (unsigned i = 0, e = RegionCriticalPSets.size(); i != e; ++i)
967 dbgs() << TRI->getRegPressureSetName(
Andrew Trick1a831342013-08-30 03:49:48 +0000968 RegionCriticalPSets[i].getPSet()) << " ";
Andrew Trick22025772012-05-17 18:35:10 +0000969 dbgs() << "\n");
970}
971
Andrew Trickd7f890e2013-12-28 21:56:47 +0000972void ScheduleDAGMILive::
Andrew Trickb248b4a2013-09-06 17:32:47 +0000973updateScheduledPressure(const SUnit *SU,
974 const std::vector<unsigned> &NewMaxPressure) {
975 const PressureDiff &PDiff = getPressureDiff(SU);
976 unsigned CritIdx = 0, CritEnd = RegionCriticalPSets.size();
977 for (PressureDiff::const_iterator I = PDiff.begin(), E = PDiff.end();
978 I != E; ++I) {
979 if (!I->isValid())
980 break;
981 unsigned ID = I->getPSet();
982 while (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() < ID)
983 ++CritIdx;
984 if (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() == ID) {
985 if ((int)NewMaxPressure[ID] > RegionCriticalPSets[CritIdx].getUnitInc()
986 && NewMaxPressure[ID] <= INT16_MAX)
987 RegionCriticalPSets[CritIdx].setUnitInc(NewMaxPressure[ID]);
988 }
989 unsigned Limit = RegClassInfo->getRegPressureSetLimit(ID);
990 if (NewMaxPressure[ID] >= Limit - 2) {
991 DEBUG(dbgs() << " " << TRI->getRegPressureSetName(ID) << ": "
Andrew Trick569dc65a2015-05-17 23:40:31 +0000992 << NewMaxPressure[ID]
993 << ((NewMaxPressure[ID] > Limit) ? " > " : " <= ") << Limit
994 << "(+ " << BotRPTracker.getLiveThru()[ID] << " livethru)\n");
Andrew Trickb248b4a2013-09-06 17:32:47 +0000995 }
Andrew Trick22025772012-05-17 18:35:10 +0000996 }
Andrew Trick88639922012-04-24 17:56:43 +0000997}
998
Andrew Trick2bc74c22013-08-30 04:36:57 +0000999/// Update the PressureDiff array for liveness after scheduling this
1000/// instruction.
Matthias Braun5d458612016-01-20 00:23:26 +00001001void ScheduleDAGMILive::updatePressureDiffs(
1002 ArrayRef<RegisterMaskPair> LiveUses) {
1003 for (const RegisterMaskPair &P : LiveUses) {
Matthias Braun5d458612016-01-20 00:23:26 +00001004 unsigned Reg = P.RegUnit;
Matthias Braund4f64092016-01-20 00:23:32 +00001005 /// FIXME: Currently assuming single-use physregs.
Andrew Trick2bc74c22013-08-30 04:36:57 +00001006 if (!TRI->isVirtualRegister(Reg))
1007 continue;
Andrew Trickffdbefb2013-09-06 17:32:39 +00001008
Matthias Braund4f64092016-01-20 00:23:32 +00001009 if (ShouldTrackLaneMasks) {
1010 // If the register has just become live then other uses won't change
1011 // this fact anymore => decrement pressure.
1012 // If the register has just become dead then other uses make it come
1013 // back to life => increment pressure.
1014 bool Decrement = P.LaneMask != 0;
1015
1016 for (const VReg2SUnit &V2SU
1017 : make_range(VRegUses.find(Reg), VRegUses.end())) {
1018 SUnit &SU = *V2SU.SU;
1019 if (SU.isScheduled || &SU == &ExitSU)
1020 continue;
1021
1022 PressureDiff &PDiff = getPressureDiff(&SU);
1023 PDiff.addPressureChange(Reg, Decrement, &MRI);
1024 DEBUG(
1025 dbgs() << " UpdateRegP: SU(" << SU.NodeNum << ") "
1026 << PrintReg(Reg, TRI) << ':' << PrintLaneMask(P.LaneMask)
1027 << ' ' << *SU.getInstr();
1028 dbgs() << " to ";
1029 PDiff.dump(*TRI);
1030 );
1031 }
1032 } else {
1033 assert(P.LaneMask != 0);
1034 DEBUG(dbgs() << " LiveReg: " << PrintVRegOrUnit(Reg, TRI) << "\n");
1035 // This may be called before CurrentBottom has been initialized. However,
1036 // BotRPTracker must have a valid position. We want the value live into the
1037 // instruction or live out of the block, so ask for the previous
1038 // instruction's live-out.
1039 const LiveInterval &LI = LIS->getInterval(Reg);
1040 VNInfo *VNI;
1041 MachineBasicBlock::const_iterator I =
1042 nextIfDebug(BotRPTracker.getPos(), BB->end());
1043 if (I == BB->end())
1044 VNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
1045 else {
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001046 LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(*I));
Matthias Braund4f64092016-01-20 00:23:32 +00001047 VNI = LRQ.valueIn();
1048 }
1049 // RegisterPressureTracker guarantees that readsReg is true for LiveUses.
1050 assert(VNI && "No live value at use.");
1051 for (const VReg2SUnit &V2SU
1052 : make_range(VRegUses.find(Reg), VRegUses.end())) {
1053 SUnit *SU = V2SU.SU;
1054 // If this use comes before the reaching def, it cannot be a last use,
1055 // so decrease its pressure change.
1056 if (!SU->isScheduled && SU != &ExitSU) {
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001057 LiveQueryResult LRQ =
1058 LI.Query(LIS->getInstructionIndex(*SU->getInstr()));
Matthias Braund4f64092016-01-20 00:23:32 +00001059 if (LRQ.valueIn() == VNI) {
1060 PressureDiff &PDiff = getPressureDiff(SU);
1061 PDiff.addPressureChange(Reg, true, &MRI);
1062 DEBUG(
1063 dbgs() << " UpdateRegP: SU(" << SU->NodeNum << ") "
1064 << *SU->getInstr();
1065 dbgs() << " to ";
1066 PDiff.dump(*TRI);
1067 );
1068 }
Matthias Braun9198c672015-11-06 20:59:02 +00001069 }
Andrew Trick2bc74c22013-08-30 04:36:57 +00001070 }
1071 }
1072 }
1073}
1074
Andrew Trick8823dec2012-03-14 04:00:41 +00001075/// schedule - Called back from MachineScheduler::runOnMachineFunction
Andrew Trick88639922012-04-24 17:56:43 +00001076/// after setting up the current scheduling region. [RegionBegin, RegionEnd)
1077/// only includes instructions that have DAG nodes, not scheduling boundaries.
Andrew Trick7a8e1002012-09-11 00:39:15 +00001078///
1079/// This is a skeletal driver, with all the functionality pushed into helpers,
Nick Lewycky06b0ea22015-08-18 22:41:58 +00001080/// so that it can be easily extended by experimental schedulers. Generally,
Andrew Trick7a8e1002012-09-11 00:39:15 +00001081/// implementing MachineSchedStrategy should be sufficient to implement a new
1082/// scheduling algorithm. However, if a scheduler further subclasses
Andrew Trickd7f890e2013-12-28 21:56:47 +00001083/// ScheduleDAGMILive then it will want to override this virtual method in order
1084/// to update any specialized state.
1085void ScheduleDAGMILive::schedule() {
James Y Knighte72b0db2015-09-18 18:52:20 +00001086 DEBUG(dbgs() << "ScheduleDAGMILive::schedule starting\n");
1087 DEBUG(SchedImpl->dumpPolicy());
Andrew Trick7a8e1002012-09-11 00:39:15 +00001088 buildDAGWithRegPressure();
1089
Andrew Tricka7714a02012-11-12 19:40:10 +00001090 Topo.InitDAGTopologicalSorting();
1091
Andrew Tricka2733e92012-09-14 17:22:42 +00001092 postprocessDAG();
1093
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001094 SmallVector<SUnit*, 8> TopRoots, BotRoots;
1095 findRootsAndBiasEdges(TopRoots, BotRoots);
1096
1097 // Initialize the strategy before modifying the DAG.
1098 // This may initialize a DFSResult to be used for queue priority.
1099 SchedImpl->initialize(this);
1100
Matthias Braun9198c672015-11-06 20:59:02 +00001101 DEBUG(
1102 for (const SUnit &SU : SUnits) {
1103 SU.dumpAll(this);
1104 if (ShouldTrackPressure) {
1105 dbgs() << " Pressure Diff : ";
1106 getPressureDiff(&SU).dump(*TRI);
1107 }
1108 dbgs() << '\n';
1109 }
1110 );
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001111 if (ViewMISchedDAGs) viewGraph();
Andrew Trick7a8e1002012-09-11 00:39:15 +00001112
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001113 // Initialize ready queues now that the DAG and priority data are finalized.
1114 initQueues(TopRoots, BotRoots);
Andrew Trick7a8e1002012-09-11 00:39:15 +00001115
Andrew Trickd7f890e2013-12-28 21:56:47 +00001116 if (ShouldTrackPressure) {
1117 assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
1118 TopRPTracker.setPos(CurrentTop);
1119 }
1120
Andrew Trick7a8e1002012-09-11 00:39:15 +00001121 bool IsTopNode = false;
James Y Knighte72b0db2015-09-18 18:52:20 +00001122 while (true) {
1123 DEBUG(dbgs() << "** ScheduleDAGMILive::schedule picking next node\n");
1124 SUnit *SU = SchedImpl->pickNode(IsTopNode);
1125 if (!SU) break;
1126
Andrew Trick984d98b2012-10-08 18:53:53 +00001127 assert(!SU->isScheduled && "Node already scheduled");
Andrew Trick7a8e1002012-09-11 00:39:15 +00001128 if (!checkSchedLimit())
1129 break;
1130
1131 scheduleMI(SU, IsTopNode);
1132
Andrew Trickd7f890e2013-12-28 21:56:47 +00001133 if (DFSResult) {
1134 unsigned SubtreeID = DFSResult->getSubtreeID(SU);
1135 if (!ScheduledTrees.test(SubtreeID)) {
1136 ScheduledTrees.set(SubtreeID);
1137 DFSResult->scheduleTree(SubtreeID);
1138 SchedImpl->scheduleTree(SubtreeID);
1139 }
1140 }
1141
1142 // Notify the scheduling strategy after updating the DAG.
1143 SchedImpl->schedNode(SU, IsTopNode);
Andrew Trick43adfb32015-03-27 06:10:13 +00001144
1145 updateQueues(SU, IsTopNode);
Andrew Trick7a8e1002012-09-11 00:39:15 +00001146 }
1147 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
1148
1149 placeDebugValues();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001150
1151 DEBUG({
Andrew Trickcf7e6972012-11-28 03:42:47 +00001152 unsigned BBNum = begin()->getParent()->getNumber();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001153 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
1154 dumpSchedule();
1155 dbgs() << '\n';
1156 });
Andrew Trick7a8e1002012-09-11 00:39:15 +00001157}
1158
1159/// Build the DAG and setup three register pressure trackers.
Andrew Trickd7f890e2013-12-28 21:56:47 +00001160void ScheduleDAGMILive::buildDAGWithRegPressure() {
Andrew Trickb6e74712013-09-04 20:59:59 +00001161 if (!ShouldTrackPressure) {
1162 RPTracker.reset();
1163 RegionCriticalPSets.clear();
1164 buildSchedGraph(AA);
1165 return;
1166 }
1167
Andrew Trick4add42f2012-05-10 21:06:10 +00001168 // Initialize the register pressure tracker used by buildSchedGraph.
Andrew Trick9c17eab2013-07-30 19:59:12 +00001169 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
Matthias Braund4f64092016-01-20 00:23:32 +00001170 ShouldTrackLaneMasks, /*TrackUntiedDefs=*/true);
Andrew Trick88639922012-04-24 17:56:43 +00001171
Andrew Trick4add42f2012-05-10 21:06:10 +00001172 // Account for liveness generate by the region boundary.
1173 if (LiveRegionEnd != RegionEnd)
1174 RPTracker.recede();
1175
1176 // Build the DAG, and compute current register pressure.
Matthias Braund4f64092016-01-20 00:23:32 +00001177 buildSchedGraph(AA, &RPTracker, &SUPressureDiffs, LIS, ShouldTrackLaneMasks);
Andrew Trick02a80da2012-03-08 01:41:12 +00001178
Andrew Trick4add42f2012-05-10 21:06:10 +00001179 // Initialize top/bottom trackers after computing region pressure.
1180 initRegPressure();
Andrew Trick7a8e1002012-09-11 00:39:15 +00001181}
Andrew Trick4add42f2012-05-10 21:06:10 +00001182
Andrew Trickd7f890e2013-12-28 21:56:47 +00001183void ScheduleDAGMILive::computeDFSResult() {
Andrew Trick44f750a2013-01-25 04:01:04 +00001184 if (!DFSResult)
1185 DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize);
1186 DFSResult->clear();
Andrew Trick44f750a2013-01-25 04:01:04 +00001187 ScheduledTrees.clear();
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001188 DFSResult->resize(SUnits.size());
1189 DFSResult->compute(SUnits);
Andrew Trick44f750a2013-01-25 04:01:04 +00001190 ScheduledTrees.resize(DFSResult->getNumSubtrees());
1191}
1192
Andrew Trick483f4192013-08-29 18:04:49 +00001193/// Compute the max cyclic critical path through the DAG. The scheduling DAG
1194/// only provides the critical path for single block loops. To handle loops that
1195/// span blocks, we could use the vreg path latencies provided by
1196/// MachineTraceMetrics instead. However, MachineTraceMetrics is not currently
1197/// available for use in the scheduler.
1198///
1199/// The cyclic path estimation identifies a def-use pair that crosses the back
Andrew Trickef80f502013-08-30 02:02:12 +00001200/// edge and considers the depth and height of the nodes. For example, consider
Andrew Trick483f4192013-08-29 18:04:49 +00001201/// the following instruction sequence where each instruction has unit latency
1202/// and defines an epomymous virtual register:
1203///
1204/// a->b(a,c)->c(b)->d(c)->exit
1205///
1206/// The cyclic critical path is a two cycles: b->c->b
1207/// The acyclic critical path is four cycles: a->b->c->d->exit
1208/// LiveOutHeight = height(c) = len(c->d->exit) = 2
1209/// LiveOutDepth = depth(c) + 1 = len(a->b->c) + 1 = 3
1210/// LiveInHeight = height(b) + 1 = len(b->c->d->exit) + 1 = 4
1211/// LiveInDepth = depth(b) = len(a->b) = 1
1212///
1213/// LiveOutDepth - LiveInDepth = 3 - 1 = 2
1214/// LiveInHeight - LiveOutHeight = 4 - 2 = 2
1215/// CyclicCriticalPath = min(2, 2) = 2
Andrew Trickd7f890e2013-12-28 21:56:47 +00001216///
1217/// This could be relevant to PostRA scheduling, but is currently implemented
1218/// assuming LiveIntervals.
1219unsigned ScheduleDAGMILive::computeCyclicCriticalPath() {
Andrew Trick483f4192013-08-29 18:04:49 +00001220 // This only applies to single block loop.
1221 if (!BB->isSuccessor(BB))
1222 return 0;
1223
1224 unsigned MaxCyclicLatency = 0;
1225 // Visit each live out vreg def to find def/use pairs that cross iterations.
Matthias Braun5d458612016-01-20 00:23:26 +00001226 for (const RegisterMaskPair &P : RPTracker.getPressure().LiveOutRegs) {
1227 unsigned Reg = P.RegUnit;
Andrew Trick483f4192013-08-29 18:04:49 +00001228 if (!TRI->isVirtualRegister(Reg))
1229 continue;
1230 const LiveInterval &LI = LIS->getInterval(Reg);
1231 const VNInfo *DefVNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
1232 if (!DefVNI)
1233 continue;
1234
1235 MachineInstr *DefMI = LIS->getInstructionFromIndex(DefVNI->def);
1236 const SUnit *DefSU = getSUnit(DefMI);
1237 if (!DefSU)
1238 continue;
1239
1240 unsigned LiveOutHeight = DefSU->getHeight();
1241 unsigned LiveOutDepth = DefSU->getDepth() + DefSU->Latency;
1242 // Visit all local users of the vreg def.
Matthias Braunb0c437b2015-10-29 03:57:17 +00001243 for (const VReg2SUnit &V2SU
1244 : make_range(VRegUses.find(Reg), VRegUses.end())) {
1245 SUnit *SU = V2SU.SU;
1246 if (SU == &ExitSU)
Andrew Trick483f4192013-08-29 18:04:49 +00001247 continue;
1248
1249 // Only consider uses of the phi.
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001250 LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(*SU->getInstr()));
Andrew Trick483f4192013-08-29 18:04:49 +00001251 if (!LRQ.valueIn()->isPHIDef())
1252 continue;
1253
1254 // Assume that a path spanning two iterations is a cycle, which could
1255 // overestimate in strange cases. This allows cyclic latency to be
1256 // estimated as the minimum slack of the vreg's depth or height.
1257 unsigned CyclicLatency = 0;
Matthias Braunb0c437b2015-10-29 03:57:17 +00001258 if (LiveOutDepth > SU->getDepth())
1259 CyclicLatency = LiveOutDepth - SU->getDepth();
Andrew Trick483f4192013-08-29 18:04:49 +00001260
Matthias Braunb0c437b2015-10-29 03:57:17 +00001261 unsigned LiveInHeight = SU->getHeight() + DefSU->Latency;
Andrew Trick483f4192013-08-29 18:04:49 +00001262 if (LiveInHeight > LiveOutHeight) {
1263 if (LiveInHeight - LiveOutHeight < CyclicLatency)
1264 CyclicLatency = LiveInHeight - LiveOutHeight;
Matthias Braunb550b762016-04-21 01:54:13 +00001265 } else
Andrew Trick483f4192013-08-29 18:04:49 +00001266 CyclicLatency = 0;
1267
1268 DEBUG(dbgs() << "Cyclic Path: SU(" << DefSU->NodeNum << ") -> SU("
Matthias Braunb0c437b2015-10-29 03:57:17 +00001269 << SU->NodeNum << ") = " << CyclicLatency << "c\n");
Andrew Trick483f4192013-08-29 18:04:49 +00001270 if (CyclicLatency > MaxCyclicLatency)
1271 MaxCyclicLatency = CyclicLatency;
1272 }
1273 }
1274 DEBUG(dbgs() << "Cyclic Critical Path: " << MaxCyclicLatency << "c\n");
1275 return MaxCyclicLatency;
1276}
1277
Andrew Trick7a8e1002012-09-11 00:39:15 +00001278/// Move an instruction and update register pressure.
Andrew Trickd7f890e2013-12-28 21:56:47 +00001279void ScheduleDAGMILive::scheduleMI(SUnit *SU, bool IsTopNode) {
Andrew Trick7a8e1002012-09-11 00:39:15 +00001280 // Move the instruction to its new location in the instruction stream.
1281 MachineInstr *MI = SU->getInstr();
Andrew Trick02a80da2012-03-08 01:41:12 +00001282
Andrew Trick7a8e1002012-09-11 00:39:15 +00001283 if (IsTopNode) {
1284 assert(SU->isTopReady() && "node still has unscheduled dependencies");
1285 if (&*CurrentTop == MI)
1286 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
Andrew Trick8823dec2012-03-14 04:00:41 +00001287 else {
Andrew Trick7a8e1002012-09-11 00:39:15 +00001288 moveInstruction(MI, CurrentTop);
1289 TopRPTracker.setPos(MI);
Andrew Trick8823dec2012-03-14 04:00:41 +00001290 }
Andrew Trickc3ea0052012-04-24 18:04:37 +00001291
Andrew Trickb6e74712013-09-04 20:59:59 +00001292 if (ShouldTrackPressure) {
1293 // Update top scheduled pressure.
Matthias Braund4f64092016-01-20 00:23:32 +00001294 RegisterOperands RegOpers;
1295 RegOpers.collect(*MI, *TRI, MRI, ShouldTrackLaneMasks, false);
1296 if (ShouldTrackLaneMasks) {
1297 // Adjust liveness and add missing dead+read-undef flags.
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001298 SlotIndex SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot();
Matthias Braund4f64092016-01-20 00:23:32 +00001299 RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx, MI);
1300 } else {
1301 // Adjust for missing dead-def flags.
1302 RegOpers.detectDeadDefs(*MI, *LIS);
1303 }
1304
1305 TopRPTracker.advance(RegOpers);
Andrew Trickb6e74712013-09-04 20:59:59 +00001306 assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
Matthias Braun9198c672015-11-06 20:59:02 +00001307 DEBUG(
1308 dbgs() << "Top Pressure:\n";
1309 dumpRegSetPressure(TopRPTracker.getRegSetPressureAtPos(), TRI);
1310 );
1311
Andrew Trickb248b4a2013-09-06 17:32:47 +00001312 updateScheduledPressure(SU, TopRPTracker.getPressure().MaxSetPressure);
Andrew Trickb6e74712013-09-04 20:59:59 +00001313 }
Matthias Braunb550b762016-04-21 01:54:13 +00001314 } else {
Andrew Trick7a8e1002012-09-11 00:39:15 +00001315 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
1316 MachineBasicBlock::iterator priorII =
1317 priorNonDebug(CurrentBottom, CurrentTop);
1318 if (&*priorII == MI)
1319 CurrentBottom = priorII;
1320 else {
1321 if (&*CurrentTop == MI) {
1322 CurrentTop = nextIfDebug(++CurrentTop, priorII);
1323 TopRPTracker.setPos(CurrentTop);
1324 }
1325 moveInstruction(MI, CurrentBottom);
1326 CurrentBottom = MI;
1327 }
Andrew Trickb6e74712013-09-04 20:59:59 +00001328 if (ShouldTrackPressure) {
Matthias Braund4f64092016-01-20 00:23:32 +00001329 RegisterOperands RegOpers;
1330 RegOpers.collect(*MI, *TRI, MRI, ShouldTrackLaneMasks, false);
1331 if (ShouldTrackLaneMasks) {
1332 // Adjust liveness and add missing dead+read-undef flags.
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001333 SlotIndex SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot();
Matthias Braund4f64092016-01-20 00:23:32 +00001334 RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx, MI);
1335 } else {
1336 // Adjust for missing dead-def flags.
1337 RegOpers.detectDeadDefs(*MI, *LIS);
1338 }
1339
1340 BotRPTracker.recedeSkipDebugValues();
Matthias Braun5d458612016-01-20 00:23:26 +00001341 SmallVector<RegisterMaskPair, 8> LiveUses;
Matthias Braund4f64092016-01-20 00:23:32 +00001342 BotRPTracker.recede(RegOpers, &LiveUses);
Andrew Trickb6e74712013-09-04 20:59:59 +00001343 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
Matthias Braun9198c672015-11-06 20:59:02 +00001344 DEBUG(
1345 dbgs() << "Bottom Pressure:\n";
1346 dumpRegSetPressure(BotRPTracker.getRegSetPressureAtPos(), TRI);
1347 );
1348
Andrew Trickb248b4a2013-09-06 17:32:47 +00001349 updateScheduledPressure(SU, BotRPTracker.getPressure().MaxSetPressure);
Andrew Trickb6e74712013-09-04 20:59:59 +00001350 updatePressureDiffs(LiveUses);
Andrew Trickb6e74712013-09-04 20:59:59 +00001351 }
Andrew Trick7a8e1002012-09-11 00:39:15 +00001352 }
1353}
1354
Andrew Trick263280242012-11-12 19:52:20 +00001355//===----------------------------------------------------------------------===//
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001356// BaseMemOpClusterMutation - DAG post-processing to cluster loads or stores.
Andrew Trick263280242012-11-12 19:52:20 +00001357//===----------------------------------------------------------------------===//
1358
Andrew Tricka7714a02012-11-12 19:40:10 +00001359namespace {
1360/// \brief Post-process the DAG to create cluster edges between neighboring
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001361/// loads or between neighboring stores.
1362class BaseMemOpClusterMutation : public ScheduleDAGMutation {
1363 struct MemOpInfo {
Andrew Tricka7714a02012-11-12 19:40:10 +00001364 SUnit *SU;
1365 unsigned BaseReg;
Chad Rosierc27a18f2016-03-09 16:00:35 +00001366 int64_t Offset;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001367 MemOpInfo(SUnit *su, unsigned reg, int64_t ofs)
1368 : SU(su), BaseReg(reg), Offset(ofs) {}
Benjamin Kramerb0f74b22014-03-07 21:35:39 +00001369
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001370 bool operator<(const MemOpInfo&RHS) const {
Benjamin Kramerb0f74b22014-03-07 21:35:39 +00001371 return std::tie(BaseReg, Offset) < std::tie(RHS.BaseReg, RHS.Offset);
1372 }
Andrew Tricka7714a02012-11-12 19:40:10 +00001373 };
Andrew Tricka7714a02012-11-12 19:40:10 +00001374
1375 const TargetInstrInfo *TII;
1376 const TargetRegisterInfo *TRI;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001377 bool IsLoad;
1378
Andrew Tricka7714a02012-11-12 19:40:10 +00001379public:
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001380 BaseMemOpClusterMutation(const TargetInstrInfo *tii,
1381 const TargetRegisterInfo *tri, bool IsLoad)
1382 : TII(tii), TRI(tri), IsLoad(IsLoad) {}
Andrew Tricka7714a02012-11-12 19:40:10 +00001383
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001384 void apply(ScheduleDAGInstrs *DAGInstrs) override;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001385
Andrew Tricka7714a02012-11-12 19:40:10 +00001386protected:
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001387 void clusterNeighboringMemOps(ArrayRef<SUnit *> MemOps, ScheduleDAGMI *DAG);
1388};
1389
1390class StoreClusterMutation : public BaseMemOpClusterMutation {
1391public:
1392 StoreClusterMutation(const TargetInstrInfo *tii,
1393 const TargetRegisterInfo *tri)
1394 : BaseMemOpClusterMutation(tii, tri, false) {}
1395};
1396
1397class LoadClusterMutation : public BaseMemOpClusterMutation {
1398public:
1399 LoadClusterMutation(const TargetInstrInfo *tii, const TargetRegisterInfo *tri)
1400 : BaseMemOpClusterMutation(tii, tri, true) {}
Andrew Tricka7714a02012-11-12 19:40:10 +00001401};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001402} // anonymous
Andrew Tricka7714a02012-11-12 19:40:10 +00001403
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001404void BaseMemOpClusterMutation::clusterNeighboringMemOps(
1405 ArrayRef<SUnit *> MemOps, ScheduleDAGMI *DAG) {
1406 SmallVector<MemOpInfo, 32> MemOpRecords;
1407 for (unsigned Idx = 0, End = MemOps.size(); Idx != End; ++Idx) {
1408 SUnit *SU = MemOps[Idx];
Andrew Tricka7714a02012-11-12 19:40:10 +00001409 unsigned BaseReg;
Chad Rosierc27a18f2016-03-09 16:00:35 +00001410 int64_t Offset;
Sanjoy Dasb666ea32015-06-15 18:44:14 +00001411 if (TII->getMemOpBaseRegImmOfs(SU->getInstr(), BaseReg, Offset, TRI))
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001412 MemOpRecords.push_back(MemOpInfo(SU, BaseReg, Offset));
Andrew Tricka7714a02012-11-12 19:40:10 +00001413 }
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001414 if (MemOpRecords.size() < 2)
Andrew Tricka7714a02012-11-12 19:40:10 +00001415 return;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001416
1417 std::sort(MemOpRecords.begin(), MemOpRecords.end());
Andrew Tricka7714a02012-11-12 19:40:10 +00001418 unsigned ClusterLength = 1;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001419 for (unsigned Idx = 0, End = MemOpRecords.size(); Idx < (End - 1); ++Idx) {
1420 if (MemOpRecords[Idx].BaseReg != MemOpRecords[Idx+1].BaseReg) {
Andrew Tricka7714a02012-11-12 19:40:10 +00001421 ClusterLength = 1;
1422 continue;
1423 }
1424
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001425 SUnit *SUa = MemOpRecords[Idx].SU;
1426 SUnit *SUb = MemOpRecords[Idx+1].SU;
1427 if (TII->shouldClusterMemOps(SUa->getInstr(), SUb->getInstr(), ClusterLength)
Andrew Tricka7714a02012-11-12 19:40:10 +00001428 && DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001429 DEBUG(dbgs() << "Cluster ld/st SU(" << SUa->NodeNum << ") - SU("
Andrew Tricka7714a02012-11-12 19:40:10 +00001430 << SUb->NodeNum << ")\n");
1431 // Copy successor edges from SUa to SUb. Interleaving computation
1432 // dependent on SUa can prevent load combining due to register reuse.
1433 // Predecessor edges do not need to be copied from SUb to SUa since nearby
1434 // loads should have effectively the same inputs.
1435 for (SUnit::const_succ_iterator
1436 SI = SUa->Succs.begin(), SE = SUa->Succs.end(); SI != SE; ++SI) {
1437 if (SI->getSUnit() == SUb)
1438 continue;
1439 DEBUG(dbgs() << " Copy Succ SU(" << SI->getSUnit()->NodeNum << ")\n");
1440 DAG->addEdge(SI->getSUnit(), SDep(SUb, SDep::Artificial));
1441 }
1442 ++ClusterLength;
Matthias Braunb550b762016-04-21 01:54:13 +00001443 } else
Andrew Tricka7714a02012-11-12 19:40:10 +00001444 ClusterLength = 1;
1445 }
1446}
1447
1448/// \brief Callback from DAG postProcessing to create cluster edges for loads.
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001449void BaseMemOpClusterMutation::apply(ScheduleDAGInstrs *DAGInstrs) {
1450
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001451 ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs);
1452
Andrew Tricka7714a02012-11-12 19:40:10 +00001453 // Map DAG NodeNum to store chain ID.
1454 DenseMap<unsigned, unsigned> StoreChainIDs;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001455 // Map each store chain to a set of dependent MemOps.
Andrew Tricka7714a02012-11-12 19:40:10 +00001456 SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
1457 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
1458 SUnit *SU = &DAG->SUnits[Idx];
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001459 if ((IsLoad && !SU->getInstr()->mayLoad()) ||
1460 (!IsLoad && !SU->getInstr()->mayStore()))
Andrew Tricka7714a02012-11-12 19:40:10 +00001461 continue;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001462
Andrew Tricka7714a02012-11-12 19:40:10 +00001463 unsigned ChainPredID = DAG->SUnits.size();
1464 for (SUnit::const_pred_iterator
1465 PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
1466 if (PI->isCtrl()) {
1467 ChainPredID = PI->getSUnit()->NodeNum;
1468 break;
1469 }
1470 }
1471 // Check if this chain-like pred has been seen
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001472 // before. ChainPredID==MaxNodeID at the top of the schedule.
Andrew Tricka7714a02012-11-12 19:40:10 +00001473 unsigned NumChains = StoreChainDependents.size();
1474 std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
1475 StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
1476 if (Result.second)
1477 StoreChainDependents.resize(NumChains + 1);
1478 StoreChainDependents[Result.first->second].push_back(SU);
1479 }
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001480
Andrew Tricka7714a02012-11-12 19:40:10 +00001481 // Iterate over the store chains.
1482 for (unsigned Idx = 0, End = StoreChainDependents.size(); Idx != End; ++Idx)
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001483 clusterNeighboringMemOps(StoreChainDependents[Idx], DAG);
Andrew Tricka7714a02012-11-12 19:40:10 +00001484}
1485
Andrew Trick02a80da2012-03-08 01:41:12 +00001486//===----------------------------------------------------------------------===//
Andrew Trick263280242012-11-12 19:52:20 +00001487// MacroFusion - DAG post-processing to encourage fusion of macro ops.
1488//===----------------------------------------------------------------------===//
1489
1490namespace {
1491/// \brief Post-process the DAG to create cluster edges between instructions
1492/// that may be fused by the processor into a single operation.
1493class MacroFusion : public ScheduleDAGMutation {
Matthias Braun2bd6dd82015-07-20 22:34:44 +00001494 const TargetInstrInfo &TII;
1495 const TargetRegisterInfo &TRI;
Andrew Trick263280242012-11-12 19:52:20 +00001496public:
Matthias Braun2bd6dd82015-07-20 22:34:44 +00001497 MacroFusion(const TargetInstrInfo &TII, const TargetRegisterInfo &TRI)
1498 : TII(TII), TRI(TRI) {}
Andrew Trick263280242012-11-12 19:52:20 +00001499
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001500 void apply(ScheduleDAGInstrs *DAGInstrs) override;
Andrew Trick263280242012-11-12 19:52:20 +00001501};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001502} // anonymous
Andrew Trick263280242012-11-12 19:52:20 +00001503
Matthias Braun2bd6dd82015-07-20 22:34:44 +00001504/// Returns true if \p MI reads a register written by \p Other.
1505static bool HasDataDep(const TargetRegisterInfo &TRI, const MachineInstr &MI,
1506 const MachineInstr &Other) {
1507 for (const MachineOperand &MO : MI.uses()) {
1508 if (!MO.isReg() || !MO.readsReg())
1509 continue;
1510
1511 unsigned Reg = MO.getReg();
1512 if (Other.modifiesRegister(Reg, &TRI))
1513 return true;
1514 }
1515 return false;
1516}
1517
Andrew Trick263280242012-11-12 19:52:20 +00001518/// \brief Callback from DAG postProcessing to create cluster edges to encourage
1519/// fused operations.
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001520void MacroFusion::apply(ScheduleDAGInstrs *DAGInstrs) {
1521 ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs);
1522
Andrew Trick263280242012-11-12 19:52:20 +00001523 // For now, assume targets can only fuse with the branch.
Matthias Braun2bd6dd82015-07-20 22:34:44 +00001524 SUnit &ExitSU = DAG->ExitSU;
1525 MachineInstr *Branch = ExitSU.getInstr();
Andrew Trick263280242012-11-12 19:52:20 +00001526 if (!Branch)
1527 return;
1528
Matthias Braun2bd6dd82015-07-20 22:34:44 +00001529 for (SUnit &SU : DAG->SUnits) {
1530 // SUnits with successors can't be schedule in front of the ExitSU.
1531 if (!SU.Succs.empty())
1532 continue;
1533 // We only care if the node writes to a register that the branch reads.
1534 MachineInstr *Pred = SU.getInstr();
1535 if (!HasDataDep(TRI, *Branch, *Pred))
1536 continue;
1537
1538 if (!TII.shouldScheduleAdjacent(Pred, Branch))
Andrew Trick263280242012-11-12 19:52:20 +00001539 continue;
1540
1541 // Create a single weak edge from SU to ExitSU. The only effect is to cause
1542 // bottom-up scheduling to heavily prioritize the clustered SU. There is no
1543 // need to copy predecessor edges from ExitSU to SU, since top-down
1544 // scheduling cannot prioritize ExitSU anyway. To defer top-down scheduling
1545 // of SU, we could create an artificial edge from the deepest root, but it
1546 // hasn't been needed yet.
Matthias Braun2bd6dd82015-07-20 22:34:44 +00001547 bool Success = DAG->addEdge(&ExitSU, SDep(&SU, SDep::Cluster));
Andrew Trick263280242012-11-12 19:52:20 +00001548 (void)Success;
1549 assert(Success && "No DAG nodes should be reachable from ExitSU");
1550
Matthias Braun2bd6dd82015-07-20 22:34:44 +00001551 DEBUG(dbgs() << "Macro Fuse SU(" << SU.NodeNum << ")\n");
Andrew Trick263280242012-11-12 19:52:20 +00001552 break;
1553 }
1554}
1555
1556//===----------------------------------------------------------------------===//
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001557// CopyConstrain - DAG post-processing to encourage copy elimination.
1558//===----------------------------------------------------------------------===//
1559
1560namespace {
1561/// \brief Post-process the DAG to create weak edges from all uses of a copy to
1562/// the one use that defines the copy's source vreg, most likely an induction
1563/// variable increment.
1564class CopyConstrain : public ScheduleDAGMutation {
1565 // Transient state.
1566 SlotIndex RegionBeginIdx;
Andrew Trick2e875172013-04-24 23:19:56 +00001567 // RegionEndIdx is the slot index of the last non-debug instruction in the
1568 // scheduling region. So we may have RegionBeginIdx == RegionEndIdx.
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001569 SlotIndex RegionEndIdx;
1570public:
1571 CopyConstrain(const TargetInstrInfo *, const TargetRegisterInfo *) {}
1572
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001573 void apply(ScheduleDAGInstrs *DAGInstrs) override;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001574
1575protected:
Andrew Trickd7f890e2013-12-28 21:56:47 +00001576 void constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG);
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001577};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001578} // anonymous
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001579
1580/// constrainLocalCopy handles two possibilities:
1581/// 1) Local src:
1582/// I0: = dst
1583/// I1: src = ...
1584/// I2: = dst
1585/// I3: dst = src (copy)
1586/// (create pred->succ edges I0->I1, I2->I1)
1587///
1588/// 2) Local copy:
1589/// I0: dst = src (copy)
1590/// I1: = dst
1591/// I2: src = ...
1592/// I3: = dst
1593/// (create pred->succ edges I1->I2, I3->I2)
1594///
1595/// Although the MachineScheduler is currently constrained to single blocks,
1596/// this algorithm should handle extended blocks. An EBB is a set of
1597/// contiguously numbered blocks such that the previous block in the EBB is
1598/// always the single predecessor.
Andrew Trickd7f890e2013-12-28 21:56:47 +00001599void CopyConstrain::constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG) {
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001600 LiveIntervals *LIS = DAG->getLIS();
1601 MachineInstr *Copy = CopySU->getInstr();
1602
1603 // Check for pure vreg copies.
Matthias Braun7511abd2016-04-04 21:23:46 +00001604 const MachineOperand &SrcOp = Copy->getOperand(1);
1605 unsigned SrcReg = SrcOp.getReg();
1606 if (!TargetRegisterInfo::isVirtualRegister(SrcReg) || !SrcOp.readsReg())
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001607 return;
1608
Matthias Braun7511abd2016-04-04 21:23:46 +00001609 const MachineOperand &DstOp = Copy->getOperand(0);
1610 unsigned DstReg = DstOp.getReg();
1611 if (!TargetRegisterInfo::isVirtualRegister(DstReg) || DstOp.isDead())
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001612 return;
1613
1614 // Check if either the dest or source is local. If it's live across a back
1615 // edge, it's not local. Note that if both vregs are live across the back
1616 // edge, we cannot successfully contrain the copy without cyclic scheduling.
Michael Kuperstein54c61ed2015-01-19 07:30:47 +00001617 // If both the copy's source and dest are local live intervals, then we
1618 // should treat the dest as the global for the purpose of adding
1619 // constraints. This adds edges from source's other uses to the copy.
1620 unsigned LocalReg = SrcReg;
1621 unsigned GlobalReg = DstReg;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001622 LiveInterval *LocalLI = &LIS->getInterval(LocalReg);
1623 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx)) {
Michael Kuperstein54c61ed2015-01-19 07:30:47 +00001624 LocalReg = DstReg;
1625 GlobalReg = SrcReg;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001626 LocalLI = &LIS->getInterval(LocalReg);
1627 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx))
1628 return;
1629 }
1630 LiveInterval *GlobalLI = &LIS->getInterval(GlobalReg);
1631
1632 // Find the global segment after the start of the local LI.
1633 LiveInterval::iterator GlobalSegment = GlobalLI->find(LocalLI->beginIndex());
1634 // If GlobalLI does not overlap LocalLI->start, then a copy directly feeds a
1635 // local live range. We could create edges from other global uses to the local
1636 // start, but the coalescer should have already eliminated these cases, so
1637 // don't bother dealing with it.
1638 if (GlobalSegment == GlobalLI->end())
1639 return;
1640
1641 // If GlobalSegment is killed at the LocalLI->start, the call to find()
1642 // returned the next global segment. But if GlobalSegment overlaps with
1643 // LocalLI->start, then advance to the next segement. If a hole in GlobalLI
1644 // exists in LocalLI's vicinity, GlobalSegment will be the end of the hole.
1645 if (GlobalSegment->contains(LocalLI->beginIndex()))
1646 ++GlobalSegment;
1647
1648 if (GlobalSegment == GlobalLI->end())
1649 return;
1650
1651 // Check if GlobalLI contains a hole in the vicinity of LocalLI.
1652 if (GlobalSegment != GlobalLI->begin()) {
1653 // Two address defs have no hole.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001654 if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->end,
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001655 GlobalSegment->start)) {
1656 return;
1657 }
Andrew Trickd9761772013-07-30 19:59:08 +00001658 // If the prior global segment may be defined by the same two-address
1659 // instruction that also defines LocalLI, then can't make a hole here.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001660 if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->start,
Andrew Trickd9761772013-07-30 19:59:08 +00001661 LocalLI->beginIndex())) {
1662 return;
1663 }
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001664 // If GlobalLI has a prior segment, it must be live into the EBB. Otherwise
1665 // it would be a disconnected component in the live range.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001666 assert(std::prev(GlobalSegment)->start < LocalLI->beginIndex() &&
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001667 "Disconnected LRG within the scheduling region.");
1668 }
1669 MachineInstr *GlobalDef = LIS->getInstructionFromIndex(GlobalSegment->start);
1670 if (!GlobalDef)
1671 return;
1672
1673 SUnit *GlobalSU = DAG->getSUnit(GlobalDef);
1674 if (!GlobalSU)
1675 return;
1676
1677 // GlobalDef is the bottom of the GlobalLI hole. Open the hole by
1678 // constraining the uses of the last local def to precede GlobalDef.
1679 SmallVector<SUnit*,8> LocalUses;
1680 const VNInfo *LastLocalVN = LocalLI->getVNInfoBefore(LocalLI->endIndex());
1681 MachineInstr *LastLocalDef = LIS->getInstructionFromIndex(LastLocalVN->def);
1682 SUnit *LastLocalSU = DAG->getSUnit(LastLocalDef);
1683 for (SUnit::const_succ_iterator
1684 I = LastLocalSU->Succs.begin(), E = LastLocalSU->Succs.end();
1685 I != E; ++I) {
1686 if (I->getKind() != SDep::Data || I->getReg() != LocalReg)
1687 continue;
1688 if (I->getSUnit() == GlobalSU)
1689 continue;
1690 if (!DAG->canAddEdge(GlobalSU, I->getSUnit()))
1691 return;
1692 LocalUses.push_back(I->getSUnit());
1693 }
1694 // Open the top of the GlobalLI hole by constraining any earlier global uses
1695 // to precede the start of LocalLI.
1696 SmallVector<SUnit*,8> GlobalUses;
1697 MachineInstr *FirstLocalDef =
1698 LIS->getInstructionFromIndex(LocalLI->beginIndex());
1699 SUnit *FirstLocalSU = DAG->getSUnit(FirstLocalDef);
1700 for (SUnit::const_pred_iterator
1701 I = GlobalSU->Preds.begin(), E = GlobalSU->Preds.end(); I != E; ++I) {
1702 if (I->getKind() != SDep::Anti || I->getReg() != GlobalReg)
1703 continue;
1704 if (I->getSUnit() == FirstLocalSU)
1705 continue;
1706 if (!DAG->canAddEdge(FirstLocalSU, I->getSUnit()))
1707 return;
1708 GlobalUses.push_back(I->getSUnit());
1709 }
1710 DEBUG(dbgs() << "Constraining copy SU(" << CopySU->NodeNum << ")\n");
1711 // Add the weak edges.
1712 for (SmallVectorImpl<SUnit*>::const_iterator
1713 I = LocalUses.begin(), E = LocalUses.end(); I != E; ++I) {
1714 DEBUG(dbgs() << " Local use SU(" << (*I)->NodeNum << ") -> SU("
1715 << GlobalSU->NodeNum << ")\n");
1716 DAG->addEdge(GlobalSU, SDep(*I, SDep::Weak));
1717 }
1718 for (SmallVectorImpl<SUnit*>::const_iterator
1719 I = GlobalUses.begin(), E = GlobalUses.end(); I != E; ++I) {
1720 DEBUG(dbgs() << " Global use SU(" << (*I)->NodeNum << ") -> SU("
1721 << FirstLocalSU->NodeNum << ")\n");
1722 DAG->addEdge(FirstLocalSU, SDep(*I, SDep::Weak));
1723 }
1724}
1725
1726/// \brief Callback from DAG postProcessing to create weak edges to encourage
1727/// copy elimination.
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001728void CopyConstrain::apply(ScheduleDAGInstrs *DAGInstrs) {
1729 ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs);
Andrew Trickd7f890e2013-12-28 21:56:47 +00001730 assert(DAG->hasVRegLiveness() && "Expect VRegs with LiveIntervals");
1731
Andrew Trick2e875172013-04-24 23:19:56 +00001732 MachineBasicBlock::iterator FirstPos = nextIfDebug(DAG->begin(), DAG->end());
1733 if (FirstPos == DAG->end())
1734 return;
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001735 RegionBeginIdx = DAG->getLIS()->getInstructionIndex(*FirstPos);
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001736 RegionEndIdx = DAG->getLIS()->getInstructionIndex(
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001737 *priorNonDebug(DAG->end(), DAG->begin()));
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001738
1739 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
1740 SUnit *SU = &DAG->SUnits[Idx];
1741 if (!SU->getInstr()->isCopy())
1742 continue;
1743
Andrew Trickd7f890e2013-12-28 21:56:47 +00001744 constrainLocalCopy(SU, static_cast<ScheduleDAGMILive*>(DAG));
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001745 }
1746}
1747
1748//===----------------------------------------------------------------------===//
Andrew Trickfc127d12013-12-07 05:59:44 +00001749// MachineSchedStrategy helpers used by GenericScheduler, GenericPostScheduler
1750// and possibly other custom schedulers.
Andrew Trickd14d7c22013-12-28 21:56:57 +00001751//===----------------------------------------------------------------------===//
Andrew Tricke1c034f2012-01-17 06:55:03 +00001752
Andrew Trick5a22df42013-12-05 17:56:02 +00001753static const unsigned InvalidCycle = ~0U;
1754
Andrew Trickfc127d12013-12-07 05:59:44 +00001755SchedBoundary::~SchedBoundary() { delete HazardRec; }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001756
Andrew Trickfc127d12013-12-07 05:59:44 +00001757void SchedBoundary::reset() {
1758 // A new HazardRec is created for each DAG and owned by SchedBoundary.
1759 // Destroying and reconstructing it is very expensive though. So keep
1760 // invalid, placeholder HazardRecs.
1761 if (HazardRec && HazardRec->isEnabled()) {
1762 delete HazardRec;
Craig Topperc0196b12014-04-14 00:51:57 +00001763 HazardRec = nullptr;
Andrew Trickfc127d12013-12-07 05:59:44 +00001764 }
1765 Available.clear();
1766 Pending.clear();
1767 CheckPending = false;
1768 NextSUs.clear();
1769 CurrCycle = 0;
1770 CurrMOps = 0;
1771 MinReadyCycle = UINT_MAX;
1772 ExpectedLatency = 0;
1773 DependentLatency = 0;
1774 RetiredMOps = 0;
1775 MaxExecutedResCount = 0;
1776 ZoneCritResIdx = 0;
1777 IsResourceLimited = false;
1778 ReservedCycles.clear();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001779#ifndef NDEBUG
Andrew Trickd14d7c22013-12-28 21:56:57 +00001780 // Track the maximum number of stall cycles that could arise either from the
1781 // latency of a DAG edge or the number of cycles that a processor resource is
1782 // reserved (SchedBoundary::ReservedCycles).
Andrew Trick7f1ebbe2014-06-07 01:48:43 +00001783 MaxObservedStall = 0;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001784#endif
Andrew Trickfc127d12013-12-07 05:59:44 +00001785 // Reserve a zero-count for invalid CritResIdx.
1786 ExecutedResCounts.resize(1);
1787 assert(!ExecutedResCounts[0] && "nonzero count for bad resource");
1788}
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001789
Andrew Trickfc127d12013-12-07 05:59:44 +00001790void SchedRemainder::
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001791init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
1792 reset();
1793 if (!SchedModel->hasInstrSchedModel())
1794 return;
1795 RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
1796 for (std::vector<SUnit>::iterator
1797 I = DAG->SUnits.begin(), E = DAG->SUnits.end(); I != E; ++I) {
1798 const MCSchedClassDesc *SC = DAG->getSchedClass(&*I);
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001799 RemIssueCount += SchedModel->getNumMicroOps(I->getInstr(), SC)
1800 * SchedModel->getMicroOpFactor();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001801 for (TargetSchedModel::ProcResIter
1802 PI = SchedModel->getWriteProcResBegin(SC),
1803 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1804 unsigned PIdx = PI->ProcResourceIdx;
1805 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1806 RemainingCounts[PIdx] += (Factor * PI->Cycles);
1807 }
1808 }
1809}
1810
Andrew Trickfc127d12013-12-07 05:59:44 +00001811void SchedBoundary::
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001812init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
1813 reset();
1814 DAG = dag;
1815 SchedModel = smodel;
1816 Rem = rem;
Andrew Trick5a22df42013-12-05 17:56:02 +00001817 if (SchedModel->hasInstrSchedModel()) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001818 ExecutedResCounts.resize(SchedModel->getNumProcResourceKinds());
Andrew Trick5a22df42013-12-05 17:56:02 +00001819 ReservedCycles.resize(SchedModel->getNumProcResourceKinds(), InvalidCycle);
1820 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001821}
1822
Andrew Trick880e5732013-12-05 17:55:58 +00001823/// Compute the stall cycles based on this SUnit's ready time. Heuristics treat
1824/// these "soft stalls" differently than the hard stall cycles based on CPU
1825/// resources and computed by checkHazard(). A fully in-order model
1826/// (MicroOpBufferSize==0) will not make use of this since instructions are not
1827/// available for scheduling until they are ready. However, a weaker in-order
1828/// model may use this for heuristics. For example, if a processor has in-order
1829/// behavior when reading certain resources, this may come into play.
Andrew Trickfc127d12013-12-07 05:59:44 +00001830unsigned SchedBoundary::getLatencyStallCycles(SUnit *SU) {
Andrew Trick880e5732013-12-05 17:55:58 +00001831 if (!SU->isUnbuffered)
1832 return 0;
1833
1834 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
1835 if (ReadyCycle > CurrCycle)
1836 return ReadyCycle - CurrCycle;
1837 return 0;
1838}
1839
Andrew Trick5a22df42013-12-05 17:56:02 +00001840/// Compute the next cycle at which the given processor resource can be
1841/// scheduled.
Andrew Trickfc127d12013-12-07 05:59:44 +00001842unsigned SchedBoundary::
Andrew Trick5a22df42013-12-05 17:56:02 +00001843getNextResourceCycle(unsigned PIdx, unsigned Cycles) {
1844 unsigned NextUnreserved = ReservedCycles[PIdx];
1845 // If this resource has never been used, always return cycle zero.
1846 if (NextUnreserved == InvalidCycle)
1847 return 0;
1848 // For bottom-up scheduling add the cycles needed for the current operation.
1849 if (!isTop())
1850 NextUnreserved += Cycles;
1851 return NextUnreserved;
1852}
1853
Andrew Trick8c9e6722012-06-29 03:23:24 +00001854/// Does this SU have a hazard within the current instruction group.
1855///
1856/// The scheduler supports two modes of hazard recognition. The first is the
1857/// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
1858/// supports highly complicated in-order reservation tables
1859/// (ScoreboardHazardRecognizer) and arbitraty target-specific logic.
1860///
1861/// The second is a streamlined mechanism that checks for hazards based on
1862/// simple counters that the scheduler itself maintains. It explicitly checks
1863/// for instruction dispatch limitations, including the number of micro-ops that
1864/// can dispatch per cycle.
1865///
1866/// TODO: Also check whether the SU must start a new group.
Andrew Trickfc127d12013-12-07 05:59:44 +00001867bool SchedBoundary::checkHazard(SUnit *SU) {
Andrew Trickd14d7c22013-12-28 21:56:57 +00001868 if (HazardRec->isEnabled()
1869 && HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard) {
1870 return true;
1871 }
Andrew Trickdd79f0f2012-10-10 05:43:09 +00001872 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
Andrew Tricke2ff5752013-06-15 04:49:49 +00001873 if ((CurrMOps > 0) && (CurrMOps + uops > SchedModel->getIssueWidth())) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001874 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") uops="
1875 << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
Andrew Trick8c9e6722012-06-29 03:23:24 +00001876 return true;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001877 }
Andrew Trick5a22df42013-12-05 17:56:02 +00001878 if (SchedModel->hasInstrSchedModel() && SU->hasReservedResource) {
1879 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1880 for (TargetSchedModel::ProcResIter
1881 PI = SchedModel->getWriteProcResBegin(SC),
1882 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
Andrew Trick56327222014-06-27 04:57:05 +00001883 unsigned NRCycle = getNextResourceCycle(PI->ProcResourceIdx, PI->Cycles);
1884 if (NRCycle > CurrCycle) {
Andrew Trick040c0da2014-06-27 05:09:36 +00001885#ifndef NDEBUG
Chad Rosieraba845e2014-07-02 16:46:08 +00001886 MaxObservedStall = std::max(PI->Cycles, MaxObservedStall);
Andrew Trick040c0da2014-06-27 05:09:36 +00001887#endif
Andrew Trick56327222014-06-27 04:57:05 +00001888 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") "
1889 << SchedModel->getResourceName(PI->ProcResourceIdx)
1890 << "=" << NRCycle << "c\n");
Andrew Trick5a22df42013-12-05 17:56:02 +00001891 return true;
Andrew Trick56327222014-06-27 04:57:05 +00001892 }
Andrew Trick5a22df42013-12-05 17:56:02 +00001893 }
1894 }
Andrew Trick8c9e6722012-06-29 03:23:24 +00001895 return false;
1896}
1897
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001898// Find the unscheduled node in ReadySUs with the highest latency.
Andrew Trickfc127d12013-12-07 05:59:44 +00001899unsigned SchedBoundary::
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001900findMaxLatency(ArrayRef<SUnit*> ReadySUs) {
Craig Topperc0196b12014-04-14 00:51:57 +00001901 SUnit *LateSU = nullptr;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001902 unsigned RemLatency = 0;
1903 for (ArrayRef<SUnit*>::iterator I = ReadySUs.begin(), E = ReadySUs.end();
Andrew Trickd6d5ad32012-12-18 20:52:56 +00001904 I != E; ++I) {
1905 unsigned L = getUnscheduledLatency(*I);
Andrew Trickf5b8ef22013-06-15 04:49:44 +00001906 if (L > RemLatency) {
Andrew Trickd6d5ad32012-12-18 20:52:56 +00001907 RemLatency = L;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001908 LateSU = *I;
Andrew Trickf5b8ef22013-06-15 04:49:44 +00001909 }
Andrew Trickd6d5ad32012-12-18 20:52:56 +00001910 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001911 if (LateSU) {
1912 DEBUG(dbgs() << Available.getName() << " RemLatency SU("
1913 << LateSU->NodeNum << ") " << RemLatency << "c\n");
Andrew Trickd6d5ad32012-12-18 20:52:56 +00001914 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001915 return RemLatency;
1916}
Andrew Trickf5b8ef22013-06-15 04:49:44 +00001917
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001918// Count resources in this zone and the remaining unscheduled
1919// instruction. Return the max count, scaled. Set OtherCritIdx to the critical
1920// resource index, or zero if the zone is issue limited.
Andrew Trickfc127d12013-12-07 05:59:44 +00001921unsigned SchedBoundary::
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001922getOtherResourceCount(unsigned &OtherCritIdx) {
Alexey Samsonov64c391d2013-07-19 08:55:18 +00001923 OtherCritIdx = 0;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001924 if (!SchedModel->hasInstrSchedModel())
1925 return 0;
1926
1927 unsigned OtherCritCount = Rem->RemIssueCount
1928 + (RetiredMOps * SchedModel->getMicroOpFactor());
1929 DEBUG(dbgs() << " " << Available.getName() << " + Remain MOps: "
1930 << OtherCritCount / SchedModel->getMicroOpFactor() << '\n');
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001931 for (unsigned PIdx = 1, PEnd = SchedModel->getNumProcResourceKinds();
1932 PIdx != PEnd; ++PIdx) {
1933 unsigned OtherCount = getResourceCount(PIdx) + Rem->RemainingCounts[PIdx];
1934 if (OtherCount > OtherCritCount) {
1935 OtherCritCount = OtherCount;
1936 OtherCritIdx = PIdx;
1937 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001938 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001939 if (OtherCritIdx) {
1940 DEBUG(dbgs() << " " << Available.getName() << " + Remain CritRes: "
1941 << OtherCritCount / SchedModel->getResourceFactor(OtherCritIdx)
Andrew Trickfc127d12013-12-07 05:59:44 +00001942 << " " << SchedModel->getResourceName(OtherCritIdx) << "\n");
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001943 }
1944 return OtherCritCount;
1945}
1946
Andrew Trickfc127d12013-12-07 05:59:44 +00001947void SchedBoundary::releaseNode(SUnit *SU, unsigned ReadyCycle) {
Andrew Trick7f1ebbe2014-06-07 01:48:43 +00001948 assert(SU->getInstr() && "Scheduled SUnit must have instr");
1949
1950#ifndef NDEBUG
Andrew Trick491e34a2014-06-12 22:36:28 +00001951 // ReadyCycle was been bumped up to the CurrCycle when this node was
1952 // scheduled, but CurrCycle may have been eagerly advanced immediately after
1953 // scheduling, so may now be greater than ReadyCycle.
1954 if (ReadyCycle > CurrCycle)
1955 MaxObservedStall = std::max(ReadyCycle - CurrCycle, MaxObservedStall);
Andrew Trick7f1ebbe2014-06-07 01:48:43 +00001956#endif
1957
Andrew Trick61f1a272012-05-24 22:11:09 +00001958 if (ReadyCycle < MinReadyCycle)
1959 MinReadyCycle = ReadyCycle;
1960
1961 // Check for interlocks first. For the purpose of other heuristics, an
1962 // instruction that cannot issue appears as if it's not in the ReadyQueue.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001963 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
Matthias Braun6493bc22016-04-22 19:09:17 +00001964 if ((!IsBuffered && ReadyCycle > CurrCycle) || checkHazard(SU) ||
1965 Available.size() >= ReadyListLimit)
Andrew Trick61f1a272012-05-24 22:11:09 +00001966 Pending.push(SU);
1967 else
1968 Available.push(SU);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001969
1970 // Record this node as an immediate dependent of the scheduled node.
1971 NextSUs.insert(SU);
Andrew Trick61f1a272012-05-24 22:11:09 +00001972}
1973
Andrew Trickfc127d12013-12-07 05:59:44 +00001974void SchedBoundary::releaseTopNode(SUnit *SU) {
1975 if (SU->isScheduled)
1976 return;
1977
Andrew Trickfc127d12013-12-07 05:59:44 +00001978 releaseNode(SU, SU->TopReadyCycle);
1979}
1980
1981void SchedBoundary::releaseBottomNode(SUnit *SU) {
1982 if (SU->isScheduled)
1983 return;
1984
Andrew Trickfc127d12013-12-07 05:59:44 +00001985 releaseNode(SU, SU->BotReadyCycle);
1986}
1987
Andrew Trick61f1a272012-05-24 22:11:09 +00001988/// Move the boundary of scheduled code by one cycle.
Andrew Trickfc127d12013-12-07 05:59:44 +00001989void SchedBoundary::bumpCycle(unsigned NextCycle) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001990 if (SchedModel->getMicroOpBufferSize() == 0) {
1991 assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
1992 if (MinReadyCycle > NextCycle)
1993 NextCycle = MinReadyCycle;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001994 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001995 // Update the current micro-ops, which will issue in the next cycle.
1996 unsigned DecMOps = SchedModel->getIssueWidth() * (NextCycle - CurrCycle);
1997 CurrMOps = (CurrMOps <= DecMOps) ? 0 : CurrMOps - DecMOps;
1998
1999 // Decrement DependentLatency based on the next cycle.
Andrew Trickf5b8ef22013-06-15 04:49:44 +00002000 if ((NextCycle - CurrCycle) > DependentLatency)
2001 DependentLatency = 0;
2002 else
2003 DependentLatency -= (NextCycle - CurrCycle);
Andrew Trick61f1a272012-05-24 22:11:09 +00002004
2005 if (!HazardRec->isEnabled()) {
Andrew Trick45446062012-06-05 21:11:27 +00002006 // Bypass HazardRec virtual calls.
Andrew Trick61f1a272012-05-24 22:11:09 +00002007 CurrCycle = NextCycle;
Matthias Braunb550b762016-04-21 01:54:13 +00002008 } else {
Andrew Trick45446062012-06-05 21:11:27 +00002009 // Bypass getHazardType calls in case of long latency.
Andrew Trick61f1a272012-05-24 22:11:09 +00002010 for (; CurrCycle != NextCycle; ++CurrCycle) {
2011 if (isTop())
2012 HazardRec->AdvanceCycle();
2013 else
2014 HazardRec->RecedeCycle();
2015 }
2016 }
2017 CheckPending = true;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002018 unsigned LFactor = SchedModel->getLatencyFactor();
2019 IsResourceLimited =
2020 (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
2021 > (int)LFactor;
Andrew Trick61f1a272012-05-24 22:11:09 +00002022
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002023 DEBUG(dbgs() << "Cycle: " << CurrCycle << ' ' << Available.getName() << '\n');
2024}
2025
Andrew Trickfc127d12013-12-07 05:59:44 +00002026void SchedBoundary::incExecutedResources(unsigned PIdx, unsigned Count) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002027 ExecutedResCounts[PIdx] += Count;
2028 if (ExecutedResCounts[PIdx] > MaxExecutedResCount)
2029 MaxExecutedResCount = ExecutedResCounts[PIdx];
Andrew Trick61f1a272012-05-24 22:11:09 +00002030}
2031
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002032/// Add the given processor resource to this scheduled zone.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002033///
2034/// \param Cycles indicates the number of consecutive (non-pipelined) cycles
2035/// during which this resource is consumed.
2036///
2037/// \return the next cycle at which the instruction may execute without
2038/// oversubscribing resources.
Andrew Trickfc127d12013-12-07 05:59:44 +00002039unsigned SchedBoundary::
Andrew Trick5a22df42013-12-05 17:56:02 +00002040countResource(unsigned PIdx, unsigned Cycles, unsigned NextCycle) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002041 unsigned Factor = SchedModel->getResourceFactor(PIdx);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002042 unsigned Count = Factor * Cycles;
Andrew Trickfc127d12013-12-07 05:59:44 +00002043 DEBUG(dbgs() << " " << SchedModel->getResourceName(PIdx)
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002044 << " +" << Cycles << "x" << Factor << "u\n");
2045
2046 // Update Executed resources counts.
2047 incExecutedResources(PIdx, Count);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002048 assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
2049 Rem->RemainingCounts[PIdx] -= Count;
2050
Andrew Trickb13ef172013-07-19 00:20:07 +00002051 // Check if this resource exceeds the current critical resource. If so, it
2052 // becomes the critical resource.
2053 if (ZoneCritResIdx != PIdx && (getResourceCount(PIdx) > getCriticalCount())) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002054 ZoneCritResIdx = PIdx;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002055 DEBUG(dbgs() << " *** Critical resource "
Andrew Trickfc127d12013-12-07 05:59:44 +00002056 << SchedModel->getResourceName(PIdx) << ": "
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002057 << getResourceCount(PIdx) / SchedModel->getLatencyFactor() << "c\n");
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002058 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002059 // For reserved resources, record the highest cycle using the resource.
2060 unsigned NextAvailable = getNextResourceCycle(PIdx, Cycles);
2061 if (NextAvailable > CurrCycle) {
2062 DEBUG(dbgs() << " Resource conflict: "
2063 << SchedModel->getProcResource(PIdx)->Name << " reserved until @"
2064 << NextAvailable << "\n");
2065 }
2066 return NextAvailable;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002067}
2068
Andrew Trick45446062012-06-05 21:11:27 +00002069/// Move the boundary of scheduled code by one SUnit.
Andrew Trickfc127d12013-12-07 05:59:44 +00002070void SchedBoundary::bumpNode(SUnit *SU) {
Andrew Trick45446062012-06-05 21:11:27 +00002071 // Update the reservation table.
2072 if (HazardRec->isEnabled()) {
2073 if (!isTop() && SU->isCall) {
2074 // Calls are scheduled with their preceding instructions. For bottom-up
2075 // scheduling, clear the pipeline state before emitting.
2076 HazardRec->Reset();
2077 }
2078 HazardRec->EmitInstruction(SU);
2079 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002080 // checkHazard should prevent scheduling multiple instructions per cycle that
2081 // exceed the issue width.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002082 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
2083 unsigned IncMOps = SchedModel->getNumMicroOps(SU->getInstr());
Daniel Jasper0d92abd2013-12-06 08:58:22 +00002084 assert(
2085 (CurrMOps == 0 || (CurrMOps + IncMOps) <= SchedModel->getIssueWidth()) &&
Andrew Trickf7760a22013-12-06 17:19:20 +00002086 "Cannot schedule this instruction's MicroOps in the current cycle.");
Andrew Trick5a22df42013-12-05 17:56:02 +00002087
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002088 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
2089 DEBUG(dbgs() << " Ready @" << ReadyCycle << "c\n");
2090
Andrew Trick5a22df42013-12-05 17:56:02 +00002091 unsigned NextCycle = CurrCycle;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002092 switch (SchedModel->getMicroOpBufferSize()) {
2093 case 0:
2094 assert(ReadyCycle <= CurrCycle && "Broken PendingQueue");
2095 break;
2096 case 1:
2097 if (ReadyCycle > NextCycle) {
2098 NextCycle = ReadyCycle;
2099 DEBUG(dbgs() << " *** Stall until: " << ReadyCycle << "\n");
2100 }
2101 break;
2102 default:
2103 // We don't currently model the OOO reorder buffer, so consider all
Andrew Trick880e5732013-12-05 17:55:58 +00002104 // scheduled MOps to be "retired". We do loosely model in-order resource
2105 // latency. If this instruction uses an in-order resource, account for any
2106 // likely stall cycles.
2107 if (SU->isUnbuffered && ReadyCycle > NextCycle)
2108 NextCycle = ReadyCycle;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002109 break;
2110 }
2111 RetiredMOps += IncMOps;
2112
2113 // Update resource counts and critical resource.
2114 if (SchedModel->hasInstrSchedModel()) {
2115 unsigned DecRemIssue = IncMOps * SchedModel->getMicroOpFactor();
2116 assert(Rem->RemIssueCount >= DecRemIssue && "MOps double counted");
2117 Rem->RemIssueCount -= DecRemIssue;
2118 if (ZoneCritResIdx) {
2119 // Scale scheduled micro-ops for comparing with the critical resource.
2120 unsigned ScaledMOps =
2121 RetiredMOps * SchedModel->getMicroOpFactor();
2122
2123 // If scaled micro-ops are now more than the previous critical resource by
2124 // a full cycle, then micro-ops issue becomes critical.
2125 if ((int)(ScaledMOps - getResourceCount(ZoneCritResIdx))
2126 >= (int)SchedModel->getLatencyFactor()) {
2127 ZoneCritResIdx = 0;
2128 DEBUG(dbgs() << " *** Critical resource NumMicroOps: "
2129 << ScaledMOps / SchedModel->getLatencyFactor() << "c\n");
2130 }
2131 }
2132 for (TargetSchedModel::ProcResIter
2133 PI = SchedModel->getWriteProcResBegin(SC),
2134 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2135 unsigned RCycle =
Andrew Trick5a22df42013-12-05 17:56:02 +00002136 countResource(PI->ProcResourceIdx, PI->Cycles, NextCycle);
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002137 if (RCycle > NextCycle)
2138 NextCycle = RCycle;
2139 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002140 if (SU->hasReservedResource) {
2141 // For reserved resources, record the highest cycle using the resource.
2142 // For top-down scheduling, this is the cycle in which we schedule this
2143 // instruction plus the number of cycles the operations reserves the
2144 // resource. For bottom-up is it simply the instruction's cycle.
2145 for (TargetSchedModel::ProcResIter
2146 PI = SchedModel->getWriteProcResBegin(SC),
2147 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2148 unsigned PIdx = PI->ProcResourceIdx;
Andrew Trickd14d7c22013-12-28 21:56:57 +00002149 if (SchedModel->getProcResource(PIdx)->BufferSize == 0) {
Chad Rosieraba845e2014-07-02 16:46:08 +00002150 if (isTop()) {
2151 ReservedCycles[PIdx] =
2152 std::max(getNextResourceCycle(PIdx, 0), NextCycle + PI->Cycles);
2153 }
2154 else
2155 ReservedCycles[PIdx] = NextCycle;
Andrew Trickd14d7c22013-12-28 21:56:57 +00002156 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002157 }
2158 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002159 }
2160 // Update ExpectedLatency and DependentLatency.
2161 unsigned &TopLatency = isTop() ? ExpectedLatency : DependentLatency;
2162 unsigned &BotLatency = isTop() ? DependentLatency : ExpectedLatency;
2163 if (SU->getDepth() > TopLatency) {
2164 TopLatency = SU->getDepth();
2165 DEBUG(dbgs() << " " << Available.getName()
2166 << " TopLatency SU(" << SU->NodeNum << ") " << TopLatency << "c\n");
2167 }
2168 if (SU->getHeight() > BotLatency) {
2169 BotLatency = SU->getHeight();
2170 DEBUG(dbgs() << " " << Available.getName()
2171 << " BotLatency SU(" << SU->NodeNum << ") " << BotLatency << "c\n");
2172 }
2173 // If we stall for any reason, bump the cycle.
2174 if (NextCycle > CurrCycle) {
2175 bumpCycle(NextCycle);
Matthias Braunb550b762016-04-21 01:54:13 +00002176 } else {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002177 // After updating ZoneCritResIdx and ExpectedLatency, check if we're
Alp Tokercb402912014-01-24 17:20:08 +00002178 // resource limited. If a stall occurred, bumpCycle does this.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002179 unsigned LFactor = SchedModel->getLatencyFactor();
2180 IsResourceLimited =
2181 (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
2182 > (int)LFactor;
2183 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002184 // Update CurrMOps after calling bumpCycle to handle stalls, since bumpCycle
2185 // resets CurrMOps. Loop to handle instructions with more MOps than issue in
2186 // one cycle. Since we commonly reach the max MOps here, opportunistically
2187 // bump the cycle to avoid uselessly checking everything in the readyQ.
2188 CurrMOps += IncMOps;
2189 while (CurrMOps >= SchedModel->getIssueWidth()) {
Andrew Trick5a22df42013-12-05 17:56:02 +00002190 DEBUG(dbgs() << " *** Max MOps " << CurrMOps
2191 << " at cycle " << CurrCycle << '\n');
Andrew Trickd14d7c22013-12-28 21:56:57 +00002192 bumpCycle(++NextCycle);
Andrew Trick5a22df42013-12-05 17:56:02 +00002193 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002194 DEBUG(dumpScheduledState());
Andrew Trick45446062012-06-05 21:11:27 +00002195}
2196
Andrew Trick61f1a272012-05-24 22:11:09 +00002197/// Release pending ready nodes in to the available queue. This makes them
2198/// visible to heuristics.
Andrew Trickfc127d12013-12-07 05:59:44 +00002199void SchedBoundary::releasePending() {
Andrew Trick61f1a272012-05-24 22:11:09 +00002200 // If the available queue is empty, it is safe to reset MinReadyCycle.
2201 if (Available.empty())
2202 MinReadyCycle = UINT_MAX;
2203
2204 // Check to see if any of the pending instructions are ready to issue. If
2205 // so, add them to the available queue.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002206 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
Andrew Trick61f1a272012-05-24 22:11:09 +00002207 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
2208 SUnit *SU = *(Pending.begin()+i);
Andrew Trick45446062012-06-05 21:11:27 +00002209 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
Andrew Trick61f1a272012-05-24 22:11:09 +00002210
2211 if (ReadyCycle < MinReadyCycle)
2212 MinReadyCycle = ReadyCycle;
2213
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002214 if (!IsBuffered && ReadyCycle > CurrCycle)
Andrew Trick61f1a272012-05-24 22:11:09 +00002215 continue;
2216
Andrew Trick8c9e6722012-06-29 03:23:24 +00002217 if (checkHazard(SU))
Andrew Trick61f1a272012-05-24 22:11:09 +00002218 continue;
2219
Matthias Braun6493bc22016-04-22 19:09:17 +00002220 if (Available.size() >= ReadyListLimit)
2221 break;
2222
Andrew Trick61f1a272012-05-24 22:11:09 +00002223 Available.push(SU);
2224 Pending.remove(Pending.begin()+i);
2225 --i; --e;
2226 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002227 DEBUG(if (!Pending.empty()) Pending.dump());
Andrew Trick61f1a272012-05-24 22:11:09 +00002228 CheckPending = false;
2229}
2230
2231/// Remove SU from the ready set for this boundary.
Andrew Trickfc127d12013-12-07 05:59:44 +00002232void SchedBoundary::removeReady(SUnit *SU) {
Andrew Trick61f1a272012-05-24 22:11:09 +00002233 if (Available.isInQueue(SU))
2234 Available.remove(Available.find(SU));
2235 else {
2236 assert(Pending.isInQueue(SU) && "bad ready count");
2237 Pending.remove(Pending.find(SU));
2238 }
2239}
2240
2241/// If this queue only has one ready candidate, return it. As a side effect,
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002242/// defer any nodes that now hit a hazard, and advance the cycle until at least
2243/// one node is ready. If multiple instructions are ready, return NULL.
Andrew Trickfc127d12013-12-07 05:59:44 +00002244SUnit *SchedBoundary::pickOnlyChoice() {
Andrew Trick61f1a272012-05-24 22:11:09 +00002245 if (CheckPending)
2246 releasePending();
2247
Andrew Tricke2ff5752013-06-15 04:49:49 +00002248 if (CurrMOps > 0) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002249 // Defer any ready instrs that now have a hazard.
2250 for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
2251 if (checkHazard(*I)) {
2252 Pending.push(*I);
2253 I = Available.remove(I);
2254 continue;
2255 }
2256 ++I;
2257 }
2258 }
Andrew Trick61f1a272012-05-24 22:11:09 +00002259 for (unsigned i = 0; Available.empty(); ++i) {
Chad Rosieraba845e2014-07-02 16:46:08 +00002260// FIXME: Re-enable assert once PR20057 is resolved.
2261// assert(i <= (HazardRec->getMaxLookAhead() + MaxObservedStall) &&
2262// "permanent hazard");
2263 (void)i;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002264 bumpCycle(CurrCycle + 1);
Andrew Trick61f1a272012-05-24 22:11:09 +00002265 releasePending();
2266 }
2267 if (Available.size() == 1)
2268 return *Available.begin();
Craig Topperc0196b12014-04-14 00:51:57 +00002269 return nullptr;
Andrew Trick61f1a272012-05-24 22:11:09 +00002270}
2271
Andrew Trick8e8415f2013-06-15 05:46:47 +00002272#ifndef NDEBUG
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002273// This is useful information to dump after bumpNode.
2274// Note that the Queue contents are more useful before pickNodeFromQueue.
Andrew Trickfc127d12013-12-07 05:59:44 +00002275void SchedBoundary::dumpScheduledState() {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002276 unsigned ResFactor;
2277 unsigned ResCount;
2278 if (ZoneCritResIdx) {
2279 ResFactor = SchedModel->getResourceFactor(ZoneCritResIdx);
2280 ResCount = getResourceCount(ZoneCritResIdx);
Matthias Braunb550b762016-04-21 01:54:13 +00002281 } else {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002282 ResFactor = SchedModel->getMicroOpFactor();
2283 ResCount = RetiredMOps * SchedModel->getMicroOpFactor();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002284 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002285 unsigned LFactor = SchedModel->getLatencyFactor();
2286 dbgs() << Available.getName() << " @" << CurrCycle << "c\n"
2287 << " Retired: " << RetiredMOps;
2288 dbgs() << "\n Executed: " << getExecutedCount() / LFactor << "c";
2289 dbgs() << "\n Critical: " << ResCount / LFactor << "c, "
Andrew Trickfc127d12013-12-07 05:59:44 +00002290 << ResCount / ResFactor << " "
2291 << SchedModel->getResourceName(ZoneCritResIdx)
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002292 << "\n ExpectedLatency: " << ExpectedLatency << "c\n"
2293 << (IsResourceLimited ? " - Resource" : " - Latency")
2294 << " limited.\n";
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002295}
Andrew Trick8e8415f2013-06-15 05:46:47 +00002296#endif
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002297
Andrew Trickfc127d12013-12-07 05:59:44 +00002298//===----------------------------------------------------------------------===//
Andrew Trickd14d7c22013-12-28 21:56:57 +00002299// GenericScheduler - Generic implementation of MachineSchedStrategy.
Andrew Trickfc127d12013-12-07 05:59:44 +00002300//===----------------------------------------------------------------------===//
2301
Andrew Trickd14d7c22013-12-28 21:56:57 +00002302void GenericSchedulerBase::SchedCandidate::
2303initResourceDelta(const ScheduleDAGMI *DAG,
2304 const TargetSchedModel *SchedModel) {
2305 if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
2306 return;
2307
2308 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
2309 for (TargetSchedModel::ProcResIter
2310 PI = SchedModel->getWriteProcResBegin(SC),
2311 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2312 if (PI->ProcResourceIdx == Policy.ReduceResIdx)
2313 ResDelta.CritResources += PI->Cycles;
2314 if (PI->ProcResourceIdx == Policy.DemandResIdx)
2315 ResDelta.DemandedResources += PI->Cycles;
2316 }
2317}
2318
2319/// Set the CandPolicy given a scheduling zone given the current resources and
2320/// latencies inside and outside the zone.
Matthias Braunb550b762016-04-21 01:54:13 +00002321void GenericSchedulerBase::setPolicy(CandPolicy &Policy, bool IsPostRA,
Andrew Trickd14d7c22013-12-28 21:56:57 +00002322 SchedBoundary &CurrZone,
2323 SchedBoundary *OtherZone) {
Eric Christopher572e03a2015-06-19 01:53:21 +00002324 // Apply preemptive heuristics based on the total latency and resources
Andrew Trickd14d7c22013-12-28 21:56:57 +00002325 // inside and outside this zone. Potential stalls should be considered before
2326 // following this policy.
2327
2328 // Compute remaining latency. We need this both to determine whether the
2329 // overall schedule has become latency-limited and whether the instructions
2330 // outside this zone are resource or latency limited.
2331 //
2332 // The "dependent" latency is updated incrementally during scheduling as the
2333 // max height/depth of scheduled nodes minus the cycles since it was
2334 // scheduled:
2335 // DLat = max (N.depth - (CurrCycle - N.ReadyCycle) for N in Zone
2336 //
2337 // The "independent" latency is the max ready queue depth:
2338 // ILat = max N.depth for N in Available|Pending
2339 //
2340 // RemainingLatency is the greater of independent and dependent latency.
2341 unsigned RemLatency = CurrZone.getDependentLatency();
2342 RemLatency = std::max(RemLatency,
2343 CurrZone.findMaxLatency(CurrZone.Available.elements()));
2344 RemLatency = std::max(RemLatency,
2345 CurrZone.findMaxLatency(CurrZone.Pending.elements()));
2346
2347 // Compute the critical resource outside the zone.
Andrew Trick7afe4812013-12-28 22:25:57 +00002348 unsigned OtherCritIdx = 0;
Andrew Trickd14d7c22013-12-28 21:56:57 +00002349 unsigned OtherCount =
2350 OtherZone ? OtherZone->getOtherResourceCount(OtherCritIdx) : 0;
2351
2352 bool OtherResLimited = false;
2353 if (SchedModel->hasInstrSchedModel()) {
2354 unsigned LFactor = SchedModel->getLatencyFactor();
2355 OtherResLimited = (int)(OtherCount - (RemLatency * LFactor)) > (int)LFactor;
2356 }
2357 // Schedule aggressively for latency in PostRA mode. We don't check for
2358 // acyclic latency during PostRA, and highly out-of-order processors will
2359 // skip PostRA scheduling.
2360 if (!OtherResLimited) {
2361 if (IsPostRA || (RemLatency + CurrZone.getCurrCycle() > Rem.CriticalPath)) {
2362 Policy.ReduceLatency |= true;
2363 DEBUG(dbgs() << " " << CurrZone.Available.getName()
2364 << " RemainingLatency " << RemLatency << " + "
2365 << CurrZone.getCurrCycle() << "c > CritPath "
2366 << Rem.CriticalPath << "\n");
2367 }
2368 }
2369 // If the same resource is limiting inside and outside the zone, do nothing.
2370 if (CurrZone.getZoneCritResIdx() == OtherCritIdx)
2371 return;
2372
2373 DEBUG(
2374 if (CurrZone.isResourceLimited()) {
2375 dbgs() << " " << CurrZone.Available.getName() << " ResourceLimited: "
2376 << SchedModel->getResourceName(CurrZone.getZoneCritResIdx())
2377 << "\n";
2378 }
2379 if (OtherResLimited)
2380 dbgs() << " RemainingLimit: "
2381 << SchedModel->getResourceName(OtherCritIdx) << "\n";
2382 if (!CurrZone.isResourceLimited() && !OtherResLimited)
2383 dbgs() << " Latency limited both directions.\n");
2384
2385 if (CurrZone.isResourceLimited() && !Policy.ReduceResIdx)
2386 Policy.ReduceResIdx = CurrZone.getZoneCritResIdx();
2387
2388 if (OtherResLimited)
2389 Policy.DemandResIdx = OtherCritIdx;
2390}
2391
2392#ifndef NDEBUG
2393const char *GenericSchedulerBase::getReasonStr(
2394 GenericSchedulerBase::CandReason Reason) {
2395 switch (Reason) {
2396 case NoCand: return "NOCAND ";
2397 case PhysRegCopy: return "PREG-COPY";
2398 case RegExcess: return "REG-EXCESS";
2399 case RegCritical: return "REG-CRIT ";
2400 case Stall: return "STALL ";
2401 case Cluster: return "CLUSTER ";
2402 case Weak: return "WEAK ";
2403 case RegMax: return "REG-MAX ";
2404 case ResourceReduce: return "RES-REDUCE";
2405 case ResourceDemand: return "RES-DEMAND";
2406 case TopDepthReduce: return "TOP-DEPTH ";
2407 case TopPathReduce: return "TOP-PATH ";
2408 case BotHeightReduce:return "BOT-HEIGHT";
2409 case BotPathReduce: return "BOT-PATH ";
2410 case NextDefUse: return "DEF-USE ";
2411 case NodeOrder: return "ORDER ";
2412 };
2413 llvm_unreachable("Unknown reason!");
2414}
2415
2416void GenericSchedulerBase::traceCandidate(const SchedCandidate &Cand) {
2417 PressureChange P;
2418 unsigned ResIdx = 0;
2419 unsigned Latency = 0;
2420 switch (Cand.Reason) {
2421 default:
2422 break;
2423 case RegExcess:
2424 P = Cand.RPDelta.Excess;
2425 break;
2426 case RegCritical:
2427 P = Cand.RPDelta.CriticalMax;
2428 break;
2429 case RegMax:
2430 P = Cand.RPDelta.CurrentMax;
2431 break;
2432 case ResourceReduce:
2433 ResIdx = Cand.Policy.ReduceResIdx;
2434 break;
2435 case ResourceDemand:
2436 ResIdx = Cand.Policy.DemandResIdx;
2437 break;
2438 case TopDepthReduce:
2439 Latency = Cand.SU->getDepth();
2440 break;
2441 case TopPathReduce:
2442 Latency = Cand.SU->getHeight();
2443 break;
2444 case BotHeightReduce:
2445 Latency = Cand.SU->getHeight();
2446 break;
2447 case BotPathReduce:
2448 Latency = Cand.SU->getDepth();
2449 break;
2450 }
James Y Knighte72b0db2015-09-18 18:52:20 +00002451 dbgs() << " Cand SU(" << Cand.SU->NodeNum << ") " << getReasonStr(Cand.Reason);
Andrew Trickd14d7c22013-12-28 21:56:57 +00002452 if (P.isValid())
2453 dbgs() << " " << TRI->getRegPressureSetName(P.getPSet())
2454 << ":" << P.getUnitInc() << " ";
2455 else
2456 dbgs() << " ";
2457 if (ResIdx)
2458 dbgs() << " " << SchedModel->getProcResource(ResIdx)->Name << " ";
2459 else
2460 dbgs() << " ";
2461 if (Latency)
2462 dbgs() << " " << Latency << " cycles ";
2463 else
2464 dbgs() << " ";
2465 dbgs() << '\n';
2466}
2467#endif
2468
2469/// Return true if this heuristic determines order.
2470static bool tryLess(int TryVal, int CandVal,
2471 GenericSchedulerBase::SchedCandidate &TryCand,
2472 GenericSchedulerBase::SchedCandidate &Cand,
2473 GenericSchedulerBase::CandReason Reason) {
2474 if (TryVal < CandVal) {
2475 TryCand.Reason = Reason;
2476 return true;
2477 }
2478 if (TryVal > CandVal) {
2479 if (Cand.Reason > Reason)
2480 Cand.Reason = Reason;
2481 return true;
2482 }
2483 Cand.setRepeat(Reason);
2484 return false;
2485}
2486
2487static bool tryGreater(int TryVal, int CandVal,
2488 GenericSchedulerBase::SchedCandidate &TryCand,
2489 GenericSchedulerBase::SchedCandidate &Cand,
2490 GenericSchedulerBase::CandReason Reason) {
2491 if (TryVal > CandVal) {
2492 TryCand.Reason = Reason;
2493 return true;
2494 }
2495 if (TryVal < CandVal) {
2496 if (Cand.Reason > Reason)
2497 Cand.Reason = Reason;
2498 return true;
2499 }
2500 Cand.setRepeat(Reason);
2501 return false;
2502}
2503
2504static bool tryLatency(GenericSchedulerBase::SchedCandidate &TryCand,
2505 GenericSchedulerBase::SchedCandidate &Cand,
2506 SchedBoundary &Zone) {
2507 if (Zone.isTop()) {
2508 if (Cand.SU->getDepth() > Zone.getScheduledLatency()) {
2509 if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2510 TryCand, Cand, GenericSchedulerBase::TopDepthReduce))
2511 return true;
2512 }
2513 if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2514 TryCand, Cand, GenericSchedulerBase::TopPathReduce))
2515 return true;
Matthias Braunb550b762016-04-21 01:54:13 +00002516 } else {
Andrew Trickd14d7c22013-12-28 21:56:57 +00002517 if (Cand.SU->getHeight() > Zone.getScheduledLatency()) {
2518 if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2519 TryCand, Cand, GenericSchedulerBase::BotHeightReduce))
2520 return true;
2521 }
2522 if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2523 TryCand, Cand, GenericSchedulerBase::BotPathReduce))
2524 return true;
2525 }
2526 return false;
2527}
2528
2529static void tracePick(const GenericSchedulerBase::SchedCandidate &Cand,
2530 bool IsTop) {
2531 DEBUG(dbgs() << "Pick " << (IsTop ? "Top " : "Bot ")
2532 << GenericSchedulerBase::getReasonStr(Cand.Reason) << '\n');
2533}
2534
Andrew Trickfc127d12013-12-07 05:59:44 +00002535void GenericScheduler::initialize(ScheduleDAGMI *dag) {
Andrew Trickd7f890e2013-12-28 21:56:47 +00002536 assert(dag->hasVRegLiveness() &&
2537 "(PreRA)GenericScheduler needs vreg liveness");
2538 DAG = static_cast<ScheduleDAGMILive*>(dag);
Andrew Trickfc127d12013-12-07 05:59:44 +00002539 SchedModel = DAG->getSchedModel();
2540 TRI = DAG->TRI;
2541
2542 Rem.init(DAG, SchedModel);
2543 Top.init(DAG, SchedModel, &Rem);
2544 Bot.init(DAG, SchedModel, &Rem);
2545
2546 // Initialize resource counts.
2547
2548 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
2549 // are disabled, then these HazardRecs will be disabled.
2550 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
Andrew Trickfc127d12013-12-07 05:59:44 +00002551 if (!Top.HazardRec) {
2552 Top.HazardRec =
Eric Christopher99556d72014-10-14 06:56:25 +00002553 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
Eric Christopherd9134482014-08-04 21:25:23 +00002554 Itin, DAG);
Andrew Trickfc127d12013-12-07 05:59:44 +00002555 }
2556 if (!Bot.HazardRec) {
2557 Bot.HazardRec =
Eric Christopher99556d72014-10-14 06:56:25 +00002558 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
Eric Christopherd9134482014-08-04 21:25:23 +00002559 Itin, DAG);
Andrew Trickfc127d12013-12-07 05:59:44 +00002560 }
2561}
2562
2563/// Initialize the per-region scheduling policy.
2564void GenericScheduler::initPolicy(MachineBasicBlock::iterator Begin,
2565 MachineBasicBlock::iterator End,
2566 unsigned NumRegionInstrs) {
Eric Christopher99556d72014-10-14 06:56:25 +00002567 const MachineFunction &MF = *Begin->getParent()->getParent();
2568 const TargetLowering *TLI = MF.getSubtarget().getTargetLowering();
Andrew Trickfc127d12013-12-07 05:59:44 +00002569
2570 // Avoid setting up the register pressure tracker for small regions to save
2571 // compile time. As a rough heuristic, only track pressure when the number of
2572 // schedulable instructions exceeds half the integer register file.
Andrew Trick350ff2c2014-01-21 21:27:37 +00002573 RegionPolicy.ShouldTrackPressure = true;
Andrew Trick46753512014-01-22 03:38:55 +00002574 for (unsigned VT = MVT::i32; VT > (unsigned)MVT::i1; --VT) {
2575 MVT::SimpleValueType LegalIntVT = (MVT::SimpleValueType)VT;
2576 if (TLI->isTypeLegal(LegalIntVT)) {
Andrew Trick350ff2c2014-01-21 21:27:37 +00002577 unsigned NIntRegs = Context->RegClassInfo->getNumAllocatableRegs(
Andrew Trick46753512014-01-22 03:38:55 +00002578 TLI->getRegClassFor(LegalIntVT));
Andrew Trick350ff2c2014-01-21 21:27:37 +00002579 RegionPolicy.ShouldTrackPressure = NumRegionInstrs > (NIntRegs / 2);
2580 }
2581 }
Andrew Trickfc127d12013-12-07 05:59:44 +00002582
2583 // For generic targets, we default to bottom-up, because it's simpler and more
2584 // compile-time optimizations have been implemented in that direction.
2585 RegionPolicy.OnlyBottomUp = true;
2586
2587 // Allow the subtarget to override default policy.
Eric Christopher99556d72014-10-14 06:56:25 +00002588 MF.getSubtarget().overrideSchedPolicy(RegionPolicy, Begin, End,
2589 NumRegionInstrs);
Andrew Trickfc127d12013-12-07 05:59:44 +00002590
2591 // After subtarget overrides, apply command line options.
2592 if (!EnableRegPressure)
2593 RegionPolicy.ShouldTrackPressure = false;
2594
2595 // Check -misched-topdown/bottomup can force or unforce scheduling direction.
2596 // e.g. -misched-bottomup=false allows scheduling in both directions.
2597 assert((!ForceTopDown || !ForceBottomUp) &&
2598 "-misched-topdown incompatible with -misched-bottomup");
2599 if (ForceBottomUp.getNumOccurrences() > 0) {
2600 RegionPolicy.OnlyBottomUp = ForceBottomUp;
2601 if (RegionPolicy.OnlyBottomUp)
2602 RegionPolicy.OnlyTopDown = false;
2603 }
2604 if (ForceTopDown.getNumOccurrences() > 0) {
2605 RegionPolicy.OnlyTopDown = ForceTopDown;
2606 if (RegionPolicy.OnlyTopDown)
2607 RegionPolicy.OnlyBottomUp = false;
2608 }
2609}
2610
James Y Knighte72b0db2015-09-18 18:52:20 +00002611void GenericScheduler::dumpPolicy() {
2612 dbgs() << "GenericScheduler RegionPolicy: "
2613 << " ShouldTrackPressure=" << RegionPolicy.ShouldTrackPressure
2614 << " OnlyTopDown=" << RegionPolicy.OnlyTopDown
2615 << " OnlyBottomUp=" << RegionPolicy.OnlyBottomUp
2616 << "\n";
2617}
2618
Andrew Trickfc127d12013-12-07 05:59:44 +00002619/// Set IsAcyclicLatencyLimited if the acyclic path is longer than the cyclic
2620/// critical path by more cycles than it takes to drain the instruction buffer.
2621/// We estimate an upper bounds on in-flight instructions as:
2622///
2623/// CyclesPerIteration = max( CyclicPath, Loop-Resource-Height )
2624/// InFlightIterations = AcyclicPath / CyclesPerIteration
2625/// InFlightResources = InFlightIterations * LoopResources
2626///
2627/// TODO: Check execution resources in addition to IssueCount.
2628void GenericScheduler::checkAcyclicLatency() {
2629 if (Rem.CyclicCritPath == 0 || Rem.CyclicCritPath >= Rem.CriticalPath)
2630 return;
2631
2632 // Scaled number of cycles per loop iteration.
2633 unsigned IterCount =
2634 std::max(Rem.CyclicCritPath * SchedModel->getLatencyFactor(),
2635 Rem.RemIssueCount);
2636 // Scaled acyclic critical path.
2637 unsigned AcyclicCount = Rem.CriticalPath * SchedModel->getLatencyFactor();
2638 // InFlightCount = (AcyclicPath / IterCycles) * InstrPerLoop
2639 unsigned InFlightCount =
2640 (AcyclicCount * Rem.RemIssueCount + IterCount-1) / IterCount;
2641 unsigned BufferLimit =
2642 SchedModel->getMicroOpBufferSize() * SchedModel->getMicroOpFactor();
2643
2644 Rem.IsAcyclicLatencyLimited = InFlightCount > BufferLimit;
2645
2646 DEBUG(dbgs() << "IssueCycles="
2647 << Rem.RemIssueCount / SchedModel->getLatencyFactor() << "c "
2648 << "IterCycles=" << IterCount / SchedModel->getLatencyFactor()
2649 << "c NumIters=" << (AcyclicCount + IterCount-1) / IterCount
2650 << " InFlight=" << InFlightCount / SchedModel->getMicroOpFactor()
2651 << "m BufferLim=" << SchedModel->getMicroOpBufferSize() << "m\n";
2652 if (Rem.IsAcyclicLatencyLimited)
2653 dbgs() << " ACYCLIC LATENCY LIMIT\n");
2654}
2655
2656void GenericScheduler::registerRoots() {
2657 Rem.CriticalPath = DAG->ExitSU.getDepth();
2658
2659 // Some roots may not feed into ExitSU. Check all of them in case.
2660 for (std::vector<SUnit*>::const_iterator
2661 I = Bot.Available.begin(), E = Bot.Available.end(); I != E; ++I) {
2662 if ((*I)->getDepth() > Rem.CriticalPath)
2663 Rem.CriticalPath = (*I)->getDepth();
2664 }
Gerolf Hoflehnerb5220dc2014-08-07 21:49:44 +00002665 DEBUG(dbgs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << '\n');
2666 if (DumpCriticalPathLength) {
2667 errs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << " \n";
2668 }
Andrew Trickfc127d12013-12-07 05:59:44 +00002669
2670 if (EnableCyclicPath) {
2671 Rem.CyclicCritPath = DAG->computeCyclicCriticalPath();
2672 checkAcyclicLatency();
2673 }
2674}
2675
Andrew Trick1a831342013-08-30 03:49:48 +00002676static bool tryPressure(const PressureChange &TryP,
2677 const PressureChange &CandP,
Andrew Trickd14d7c22013-12-28 21:56:57 +00002678 GenericSchedulerBase::SchedCandidate &TryCand,
2679 GenericSchedulerBase::SchedCandidate &Cand,
Tom Stellard5ce53062015-12-16 18:31:01 +00002680 GenericSchedulerBase::CandReason Reason,
2681 const TargetRegisterInfo *TRI,
2682 const MachineFunction &MF) {
2683 unsigned TryPSet = TryP.getPSetOrMax();
2684 unsigned CandPSet = CandP.getPSetOrMax();
Andrew Trickb1a45b62013-08-30 04:27:29 +00002685 // If both candidates affect the same set, go with the smallest increase.
Tom Stellard5ce53062015-12-16 18:31:01 +00002686 if (TryPSet == CandPSet) {
Andrew Trickb1a45b62013-08-30 04:27:29 +00002687 return tryLess(TryP.getUnitInc(), CandP.getUnitInc(), TryCand, Cand,
2688 Reason);
Andrew Trick401b6952013-07-25 07:26:35 +00002689 }
Andrew Trickb1a45b62013-08-30 04:27:29 +00002690 // If one candidate decreases and the other increases, go with it.
2691 // Invalid candidates have UnitInc==0.
Hal Finkel7a87f8a2014-10-10 17:06:20 +00002692 if (tryGreater(TryP.getUnitInc() < 0, CandP.getUnitInc() < 0, TryCand, Cand,
2693 Reason)) {
Andrew Trickb1a45b62013-08-30 04:27:29 +00002694 return true;
2695 }
Tom Stellard5ce53062015-12-16 18:31:01 +00002696
2697 int TryRank = TryP.isValid() ? TRI->getRegPressureSetScore(MF, TryPSet) :
2698 std::numeric_limits<int>::max();
2699
2700 int CandRank = CandP.isValid() ? TRI->getRegPressureSetScore(MF, CandPSet) :
2701 std::numeric_limits<int>::max();
2702
Andrew Trick401b6952013-07-25 07:26:35 +00002703 // If the candidates are decreasing pressure, reverse priority.
Andrew Trick1a831342013-08-30 03:49:48 +00002704 if (TryP.getUnitInc() < 0)
Andrew Trick401b6952013-07-25 07:26:35 +00002705 std::swap(TryRank, CandRank);
2706 return tryGreater(TryRank, CandRank, TryCand, Cand, Reason);
2707}
2708
Andrew Tricka7714a02012-11-12 19:40:10 +00002709static unsigned getWeakLeft(const SUnit *SU, bool isTop) {
2710 return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
2711}
2712
Andrew Tricke833e1c2013-04-13 06:07:40 +00002713/// Minimize physical register live ranges. Regalloc wants them adjacent to
2714/// their physreg def/use.
2715///
2716/// FIXME: This is an unnecessary check on the critical path. Most are root/leaf
2717/// copies which can be prescheduled. The rest (e.g. x86 MUL) could be bundled
2718/// with the operation that produces or consumes the physreg. We'll do this when
2719/// regalloc has support for parallel copies.
2720static int biasPhysRegCopy(const SUnit *SU, bool isTop) {
2721 const MachineInstr *MI = SU->getInstr();
2722 if (!MI->isCopy())
2723 return 0;
2724
2725 unsigned ScheduledOper = isTop ? 1 : 0;
2726 unsigned UnscheduledOper = isTop ? 0 : 1;
2727 // If we have already scheduled the physreg produce/consumer, immediately
2728 // schedule the copy.
2729 if (TargetRegisterInfo::isPhysicalRegister(
2730 MI->getOperand(ScheduledOper).getReg()))
2731 return 1;
2732 // If the physreg is at the boundary, defer it. Otherwise schedule it
2733 // immediately to free the dependent. We can hoist the copy later.
2734 bool AtBoundary = isTop ? !SU->NumSuccsLeft : !SU->NumPredsLeft;
2735 if (TargetRegisterInfo::isPhysicalRegister(
2736 MI->getOperand(UnscheduledOper).getReg()))
2737 return AtBoundary ? -1 : 1;
2738 return 0;
2739}
2740
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002741/// Apply a set of heursitics to a new candidate. Heuristics are currently
2742/// hierarchical. This may be more efficient than a graduated cost model because
2743/// we don't need to evaluate all aspects of the model for each node in the
2744/// queue. But it's really done to make the heuristics easier to debug and
2745/// statistically analyze.
2746///
2747/// \param Cand provides the policy and current best candidate.
2748/// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
2749/// \param Zone describes the scheduled zone that we are extending.
2750/// \param RPTracker describes reg pressure within the scheduled zone.
2751/// \param TempTracker is a scratch pressure tracker to reuse in queries.
Andrew Trick665d3ec2013-09-19 23:10:59 +00002752void GenericScheduler::tryCandidate(SchedCandidate &Cand,
Andrew Trickbb1247b2013-12-05 17:55:47 +00002753 SchedCandidate &TryCand,
2754 SchedBoundary &Zone,
2755 const RegPressureTracker &RPTracker,
2756 RegPressureTracker &TempTracker) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002757
Andrew Trick66c3dfb2013-09-04 21:00:11 +00002758 if (DAG->isTrackingPressure()) {
Andrew Trick310190e2013-09-04 21:00:02 +00002759 // Always initialize TryCand's RPDelta.
2760 if (Zone.isTop()) {
2761 TempTracker.getMaxDownwardPressureDelta(
Andrew Trick1a831342013-08-30 03:49:48 +00002762 TryCand.SU->getInstr(),
Andrew Trick1a831342013-08-30 03:49:48 +00002763 TryCand.RPDelta,
2764 DAG->getRegionCriticalPSets(),
2765 DAG->getRegPressure().MaxSetPressure);
Matthias Braunb550b762016-04-21 01:54:13 +00002766 } else {
Andrew Trick310190e2013-09-04 21:00:02 +00002767 if (VerifyScheduling) {
2768 TempTracker.getMaxUpwardPressureDelta(
2769 TryCand.SU->getInstr(),
2770 &DAG->getPressureDiff(TryCand.SU),
2771 TryCand.RPDelta,
2772 DAG->getRegionCriticalPSets(),
2773 DAG->getRegPressure().MaxSetPressure);
Matthias Braunb550b762016-04-21 01:54:13 +00002774 } else {
Andrew Trick310190e2013-09-04 21:00:02 +00002775 RPTracker.getUpwardPressureDelta(
2776 TryCand.SU->getInstr(),
2777 DAG->getPressureDiff(TryCand.SU),
2778 TryCand.RPDelta,
2779 DAG->getRegionCriticalPSets(),
2780 DAG->getRegPressure().MaxSetPressure);
2781 }
Andrew Trick1a831342013-08-30 03:49:48 +00002782 }
2783 }
Andrew Trickc573cd92013-09-06 17:32:44 +00002784 DEBUG(if (TryCand.RPDelta.Excess.isValid())
James Y Knighte72b0db2015-09-18 18:52:20 +00002785 dbgs() << " Try SU(" << TryCand.SU->NodeNum << ") "
Andrew Trickc573cd92013-09-06 17:32:44 +00002786 << TRI->getRegPressureSetName(TryCand.RPDelta.Excess.getPSet())
2787 << ":" << TryCand.RPDelta.Excess.getUnitInc() << "\n");
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002788
2789 // Initialize the candidate if needed.
2790 if (!Cand.isValid()) {
2791 TryCand.Reason = NodeOrder;
2792 return;
2793 }
Andrew Tricke833e1c2013-04-13 06:07:40 +00002794
2795 if (tryGreater(biasPhysRegCopy(TryCand.SU, Zone.isTop()),
2796 biasPhysRegCopy(Cand.SU, Zone.isTop()),
2797 TryCand, Cand, PhysRegCopy))
2798 return;
2799
Andrew Tricke02d5da2015-05-17 23:40:27 +00002800 // Avoid exceeding the target's limit.
Andrew Trick66c3dfb2013-09-04 21:00:11 +00002801 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.Excess,
2802 Cand.RPDelta.Excess,
Tom Stellard5ce53062015-12-16 18:31:01 +00002803 TryCand, Cand, RegExcess, TRI,
2804 DAG->MF))
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002805 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002806
2807 // Avoid increasing the max critical pressure in the scheduled region.
Andrew Trick66c3dfb2013-09-04 21:00:11 +00002808 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CriticalMax,
2809 Cand.RPDelta.CriticalMax,
Tom Stellard5ce53062015-12-16 18:31:01 +00002810 TryCand, Cand, RegCritical, TRI,
2811 DAG->MF))
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002812 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002813
Andrew Trickddffae92013-09-06 17:32:36 +00002814 // For loops that are acyclic path limited, aggressively schedule for latency.
Andrew Tricke1f7bf22013-09-09 22:28:08 +00002815 // This can result in very long dependence chains scheduled in sequence, so
2816 // once every cycle (when CurrMOps == 0), switch to normal heuristics.
Andrew Trickfc127d12013-12-07 05:59:44 +00002817 if (Rem.IsAcyclicLatencyLimited && !Zone.getCurrMOps()
Andrew Tricke1f7bf22013-09-09 22:28:08 +00002818 && tryLatency(TryCand, Cand, Zone))
Andrew Trickddffae92013-09-06 17:32:36 +00002819 return;
2820
Andrew Trick880e5732013-12-05 17:55:58 +00002821 // Prioritize instructions that read unbuffered resources by stall cycles.
2822 if (tryLess(Zone.getLatencyStallCycles(TryCand.SU),
2823 Zone.getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
2824 return;
2825
Andrew Tricka7714a02012-11-12 19:40:10 +00002826 // Keep clustered nodes together to encourage downstream peephole
2827 // optimizations which may reduce resource requirements.
2828 //
2829 // This is a best effort to set things up for a post-RA pass. Optimizations
2830 // like generating loads of multiple registers should ideally be done within
2831 // the scheduler pass by combining the loads during DAG postprocessing.
2832 const SUnit *NextClusterSU =
2833 Zone.isTop() ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
2834 if (tryGreater(TryCand.SU == NextClusterSU, Cand.SU == NextClusterSU,
2835 TryCand, Cand, Cluster))
2836 return;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00002837
2838 // Weak edges are for clustering and other constraints.
Andrew Tricka7714a02012-11-12 19:40:10 +00002839 if (tryLess(getWeakLeft(TryCand.SU, Zone.isTop()),
2840 getWeakLeft(Cand.SU, Zone.isTop()),
Andrew Trick85a1d4c2013-04-24 15:54:43 +00002841 TryCand, Cand, Weak)) {
Andrew Tricka7714a02012-11-12 19:40:10 +00002842 return;
2843 }
Andrew Trick71f08a32013-06-17 21:45:13 +00002844 // Avoid increasing the max pressure of the entire region.
Andrew Trick66c3dfb2013-09-04 21:00:11 +00002845 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CurrentMax,
2846 Cand.RPDelta.CurrentMax,
Tom Stellard5ce53062015-12-16 18:31:01 +00002847 TryCand, Cand, RegMax, TRI,
2848 DAG->MF))
Andrew Trick71f08a32013-06-17 21:45:13 +00002849 return;
2850
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002851 // Avoid critical resource consumption and balance the schedule.
2852 TryCand.initResourceDelta(DAG, SchedModel);
2853 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
2854 TryCand, Cand, ResourceReduce))
2855 return;
2856 if (tryGreater(TryCand.ResDelta.DemandedResources,
2857 Cand.ResDelta.DemandedResources,
2858 TryCand, Cand, ResourceDemand))
2859 return;
2860
2861 // Avoid serializing long latency dependence chains.
Andrew Trickc01b0042013-08-23 17:48:43 +00002862 // For acyclic path limited loops, latency was already checked above.
Matthias Braun61f4d642015-10-22 18:07:31 +00002863 if (!RegionPolicy.DisableLatencyHeuristic && Cand.Policy.ReduceLatency &&
2864 !Rem.IsAcyclicLatencyLimited && tryLatency(TryCand, Cand, Zone)) {
Andrew Trickc01b0042013-08-23 17:48:43 +00002865 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002866 }
2867
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002868 // Prefer immediate defs/users of the last scheduled instruction. This is a
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002869 // local pressure avoidance strategy that also makes the machine code
2870 // readable.
Andrew Trickfc127d12013-12-07 05:59:44 +00002871 if (tryGreater(Zone.isNextSU(TryCand.SU), Zone.isNextSU(Cand.SU),
Andrew Tricka7714a02012-11-12 19:40:10 +00002872 TryCand, Cand, NextDefUse))
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002873 return;
Andrew Tricka7714a02012-11-12 19:40:10 +00002874
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002875 // Fall through to original instruction order.
2876 if ((Zone.isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
2877 || (!Zone.isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
2878 TryCand.Reason = NodeOrder;
2879 }
2880}
Andrew Trick419eae22012-05-10 21:06:19 +00002881
Andrew Trickc573cd92013-09-06 17:32:44 +00002882/// Pick the best candidate from the queue.
Andrew Trick7ee9de52012-05-10 21:06:16 +00002883///
2884/// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
2885/// DAG building. To adjust for the current scheduling location we need to
2886/// maintain the number of vreg uses remaining to be top-scheduled.
Andrew Trick665d3ec2013-09-19 23:10:59 +00002887void GenericScheduler::pickNodeFromQueue(SchedBoundary &Zone,
Andrew Trickbb1247b2013-12-05 17:55:47 +00002888 const RegPressureTracker &RPTracker,
2889 SchedCandidate &Cand) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002890 ReadyQueue &Q = Zone.Available;
2891
Andrew Tricka8ad5f72012-05-24 22:11:12 +00002892 DEBUG(Q.dump());
Andrew Trick22025772012-05-17 18:35:10 +00002893
Andrew Trick7ee9de52012-05-10 21:06:16 +00002894 // getMaxPressureDelta temporarily modifies the tracker.
2895 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
2896
Andrew Trickdd375dd2012-05-24 22:11:03 +00002897 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
Andrew Trick7ee9de52012-05-10 21:06:16 +00002898
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002899 SchedCandidate TryCand(Cand.Policy);
2900 TryCand.SU = *I;
2901 tryCandidate(Cand, TryCand, Zone, RPTracker, TempTracker);
2902 if (TryCand.Reason != NoCand) {
2903 // Initialize resource delta if needed in case future heuristics query it.
2904 if (TryCand.ResDelta == SchedResourceDelta())
2905 TryCand.initResourceDelta(DAG, SchedModel);
2906 Cand.setBest(TryCand);
Andrew Trick419d4912013-04-05 00:31:29 +00002907 DEBUG(traceCandidate(Cand));
Andrew Trick22025772012-05-17 18:35:10 +00002908 }
Andrew Trick7ee9de52012-05-10 21:06:16 +00002909 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002910}
2911
Andrew Trick22025772012-05-17 18:35:10 +00002912/// Pick the best candidate node from either the top or bottom queue.
Andrew Trick665d3ec2013-09-19 23:10:59 +00002913SUnit *GenericScheduler::pickNodeBidirectional(bool &IsTopNode) {
Andrew Trick22025772012-05-17 18:35:10 +00002914 // Schedule as far as possible in the direction of no choice. This is most
2915 // efficient, but also provides the best heuristics for CriticalPSets.
Andrew Trick61f1a272012-05-24 22:11:09 +00002916 if (SUnit *SU = Bot.pickOnlyChoice()) {
Andrew Trick22025772012-05-17 18:35:10 +00002917 IsTopNode = false;
Matthias Braun3b099db2015-11-13 22:30:29 +00002918 DEBUG(dbgs() << "Pick Bot ONLY1\n");
Andrew Trick61f1a272012-05-24 22:11:09 +00002919 return SU;
Andrew Trick22025772012-05-17 18:35:10 +00002920 }
Andrew Trick61f1a272012-05-24 22:11:09 +00002921 if (SUnit *SU = Top.pickOnlyChoice()) {
Andrew Trick22025772012-05-17 18:35:10 +00002922 IsTopNode = true;
Matthias Braun3b099db2015-11-13 22:30:29 +00002923 DEBUG(dbgs() << "Pick Top ONLY1\n");
Andrew Trick61f1a272012-05-24 22:11:09 +00002924 return SU;
Andrew Trick22025772012-05-17 18:35:10 +00002925 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002926 CandPolicy NoPolicy;
2927 SchedCandidate BotCand(NoPolicy);
2928 SchedCandidate TopCand(NoPolicy);
Andrew Trickfc127d12013-12-07 05:59:44 +00002929 // Set the bottom-up policy based on the state of the current bottom zone and
2930 // the instructions outside the zone, including the top zone.
Andrew Trickd14d7c22013-12-28 21:56:57 +00002931 setPolicy(BotCand.Policy, /*IsPostRA=*/false, Bot, &Top);
Andrew Trickfc127d12013-12-07 05:59:44 +00002932 // Set the top-down policy based on the state of the current top zone and
2933 // the instructions outside the zone, including the bottom zone.
Andrew Trickd14d7c22013-12-28 21:56:57 +00002934 setPolicy(TopCand.Policy, /*IsPostRA=*/false, Top, &Bot);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002935
Andrew Trick22025772012-05-17 18:35:10 +00002936 // Prefer bottom scheduling when heuristics are silent.
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002937 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
2938 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick22025772012-05-17 18:35:10 +00002939
2940 // If either Q has a single candidate that provides the least increase in
2941 // Excess pressure, we can immediately schedule from that Q.
2942 //
2943 // RegionCriticalPSets summarizes the pressure within the scheduled region and
2944 // affects picking from either Q. If scheduling in one direction must
2945 // increase pressure for one of the excess PSets, then schedule in that
2946 // direction first to provide more freedom in the other direction.
Andrew Trickd40d0f22013-06-17 21:45:05 +00002947 if ((BotCand.Reason == RegExcess && !BotCand.isRepeat(RegExcess))
Matthias Braunb550b762016-04-21 01:54:13 +00002948 || (BotCand.Reason == RegCritical && !BotCand.isRepeat(RegCritical)))
Andrew Trickd40d0f22013-06-17 21:45:05 +00002949 {
Andrew Trick22025772012-05-17 18:35:10 +00002950 IsTopNode = false;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002951 tracePick(BotCand, IsTopNode);
Andrew Trick61f1a272012-05-24 22:11:09 +00002952 return BotCand.SU;
Andrew Trick22025772012-05-17 18:35:10 +00002953 }
2954 // Check if the top Q has a better candidate.
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002955 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
2956 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
Andrew Trick22025772012-05-17 18:35:10 +00002957
Andrew Trickd40d0f22013-06-17 21:45:05 +00002958 // Choose the queue with the most important (lowest enum) reason.
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002959 if (TopCand.Reason < BotCand.Reason) {
2960 IsTopNode = true;
2961 tracePick(TopCand, IsTopNode);
2962 return TopCand.SU;
2963 }
Andrew Trickd40d0f22013-06-17 21:45:05 +00002964 // Otherwise prefer the bottom candidate, in node order if all else failed.
Andrew Trick22025772012-05-17 18:35:10 +00002965 IsTopNode = false;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002966 tracePick(BotCand, IsTopNode);
Andrew Trick61f1a272012-05-24 22:11:09 +00002967 return BotCand.SU;
Andrew Trick22025772012-05-17 18:35:10 +00002968}
2969
2970/// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
Andrew Trick665d3ec2013-09-19 23:10:59 +00002971SUnit *GenericScheduler::pickNode(bool &IsTopNode) {
Andrew Trick7ee9de52012-05-10 21:06:16 +00002972 if (DAG->top() == DAG->bottom()) {
Andrew Trick61f1a272012-05-24 22:11:09 +00002973 assert(Top.Available.empty() && Top.Pending.empty() &&
2974 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
Craig Topperc0196b12014-04-14 00:51:57 +00002975 return nullptr;
Andrew Trick7ee9de52012-05-10 21:06:16 +00002976 }
Andrew Trick7ee9de52012-05-10 21:06:16 +00002977 SUnit *SU;
Andrew Trick984d98b2012-10-08 18:53:53 +00002978 do {
Andrew Trick75e411c2013-09-06 17:32:34 +00002979 if (RegionPolicy.OnlyTopDown) {
Andrew Trick984d98b2012-10-08 18:53:53 +00002980 SU = Top.pickOnlyChoice();
2981 if (!SU) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002982 CandPolicy NoPolicy;
2983 SchedCandidate TopCand(NoPolicy);
2984 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
Andrew Trick1ab16d92013-09-04 21:00:13 +00002985 assert(TopCand.Reason != NoCand && "failed to find a candidate");
Andrew Trickef54c592013-09-04 21:00:16 +00002986 tracePick(TopCand, true);
Andrew Trick984d98b2012-10-08 18:53:53 +00002987 SU = TopCand.SU;
2988 }
2989 IsTopNode = true;
Matthias Braunb550b762016-04-21 01:54:13 +00002990 } else if (RegionPolicy.OnlyBottomUp) {
Andrew Trick984d98b2012-10-08 18:53:53 +00002991 SU = Bot.pickOnlyChoice();
2992 if (!SU) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002993 CandPolicy NoPolicy;
2994 SchedCandidate BotCand(NoPolicy);
2995 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
Andrew Trick1ab16d92013-09-04 21:00:13 +00002996 assert(BotCand.Reason != NoCand && "failed to find a candidate");
Andrew Trickef54c592013-09-04 21:00:16 +00002997 tracePick(BotCand, false);
Andrew Trick984d98b2012-10-08 18:53:53 +00002998 SU = BotCand.SU;
2999 }
3000 IsTopNode = false;
Matthias Braunb550b762016-04-21 01:54:13 +00003001 } else {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003002 SU = pickNodeBidirectional(IsTopNode);
Andrew Trick984d98b2012-10-08 18:53:53 +00003003 }
3004 } while (SU->isScheduled);
3005
Andrew Trick61f1a272012-05-24 22:11:09 +00003006 if (SU->isTopReady())
3007 Top.removeReady(SU);
3008 if (SU->isBottomReady())
3009 Bot.removeReady(SU);
Andrew Trick4e7f6a72012-05-25 02:02:39 +00003010
Andrew Trick1f0bb692013-04-13 06:07:49 +00003011 DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " << *SU->getInstr());
Andrew Trick7ee9de52012-05-10 21:06:16 +00003012 return SU;
3013}
3014
Andrew Trick665d3ec2013-09-19 23:10:59 +00003015void GenericScheduler::reschedulePhysRegCopies(SUnit *SU, bool isTop) {
Andrew Tricke833e1c2013-04-13 06:07:40 +00003016
3017 MachineBasicBlock::iterator InsertPos = SU->getInstr();
3018 if (!isTop)
3019 ++InsertPos;
3020 SmallVectorImpl<SDep> &Deps = isTop ? SU->Preds : SU->Succs;
3021
3022 // Find already scheduled copies with a single physreg dependence and move
3023 // them just above the scheduled instruction.
3024 for (SmallVectorImpl<SDep>::iterator I = Deps.begin(), E = Deps.end();
3025 I != E; ++I) {
3026 if (I->getKind() != SDep::Data || !TRI->isPhysicalRegister(I->getReg()))
3027 continue;
3028 SUnit *DepSU = I->getSUnit();
3029 if (isTop ? DepSU->Succs.size() > 1 : DepSU->Preds.size() > 1)
3030 continue;
3031 MachineInstr *Copy = DepSU->getInstr();
3032 if (!Copy->isCopy())
3033 continue;
3034 DEBUG(dbgs() << " Rescheduling physreg copy ";
3035 I->getSUnit()->dump(DAG));
3036 DAG->moveInstruction(Copy, InsertPos);
3037 }
3038}
3039
Andrew Trick61f1a272012-05-24 22:11:09 +00003040/// Update the scheduler's state after scheduling a node. This is the same node
Andrew Trickd14d7c22013-12-28 21:56:57 +00003041/// that was just returned by pickNode(). However, ScheduleDAGMILive needs to
3042/// update it's state based on the current cycle before MachineSchedStrategy
3043/// does.
Andrew Tricke833e1c2013-04-13 06:07:40 +00003044///
3045/// FIXME: Eventually, we may bundle physreg copies rather than rescheduling
3046/// them here. See comments in biasPhysRegCopy.
Andrew Trick665d3ec2013-09-19 23:10:59 +00003047void GenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
Andrew Trick45446062012-06-05 21:11:27 +00003048 if (IsTopNode) {
Andrew Trickfc127d12013-12-07 05:59:44 +00003049 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
Andrew Trickce27bb92012-06-29 03:23:22 +00003050 Top.bumpNode(SU);
Andrew Tricke833e1c2013-04-13 06:07:40 +00003051 if (SU->hasPhysRegUses)
3052 reschedulePhysRegCopies(SU, true);
Matthias Braunb550b762016-04-21 01:54:13 +00003053 } else {
Andrew Trickfc127d12013-12-07 05:59:44 +00003054 SU->BotReadyCycle = std::max(SU->BotReadyCycle, Bot.getCurrCycle());
Andrew Trickce27bb92012-06-29 03:23:22 +00003055 Bot.bumpNode(SU);
Andrew Tricke833e1c2013-04-13 06:07:40 +00003056 if (SU->hasPhysRegDefs)
3057 reschedulePhysRegCopies(SU, false);
Andrew Trick61f1a272012-05-24 22:11:09 +00003058 }
3059}
3060
Andrew Trick8823dec2012-03-14 04:00:41 +00003061/// Create the standard converging machine scheduler. This will be used as the
3062/// default scheduler if the target does not set a default.
Andrew Trickd14d7c22013-12-28 21:56:57 +00003063static ScheduleDAGInstrs *createGenericSchedLive(MachineSchedContext *C) {
David Blaikie422b93d2014-04-21 20:32:32 +00003064 ScheduleDAGMILive *DAG = new ScheduleDAGMILive(C, make_unique<GenericScheduler>(C));
Andrew Tricka7714a02012-11-12 19:40:10 +00003065 // Register DAG post-processors.
Andrew Trick85a1d4c2013-04-24 15:54:43 +00003066 //
3067 // FIXME: extend the mutation API to allow earlier mutations to instantiate
3068 // data and pass it to later mutations. Have a single mutation that gathers
3069 // the interesting nodes in one pass.
David Blaikie422b93d2014-04-21 20:32:32 +00003070 DAG->addMutation(make_unique<CopyConstrain>(DAG->TII, DAG->TRI));
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00003071 if (EnableMemOpCluster) {
3072 if (DAG->TII->enableClusterLoads())
3073 DAG->addMutation(make_unique<LoadClusterMutation>(DAG->TII, DAG->TRI));
3074 if (DAG->TII->enableClusterStores())
3075 DAG->addMutation(make_unique<StoreClusterMutation>(DAG->TII, DAG->TRI));
3076 }
Andrew Trick263280242012-11-12 19:52:20 +00003077 if (EnableMacroFusion)
Matthias Braun2bd6dd82015-07-20 22:34:44 +00003078 DAG->addMutation(make_unique<MacroFusion>(*DAG->TII, *DAG->TRI));
Andrew Tricka7714a02012-11-12 19:40:10 +00003079 return DAG;
Andrew Tricke1c034f2012-01-17 06:55:03 +00003080}
Andrew Trickd14d7c22013-12-28 21:56:57 +00003081
Andrew Tricke1c034f2012-01-17 06:55:03 +00003082static MachineSchedRegistry
Andrew Trick665d3ec2013-09-19 23:10:59 +00003083GenericSchedRegistry("converge", "Standard converging scheduler.",
Andrew Trickd14d7c22013-12-28 21:56:57 +00003084 createGenericSchedLive);
3085
3086//===----------------------------------------------------------------------===//
3087// PostGenericScheduler - Generic PostRA implementation of MachineSchedStrategy.
3088//===----------------------------------------------------------------------===//
3089
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003090void PostGenericScheduler::initialize(ScheduleDAGMI *Dag) {
3091 DAG = Dag;
3092 SchedModel = DAG->getSchedModel();
3093 TRI = DAG->TRI;
Andrew Trickd14d7c22013-12-28 21:56:57 +00003094
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003095 Rem.init(DAG, SchedModel);
3096 Top.init(DAG, SchedModel, &Rem);
3097 BotRoots.clear();
Andrew Trickd14d7c22013-12-28 21:56:57 +00003098
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003099 // Initialize the HazardRecognizers. If itineraries don't exist, are empty,
3100 // or are disabled, then these HazardRecs will be disabled.
3101 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003102 if (!Top.HazardRec) {
3103 Top.HazardRec =
Eric Christopher99556d72014-10-14 06:56:25 +00003104 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
Eric Christopherd9134482014-08-04 21:25:23 +00003105 Itin, DAG);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003106 }
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003107}
Andrew Trickd14d7c22013-12-28 21:56:57 +00003108
Andrew Trickd14d7c22013-12-28 21:56:57 +00003109
3110void PostGenericScheduler::registerRoots() {
3111 Rem.CriticalPath = DAG->ExitSU.getDepth();
3112
3113 // Some roots may not feed into ExitSU. Check all of them in case.
3114 for (SmallVectorImpl<SUnit*>::const_iterator
3115 I = BotRoots.begin(), E = BotRoots.end(); I != E; ++I) {
3116 if ((*I)->getDepth() > Rem.CriticalPath)
3117 Rem.CriticalPath = (*I)->getDepth();
3118 }
Gerolf Hoflehnerb5220dc2014-08-07 21:49:44 +00003119 DEBUG(dbgs() << "Critical Path: (PGS-RR) " << Rem.CriticalPath << '\n');
3120 if (DumpCriticalPathLength) {
3121 errs() << "Critical Path(PGS-RR ): " << Rem.CriticalPath << " \n";
3122 }
Andrew Trickd14d7c22013-12-28 21:56:57 +00003123}
3124
3125/// Apply a set of heursitics to a new candidate for PostRA scheduling.
3126///
3127/// \param Cand provides the policy and current best candidate.
3128/// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
3129void PostGenericScheduler::tryCandidate(SchedCandidate &Cand,
3130 SchedCandidate &TryCand) {
3131
3132 // Initialize the candidate if needed.
3133 if (!Cand.isValid()) {
3134 TryCand.Reason = NodeOrder;
3135 return;
3136 }
3137
3138 // Prioritize instructions that read unbuffered resources by stall cycles.
3139 if (tryLess(Top.getLatencyStallCycles(TryCand.SU),
3140 Top.getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
3141 return;
3142
3143 // Avoid critical resource consumption and balance the schedule.
3144 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
3145 TryCand, Cand, ResourceReduce))
3146 return;
3147 if (tryGreater(TryCand.ResDelta.DemandedResources,
3148 Cand.ResDelta.DemandedResources,
3149 TryCand, Cand, ResourceDemand))
3150 return;
3151
3152 // Avoid serializing long latency dependence chains.
3153 if (Cand.Policy.ReduceLatency && tryLatency(TryCand, Cand, Top)) {
3154 return;
3155 }
3156
3157 // Fall through to original instruction order.
3158 if (TryCand.SU->NodeNum < Cand.SU->NodeNum)
3159 TryCand.Reason = NodeOrder;
3160}
3161
3162void PostGenericScheduler::pickNodeFromQueue(SchedCandidate &Cand) {
3163 ReadyQueue &Q = Top.Available;
3164
3165 DEBUG(Q.dump());
3166
3167 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
3168 SchedCandidate TryCand(Cand.Policy);
3169 TryCand.SU = *I;
3170 TryCand.initResourceDelta(DAG, SchedModel);
3171 tryCandidate(Cand, TryCand);
3172 if (TryCand.Reason != NoCand) {
3173 Cand.setBest(TryCand);
3174 DEBUG(traceCandidate(Cand));
3175 }
3176 }
3177}
3178
3179/// Pick the next node to schedule.
3180SUnit *PostGenericScheduler::pickNode(bool &IsTopNode) {
3181 if (DAG->top() == DAG->bottom()) {
3182 assert(Top.Available.empty() && Top.Pending.empty() && "ReadyQ garbage");
Craig Topperc0196b12014-04-14 00:51:57 +00003183 return nullptr;
Andrew Trickd14d7c22013-12-28 21:56:57 +00003184 }
3185 SUnit *SU;
3186 do {
3187 SU = Top.pickOnlyChoice();
3188 if (!SU) {
3189 CandPolicy NoPolicy;
3190 SchedCandidate TopCand(NoPolicy);
3191 // Set the top-down policy based on the state of the current top zone and
3192 // the instructions outside the zone, including the bottom zone.
Craig Topperc0196b12014-04-14 00:51:57 +00003193 setPolicy(TopCand.Policy, /*IsPostRA=*/true, Top, nullptr);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003194 pickNodeFromQueue(TopCand);
3195 assert(TopCand.Reason != NoCand && "failed to find a candidate");
3196 tracePick(TopCand, true);
3197 SU = TopCand.SU;
3198 }
3199 } while (SU->isScheduled);
3200
3201 IsTopNode = true;
3202 Top.removeReady(SU);
3203
3204 DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " << *SU->getInstr());
3205 return SU;
3206}
3207
3208/// Called after ScheduleDAGMI has scheduled an instruction and updated
3209/// scheduled/remaining flags in the DAG nodes.
3210void PostGenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
3211 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
3212 Top.bumpNode(SU);
3213}
3214
3215/// Create a generic scheduler with no vreg liveness or DAG mutation passes.
3216static ScheduleDAGInstrs *createGenericSchedPostRA(MachineSchedContext *C) {
David Blaikie422b93d2014-04-21 20:32:32 +00003217 return new ScheduleDAGMI(C, make_unique<PostGenericScheduler>(C), /*IsPostRA=*/true);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003218}
Andrew Tricke1c034f2012-01-17 06:55:03 +00003219
3220//===----------------------------------------------------------------------===//
Andrew Trick90f711d2012-10-15 18:02:27 +00003221// ILP Scheduler. Currently for experimental analysis of heuristics.
3222//===----------------------------------------------------------------------===//
3223
3224namespace {
3225/// \brief Order nodes by the ILP metric.
3226struct ILPOrder {
Andrew Trick44f750a2013-01-25 04:01:04 +00003227 const SchedDFSResult *DFSResult;
3228 const BitVector *ScheduledTrees;
Andrew Trick90f711d2012-10-15 18:02:27 +00003229 bool MaximizeILP;
3230
Craig Topperc0196b12014-04-14 00:51:57 +00003231 ILPOrder(bool MaxILP)
3232 : DFSResult(nullptr), ScheduledTrees(nullptr), MaximizeILP(MaxILP) {}
Andrew Trick90f711d2012-10-15 18:02:27 +00003233
3234 /// \brief Apply a less-than relation on node priority.
Andrew Trick48d392e2012-11-28 05:13:28 +00003235 ///
3236 /// (Return true if A comes after B in the Q.)
Andrew Trick90f711d2012-10-15 18:02:27 +00003237 bool operator()(const SUnit *A, const SUnit *B) const {
Andrew Trick48d392e2012-11-28 05:13:28 +00003238 unsigned SchedTreeA = DFSResult->getSubtreeID(A);
3239 unsigned SchedTreeB = DFSResult->getSubtreeID(B);
3240 if (SchedTreeA != SchedTreeB) {
3241 // Unscheduled trees have lower priority.
3242 if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
3243 return ScheduledTrees->test(SchedTreeB);
3244
3245 // Trees with shallower connections have have lower priority.
3246 if (DFSResult->getSubtreeLevel(SchedTreeA)
3247 != DFSResult->getSubtreeLevel(SchedTreeB)) {
3248 return DFSResult->getSubtreeLevel(SchedTreeA)
3249 < DFSResult->getSubtreeLevel(SchedTreeB);
3250 }
3251 }
Andrew Trick90f711d2012-10-15 18:02:27 +00003252 if (MaximizeILP)
Andrew Trick48d392e2012-11-28 05:13:28 +00003253 return DFSResult->getILP(A) < DFSResult->getILP(B);
Andrew Trick90f711d2012-10-15 18:02:27 +00003254 else
Andrew Trick48d392e2012-11-28 05:13:28 +00003255 return DFSResult->getILP(A) > DFSResult->getILP(B);
Andrew Trick90f711d2012-10-15 18:02:27 +00003256 }
3257};
3258
3259/// \brief Schedule based on the ILP metric.
3260class ILPScheduler : public MachineSchedStrategy {
Andrew Trickd7f890e2013-12-28 21:56:47 +00003261 ScheduleDAGMILive *DAG;
Andrew Trick90f711d2012-10-15 18:02:27 +00003262 ILPOrder Cmp;
3263
3264 std::vector<SUnit*> ReadyQ;
3265public:
Craig Topperc0196b12014-04-14 00:51:57 +00003266 ILPScheduler(bool MaximizeILP): DAG(nullptr), Cmp(MaximizeILP) {}
Andrew Trick90f711d2012-10-15 18:02:27 +00003267
Craig Topper4584cd52014-03-07 09:26:03 +00003268 void initialize(ScheduleDAGMI *dag) override {
Andrew Trickd7f890e2013-12-28 21:56:47 +00003269 assert(dag->hasVRegLiveness() && "ILPScheduler needs vreg liveness");
3270 DAG = static_cast<ScheduleDAGMILive*>(dag);
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00003271 DAG->computeDFSResult();
Andrew Trick44f750a2013-01-25 04:01:04 +00003272 Cmp.DFSResult = DAG->getDFSResult();
3273 Cmp.ScheduledTrees = &DAG->getScheduledTrees();
Andrew Trick90f711d2012-10-15 18:02:27 +00003274 ReadyQ.clear();
Andrew Trick90f711d2012-10-15 18:02:27 +00003275 }
3276
Craig Topper4584cd52014-03-07 09:26:03 +00003277 void registerRoots() override {
Benjamin Krameraa598b32012-11-29 14:36:26 +00003278 // Restore the heap in ReadyQ with the updated DFS results.
3279 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
Andrew Trick90f711d2012-10-15 18:02:27 +00003280 }
3281
3282 /// Implement MachineSchedStrategy interface.
3283 /// -----------------------------------------
3284
Andrew Trick48d392e2012-11-28 05:13:28 +00003285 /// Callback to select the highest priority node from the ready Q.
Craig Topper4584cd52014-03-07 09:26:03 +00003286 SUnit *pickNode(bool &IsTopNode) override {
Craig Topperc0196b12014-04-14 00:51:57 +00003287 if (ReadyQ.empty()) return nullptr;
Matt Arsenault4ab769f2013-03-21 00:57:21 +00003288 std::pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
Andrew Trick90f711d2012-10-15 18:02:27 +00003289 SUnit *SU = ReadyQ.back();
3290 ReadyQ.pop_back();
3291 IsTopNode = false;
Andrew Trick1f0bb692013-04-13 06:07:49 +00003292 DEBUG(dbgs() << "Pick node " << "SU(" << SU->NodeNum << ") "
Andrew Trick44f750a2013-01-25 04:01:04 +00003293 << " ILP: " << DAG->getDFSResult()->getILP(SU)
3294 << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU) << " @"
3295 << DAG->getDFSResult()->getSubtreeLevel(
Andrew Trick1f0bb692013-04-13 06:07:49 +00003296 DAG->getDFSResult()->getSubtreeID(SU)) << '\n'
3297 << "Scheduling " << *SU->getInstr());
Andrew Trick90f711d2012-10-15 18:02:27 +00003298 return SU;
3299 }
3300
Andrew Trick44f750a2013-01-25 04:01:04 +00003301 /// \brief Scheduler callback to notify that a new subtree is scheduled.
Craig Topper4584cd52014-03-07 09:26:03 +00003302 void scheduleTree(unsigned SubtreeID) override {
Andrew Trick44f750a2013-01-25 04:01:04 +00003303 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3304 }
3305
Andrew Trick48d392e2012-11-28 05:13:28 +00003306 /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
3307 /// DFSResults, and resort the priority Q.
Craig Topper4584cd52014-03-07 09:26:03 +00003308 void schedNode(SUnit *SU, bool IsTopNode) override {
Andrew Trick48d392e2012-11-28 05:13:28 +00003309 assert(!IsTopNode && "SchedDFSResult needs bottom-up");
Andrew Trick48d392e2012-11-28 05:13:28 +00003310 }
Andrew Trick90f711d2012-10-15 18:02:27 +00003311
Craig Topper4584cd52014-03-07 09:26:03 +00003312 void releaseTopNode(SUnit *) override { /*only called for top roots*/ }
Andrew Trick90f711d2012-10-15 18:02:27 +00003313
Craig Topper4584cd52014-03-07 09:26:03 +00003314 void releaseBottomNode(SUnit *SU) override {
Andrew Trick90f711d2012-10-15 18:02:27 +00003315 ReadyQ.push_back(SU);
3316 std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3317 }
3318};
3319} // namespace
3320
3321static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
David Blaikie422b93d2014-04-21 20:32:32 +00003322 return new ScheduleDAGMILive(C, make_unique<ILPScheduler>(true));
Andrew Trick90f711d2012-10-15 18:02:27 +00003323}
3324static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
David Blaikie422b93d2014-04-21 20:32:32 +00003325 return new ScheduleDAGMILive(C, make_unique<ILPScheduler>(false));
Andrew Trick90f711d2012-10-15 18:02:27 +00003326}
3327static MachineSchedRegistry ILPMaxRegistry(
3328 "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
3329static MachineSchedRegistry ILPMinRegistry(
3330 "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
3331
3332//===----------------------------------------------------------------------===//
Andrew Trick63440872012-01-14 02:17:06 +00003333// Machine Instruction Shuffler for Correctness Testing
3334//===----------------------------------------------------------------------===//
3335
Andrew Tricke77e84e2012-01-13 06:30:30 +00003336#ifndef NDEBUG
3337namespace {
Andrew Trick8823dec2012-03-14 04:00:41 +00003338/// Apply a less-than relation on the node order, which corresponds to the
3339/// instruction order prior to scheduling. IsReverse implements greater-than.
3340template<bool IsReverse>
3341struct SUnitOrder {
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003342 bool operator()(SUnit *A, SUnit *B) const {
Andrew Trick8823dec2012-03-14 04:00:41 +00003343 if (IsReverse)
3344 return A->NodeNum > B->NodeNum;
3345 else
3346 return A->NodeNum < B->NodeNum;
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003347 }
3348};
3349
Andrew Tricke77e84e2012-01-13 06:30:30 +00003350/// Reorder instructions as much as possible.
Andrew Trick8823dec2012-03-14 04:00:41 +00003351class InstructionShuffler : public MachineSchedStrategy {
3352 bool IsAlternating;
3353 bool IsTopDown;
3354
3355 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
3356 // gives nodes with a higher number higher priority causing the latest
3357 // instructions to be scheduled first.
3358 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
3359 TopQ;
3360 // When scheduling bottom-up, use greater-than as the queue priority.
3361 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
3362 BottomQ;
Andrew Tricke77e84e2012-01-13 06:30:30 +00003363public:
Andrew Trick8823dec2012-03-14 04:00:41 +00003364 InstructionShuffler(bool alternate, bool topdown)
3365 : IsAlternating(alternate), IsTopDown(topdown) {}
Andrew Tricke77e84e2012-01-13 06:30:30 +00003366
Craig Topper9d74a5a2014-04-29 07:58:41 +00003367 void initialize(ScheduleDAGMI*) override {
Andrew Trick8823dec2012-03-14 04:00:41 +00003368 TopQ.clear();
3369 BottomQ.clear();
3370 }
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003371
Andrew Trick8823dec2012-03-14 04:00:41 +00003372 /// Implement MachineSchedStrategy interface.
3373 /// -----------------------------------------
3374
Craig Topper9d74a5a2014-04-29 07:58:41 +00003375 SUnit *pickNode(bool &IsTopNode) override {
Andrew Trick8823dec2012-03-14 04:00:41 +00003376 SUnit *SU;
3377 if (IsTopDown) {
3378 do {
Craig Topperc0196b12014-04-14 00:51:57 +00003379 if (TopQ.empty()) return nullptr;
Andrew Trick8823dec2012-03-14 04:00:41 +00003380 SU = TopQ.top();
3381 TopQ.pop();
3382 } while (SU->isScheduled);
3383 IsTopNode = true;
Matthias Braunb550b762016-04-21 01:54:13 +00003384 } else {
Andrew Trick8823dec2012-03-14 04:00:41 +00003385 do {
Craig Topperc0196b12014-04-14 00:51:57 +00003386 if (BottomQ.empty()) return nullptr;
Andrew Trick8823dec2012-03-14 04:00:41 +00003387 SU = BottomQ.top();
3388 BottomQ.pop();
3389 } while (SU->isScheduled);
3390 IsTopNode = false;
3391 }
3392 if (IsAlternating)
3393 IsTopDown = !IsTopDown;
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003394 return SU;
3395 }
3396
Craig Topper9d74a5a2014-04-29 07:58:41 +00003397 void schedNode(SUnit *SU, bool IsTopNode) override {}
Andrew Trick61f1a272012-05-24 22:11:09 +00003398
Craig Topper9d74a5a2014-04-29 07:58:41 +00003399 void releaseTopNode(SUnit *SU) override {
Andrew Trick8823dec2012-03-14 04:00:41 +00003400 TopQ.push(SU);
3401 }
Craig Topper9d74a5a2014-04-29 07:58:41 +00003402 void releaseBottomNode(SUnit *SU) override {
Andrew Trick8823dec2012-03-14 04:00:41 +00003403 BottomQ.push(SU);
Andrew Tricke77e84e2012-01-13 06:30:30 +00003404 }
3405};
3406} // namespace
3407
Andrew Trick02a80da2012-03-08 01:41:12 +00003408static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
Andrew Trick8823dec2012-03-14 04:00:41 +00003409 bool Alternate = !ForceTopDown && !ForceBottomUp;
3410 bool TopDown = !ForceBottomUp;
Benjamin Kramer05e7a842012-03-14 11:26:37 +00003411 assert((TopDown || !ForceTopDown) &&
Andrew Trick8823dec2012-03-14 04:00:41 +00003412 "-misched-topdown incompatible with -misched-bottomup");
David Blaikie422b93d2014-04-21 20:32:32 +00003413 return new ScheduleDAGMILive(C, make_unique<InstructionShuffler>(Alternate, TopDown));
Andrew Tricke77e84e2012-01-13 06:30:30 +00003414}
Andrew Trick8823dec2012-03-14 04:00:41 +00003415static MachineSchedRegistry ShufflerRegistry(
3416 "shuffle", "Shuffle machine instructions alternating directions",
3417 createInstructionShuffler);
Andrew Tricke77e84e2012-01-13 06:30:30 +00003418#endif // !NDEBUG
Andrew Trickea9fd952013-01-25 07:45:29 +00003419
3420//===----------------------------------------------------------------------===//
Andrew Trickd7f890e2013-12-28 21:56:47 +00003421// GraphWriter support for ScheduleDAGMILive.
Andrew Trickea9fd952013-01-25 07:45:29 +00003422//===----------------------------------------------------------------------===//
3423
3424#ifndef NDEBUG
3425namespace llvm {
3426
3427template<> struct GraphTraits<
3428 ScheduleDAGMI*> : public GraphTraits<ScheduleDAG*> {};
3429
3430template<>
3431struct DOTGraphTraits<ScheduleDAGMI*> : public DefaultDOTGraphTraits {
3432
3433 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
3434
3435 static std::string getGraphName(const ScheduleDAG *G) {
3436 return G->MF.getName();
3437 }
3438
3439 static bool renderGraphFromBottomUp() {
3440 return true;
3441 }
3442
3443 static bool isNodeHidden(const SUnit *Node) {
Matthias Braund78ee542015-09-17 21:09:59 +00003444 if (ViewMISchedCutoff == 0)
3445 return false;
3446 return (Node->Preds.size() > ViewMISchedCutoff
3447 || Node->Succs.size() > ViewMISchedCutoff);
Andrew Trickea9fd952013-01-25 07:45:29 +00003448 }
3449
Andrew Trickea9fd952013-01-25 07:45:29 +00003450 /// If you want to override the dot attributes printed for a particular
3451 /// edge, override this method.
3452 static std::string getEdgeAttributes(const SUnit *Node,
3453 SUnitIterator EI,
3454 const ScheduleDAG *Graph) {
3455 if (EI.isArtificialDep())
3456 return "color=cyan,style=dashed";
3457 if (EI.isCtrlDep())
3458 return "color=blue,style=dashed";
3459 return "";
3460 }
3461
3462 static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) {
Alp Tokere69170a2014-06-26 22:52:05 +00003463 std::string Str;
3464 raw_string_ostream SS(Str);
Andrew Trickd7f890e2013-12-28 21:56:47 +00003465 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3466 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
Craig Topperc0196b12014-04-14 00:51:57 +00003467 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
Andrew Trick7609b7d2013-09-06 17:32:42 +00003468 SS << "SU:" << SU->NodeNum;
3469 if (DFS)
3470 SS << " I:" << DFS->getNumInstrs(SU);
Andrew Trickea9fd952013-01-25 07:45:29 +00003471 return SS.str();
3472 }
3473 static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G) {
3474 return G->getGraphNodeLabel(SU);
3475 }
3476
Andrew Trickd7f890e2013-12-28 21:56:47 +00003477 static std::string getNodeAttributes(const SUnit *N, const ScheduleDAG *G) {
Andrew Trickea9fd952013-01-25 07:45:29 +00003478 std::string Str("shape=Mrecord");
Andrew Trickd7f890e2013-12-28 21:56:47 +00003479 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3480 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
Craig Topperc0196b12014-04-14 00:51:57 +00003481 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
Andrew Trickea9fd952013-01-25 07:45:29 +00003482 if (DFS) {
3483 Str += ",style=filled,fillcolor=\"#";
3484 Str += DOT::getColorString(DFS->getSubtreeID(N));
3485 Str += '"';
3486 }
3487 return Str;
3488 }
3489};
3490} // namespace llvm
3491#endif // NDEBUG
3492
3493/// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
3494/// rendered using 'dot'.
3495///
3496void ScheduleDAGMI::viewGraph(const Twine &Name, const Twine &Title) {
3497#ifndef NDEBUG
3498 ViewGraph(this, Name, false, Title);
3499#else
3500 errs() << "ScheduleDAGMI::viewGraph is only available in debug builds on "
3501 << "systems with Graphviz or gv!\n";
3502#endif // NDEBUG
3503}
3504
3505/// Out-of-line implementation with no arguments is handy for gdb.
3506void ScheduleDAGMI::viewGraph() {
3507 viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName());
3508}