blob: eaba9a58557c37c526a82ad00efb23280f79a26d [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
Chandler Carruth6bda14b2017-06-06 11:49:48 +000015#include "llvm/CodeGen/MachineScheduler.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000016#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/BitVector.h"
18#include "llvm/ADT/DenseMap.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/ADT/PriorityQueue.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000020#include "llvm/ADT/STLExtras.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000021#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/iterator_range.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/Analysis/AliasAnalysis.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000024#include "llvm/CodeGen/LiveInterval.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000025#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000026#include "llvm/CodeGen/MachineBasicBlock.h"
Jakub Staszakdf17ddd2013-03-10 13:11:23 +000027#include "llvm/CodeGen/MachineDominators.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000028#include "llvm/CodeGen/MachineFunction.h"
29#include "llvm/CodeGen/MachineFunctionPass.h"
30#include "llvm/CodeGen/MachineInstr.h"
Jakub Staszakdf17ddd2013-03-10 13:11:23 +000031#include "llvm/CodeGen/MachineLoopInfo.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000032#include "llvm/CodeGen/MachineOperand.h"
33#include "llvm/CodeGen/MachinePassRegistry.h"
Andrew Trick736dd9a2013-06-21 18:32:58 +000034#include "llvm/CodeGen/MachineRegisterInfo.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000035#include "llvm/CodeGen/MachineValueType.h"
Andrew Tricke77e84e2012-01-13 06:30:30 +000036#include "llvm/CodeGen/Passes.h"
Andrew Trick05ff4662012-06-06 20:29:31 +000037#include "llvm/CodeGen/RegisterClassInfo.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000038#include "llvm/CodeGen/RegisterPressure.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000039#include "llvm/CodeGen/ScheduleDAG.h"
40#include "llvm/CodeGen/ScheduleDAGInstrs.h"
41#include "llvm/CodeGen/ScheduleDAGMutation.h"
Andrew Trickcd1c2f92012-11-28 05:13:24 +000042#include "llvm/CodeGen/ScheduleDFS.h"
Andrew Trick61f1a272012-05-24 22:11:09 +000043#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000044#include "llvm/CodeGen/SlotIndexes.h"
Matthias Braun31d19d42016-05-10 03:21:59 +000045#include "llvm/CodeGen/TargetPassConfig.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000046#include "llvm/CodeGen/TargetSchedule.h"
47#include "llvm/MC/LaneBitmask.h"
48#include "llvm/Pass.h"
Andrew Tricke77e84e2012-01-13 06:30:30 +000049#include "llvm/Support/CommandLine.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000050#include "llvm/Support/Compiler.h"
Andrew Tricke77e84e2012-01-13 06:30:30 +000051#include "llvm/Support/Debug.h"
52#include "llvm/Support/ErrorHandling.h"
Andrew Trickea9fd952013-01-25 07:45:29 +000053#include "llvm/Support/GraphWriter.h"
Andrew Tricke77e84e2012-01-13 06:30:30 +000054#include "llvm/Support/raw_ostream.h"
Jakub Staszak80df8b82013-06-14 00:00:13 +000055#include "llvm/Target/TargetInstrInfo.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000056#include "llvm/Target/TargetLowering.h"
57#include "llvm/Target/TargetRegisterInfo.h"
58#include "llvm/Target/TargetSubtargetInfo.h"
59#include <algorithm>
60#include <cassert>
61#include <cstdint>
62#include <iterator>
63#include <limits>
64#include <memory>
65#include <string>
66#include <tuple>
67#include <utility>
68#include <vector>
Andrew Trick7ccdc5c2012-01-17 06:55:07 +000069
Andrew Tricke77e84e2012-01-13 06:30:30 +000070using namespace llvm;
71
Matthias Braun1527baa2017-05-25 21:26:32 +000072#define DEBUG_TYPE "machine-scheduler"
Chandler Carruth1b9dde02014-04-22 02:02:50 +000073
Andrew Trick7a8e1002012-09-11 00:39:15 +000074namespace llvm {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000075
Andrew Trick7a8e1002012-09-11 00:39:15 +000076cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
77 cl::desc("Force top-down list scheduling"));
78cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
79 cl::desc("Force bottom-up list scheduling"));
Gerolf Hoflehnerb5220dc2014-08-07 21:49:44 +000080cl::opt<bool>
81DumpCriticalPathLength("misched-dcpl", cl::Hidden,
82 cl::desc("Print critical path length to stdout"));
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000083
84} // end namespace llvm
Andrew Trick8823dec2012-03-14 04:00:41 +000085
Andrew Tricka5f19562012-03-07 00:18:25 +000086#ifndef NDEBUG
87static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
88 cl::desc("Pop up a window to show MISched dags after they are processed"));
Lang Hamesdd98c492012-03-19 18:38:38 +000089
Matthias Braund78ee542015-09-17 21:09:59 +000090/// In some situations a few uninteresting nodes depend on nearly all other
91/// nodes in the graph, provide a cutoff to hide them.
92static cl::opt<unsigned> ViewMISchedCutoff("view-misched-cutoff", cl::Hidden,
93 cl::desc("Hide nodes with more predecessor/successor than cutoff"));
94
Lang Hamesdd98c492012-03-19 18:38:38 +000095static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
96 cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
Andrew Trick33e05d72013-12-28 21:57:02 +000097
98static cl::opt<std::string> SchedOnlyFunc("misched-only-func", cl::Hidden,
99 cl::desc("Only schedule this function"));
100static cl::opt<unsigned> SchedOnlyBlock("misched-only-block", cl::Hidden,
101 cl::desc("Only schedule this MBB#"));
Andrew Tricka5f19562012-03-07 00:18:25 +0000102#else
103static bool ViewMISchedDAGs = false;
104#endif // NDEBUG
105
Matthias Braun6493bc22016-04-22 19:09:17 +0000106/// Avoid quadratic complexity in unusually large basic blocks by limiting the
107/// size of the ready lists.
108static cl::opt<unsigned> ReadyListLimit("misched-limit", cl::Hidden,
109 cl::desc("Limit ready list to N instructions"), cl::init(256));
110
Andrew Trickb6e74712013-09-04 20:59:59 +0000111static cl::opt<bool> EnableRegPressure("misched-regpressure", cl::Hidden,
112 cl::desc("Enable register pressure scheduling."), cl::init(true));
113
Andrew Trickc01b0042013-08-23 17:48:43 +0000114static cl::opt<bool> EnableCyclicPath("misched-cyclicpath", cl::Hidden,
Andrew Trick6c88b352013-09-09 23:31:14 +0000115 cl::desc("Enable cyclic critical path analysis."), cl::init(true));
Andrew Trickc01b0042013-08-23 17:48:43 +0000116
Jun Bum Lim4c5bd582016-04-15 14:58:38 +0000117static cl::opt<bool> EnableMemOpCluster("misched-cluster", cl::Hidden,
118 cl::desc("Enable memop clustering."),
119 cl::init(true));
Andrew Tricka7714a02012-11-12 19:40:10 +0000120
Andrew Trick48f2a722013-03-08 05:40:34 +0000121static cl::opt<bool> VerifyScheduling("verify-misched", cl::Hidden,
122 cl::desc("Verify machine instrs before and after machine scheduling"));
123
Andrew Trick44f750a2013-01-25 04:01:04 +0000124// DAG subtrees must have at least this many nodes.
125static const unsigned MinSubtreeSize = 8;
126
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +0000127// Pin the vtables to this file.
128void MachineSchedStrategy::anchor() {}
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +0000129
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +0000130void ScheduleDAGMutation::anchor() {}
131
Andrew Trick63440872012-01-14 02:17:06 +0000132//===----------------------------------------------------------------------===//
133// Machine Instruction Scheduling Pass and Registry
134//===----------------------------------------------------------------------===//
135
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +0000136MachineSchedContext::MachineSchedContext() {
Andrew Trick4d4b5462012-04-24 20:36:19 +0000137 RegClassInfo = new RegisterClassInfo();
138}
139
140MachineSchedContext::~MachineSchedContext() {
141 delete RegClassInfo;
142}
143
Andrew Tricke77e84e2012-01-13 06:30:30 +0000144namespace {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +0000145
Andrew Trickd7f890e2013-12-28 21:56:47 +0000146/// Base class for a machine scheduler class that can run at any point.
147class MachineSchedulerBase : public MachineSchedContext,
148 public MachineFunctionPass {
149public:
150 MachineSchedulerBase(char &ID): MachineFunctionPass(ID) {}
151
Craig Topperc0196b12014-04-14 00:51:57 +0000152 void print(raw_ostream &O, const Module* = nullptr) const override;
Andrew Trickd7f890e2013-12-28 21:56:47 +0000153
154protected:
Matthias Braun93563e72015-11-03 01:53:29 +0000155 void scheduleRegions(ScheduleDAGInstrs &Scheduler, bool FixKillFlags);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000156};
157
Andrew Tricke1c034f2012-01-17 06:55:03 +0000158/// MachineScheduler runs after coalescing and before register allocation.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000159class MachineScheduler : public MachineSchedulerBase {
Andrew Tricke77e84e2012-01-13 06:30:30 +0000160public:
Andrew Tricke1c034f2012-01-17 06:55:03 +0000161 MachineScheduler();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000162
Craig Topper4584cd52014-03-07 09:26:03 +0000163 void getAnalysisUsage(AnalysisUsage &AU) const override;
Andrew Tricke77e84e2012-01-13 06:30:30 +0000164
Craig Topper4584cd52014-03-07 09:26:03 +0000165 bool runOnMachineFunction(MachineFunction&) override;
Andrew Tricke77e84e2012-01-13 06:30:30 +0000166
Andrew Tricke77e84e2012-01-13 06:30:30 +0000167 static char ID; // Class identification, replacement for typeinfo
Andrew Trick978674b2013-09-20 05:14:41 +0000168
169protected:
170 ScheduleDAGInstrs *createMachineScheduler();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000171};
Andrew Trick17080b92013-12-28 21:56:51 +0000172
173/// PostMachineScheduler runs after shortly before code emission.
174class PostMachineScheduler : public MachineSchedulerBase {
175public:
176 PostMachineScheduler();
177
Craig Topper4584cd52014-03-07 09:26:03 +0000178 void getAnalysisUsage(AnalysisUsage &AU) const override;
Andrew Trick17080b92013-12-28 21:56:51 +0000179
Craig Topper4584cd52014-03-07 09:26:03 +0000180 bool runOnMachineFunction(MachineFunction&) override;
Andrew Trick17080b92013-12-28 21:56:51 +0000181
182 static char ID; // Class identification, replacement for typeinfo
183
184protected:
185 ScheduleDAGInstrs *createPostMachineScheduler();
186};
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +0000187
188} // end anonymous namespace
Andrew Tricke77e84e2012-01-13 06:30:30 +0000189
Andrew Tricke1c034f2012-01-17 06:55:03 +0000190char MachineScheduler::ID = 0;
Andrew Tricke77e84e2012-01-13 06:30:30 +0000191
Andrew Tricke1c034f2012-01-17 06:55:03 +0000192char &llvm::MachineSchedulerID = MachineScheduler::ID;
Andrew Tricke77e84e2012-01-13 06:30:30 +0000193
Matthias Braun1527baa2017-05-25 21:26:32 +0000194INITIALIZE_PASS_BEGIN(MachineScheduler, DEBUG_TYPE,
Andrew Tricke77e84e2012-01-13 06:30:30 +0000195 "Machine Instruction Scheduler", false, false)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000196INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Davide Italiano6a1209e2017-03-24 20:52:56 +0000197INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
Andrew Tricke77e84e2012-01-13 06:30:30 +0000198INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
199INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
Matthias Braun1527baa2017-05-25 21:26:32 +0000200INITIALIZE_PASS_END(MachineScheduler, DEBUG_TYPE,
Andrew Tricke77e84e2012-01-13 06:30:30 +0000201 "Machine Instruction Scheduler", false, false)
202
Andrew Tricke1c034f2012-01-17 06:55:03 +0000203MachineScheduler::MachineScheduler()
Andrew Trickd7f890e2013-12-28 21:56:47 +0000204: MachineSchedulerBase(ID) {
Andrew Tricke1c034f2012-01-17 06:55:03 +0000205 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Andrew Tricke77e84e2012-01-13 06:30:30 +0000206}
207
Andrew Tricke1c034f2012-01-17 06:55:03 +0000208void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
Andrew Tricke77e84e2012-01-13 06:30:30 +0000209 AU.setPreservesCFG();
210 AU.addRequiredID(MachineDominatorsID);
211 AU.addRequired<MachineLoopInfo>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000212 AU.addRequired<AAResultsWrapperPass>();
Andrew Trick45300682012-03-09 00:52:20 +0000213 AU.addRequired<TargetPassConfig>();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000214 AU.addRequired<SlotIndexes>();
215 AU.addPreserved<SlotIndexes>();
216 AU.addRequired<LiveIntervals>();
217 AU.addPreserved<LiveIntervals>();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000218 MachineFunctionPass::getAnalysisUsage(AU);
219}
220
Andrew Trick17080b92013-12-28 21:56:51 +0000221char PostMachineScheduler::ID = 0;
222
223char &llvm::PostMachineSchedulerID = PostMachineScheduler::ID;
224
225INITIALIZE_PASS(PostMachineScheduler, "postmisched",
Saleem Abdulrasool7230b372013-12-28 22:47:55 +0000226 "PostRA Machine Instruction Scheduler", false, false)
Andrew Trick17080b92013-12-28 21:56:51 +0000227
228PostMachineScheduler::PostMachineScheduler()
229: MachineSchedulerBase(ID) {
230 initializePostMachineSchedulerPass(*PassRegistry::getPassRegistry());
231}
232
233void PostMachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
234 AU.setPreservesCFG();
235 AU.addRequiredID(MachineDominatorsID);
236 AU.addRequired<MachineLoopInfo>();
237 AU.addRequired<TargetPassConfig>();
238 MachineFunctionPass::getAnalysisUsage(AU);
239}
240
Andrew Tricke77e84e2012-01-13 06:30:30 +0000241MachinePassRegistry MachineSchedRegistry::Registry;
242
Andrew Trick45300682012-03-09 00:52:20 +0000243/// A dummy default scheduler factory indicates whether the scheduler
244/// is overridden on the command line.
245static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
Craig Topperc0196b12014-04-14 00:51:57 +0000246 return nullptr;
Andrew Trick45300682012-03-09 00:52:20 +0000247}
Andrew Tricke77e84e2012-01-13 06:30:30 +0000248
249/// MachineSchedOpt allows command line selection of the scheduler.
250static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +0000251 RegisterPassParser<MachineSchedRegistry>>
Andrew Tricke77e84e2012-01-13 06:30:30 +0000252MachineSchedOpt("misched",
Andrew Trick45300682012-03-09 00:52:20 +0000253 cl::init(&useDefaultMachineSched), cl::Hidden,
Andrew Tricke77e84e2012-01-13 06:30:30 +0000254 cl::desc("Machine instruction scheduler to use"));
255
Andrew Trick45300682012-03-09 00:52:20 +0000256static MachineSchedRegistry
Andrew Trick8823dec2012-03-14 04:00:41 +0000257DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
Andrew Trick45300682012-03-09 00:52:20 +0000258 useDefaultMachineSched);
259
Eric Christopher5f141b02015-03-11 22:56:10 +0000260static cl::opt<bool> EnableMachineSched(
261 "enable-misched",
262 cl::desc("Enable the machine instruction scheduling pass."), cl::init(true),
263 cl::Hidden);
264
Chad Rosier816a1ab2016-01-20 23:08:32 +0000265static cl::opt<bool> EnablePostRAMachineSched(
266 "enable-post-misched",
267 cl::desc("Enable the post-ra machine instruction scheduling pass."),
268 cl::init(true), cl::Hidden);
269
Andrew Trickcc45a282012-04-24 18:04:34 +0000270/// Decrement this iterator until reaching the top or a non-debug instr.
Andrew Trick2bc74c22013-08-30 04:36:57 +0000271static MachineBasicBlock::const_iterator
272priorNonDebug(MachineBasicBlock::const_iterator I,
273 MachineBasicBlock::const_iterator Beg) {
Andrew Trickcc45a282012-04-24 18:04:34 +0000274 assert(I != Beg && "reached the top of the region, cannot decrement");
275 while (--I != Beg) {
276 if (!I->isDebugValue())
277 break;
278 }
279 return I;
280}
281
Andrew Trick2bc74c22013-08-30 04:36:57 +0000282/// Non-const version.
283static MachineBasicBlock::iterator
284priorNonDebug(MachineBasicBlock::iterator I,
285 MachineBasicBlock::const_iterator Beg) {
Duncan P. N. Exon Smithdcbce9c2016-08-16 23:34:07 +0000286 return priorNonDebug(MachineBasicBlock::const_iterator(I), Beg)
287 .getNonConstIterator();
Andrew Trick2bc74c22013-08-30 04:36:57 +0000288}
289
Andrew Trickcc45a282012-04-24 18:04:34 +0000290/// If this iterator is a debug value, increment until reaching the End or a
291/// non-debug instruction.
Andrew Trick2c4f8b72013-08-31 05:17:58 +0000292static MachineBasicBlock::const_iterator
293nextIfDebug(MachineBasicBlock::const_iterator I,
294 MachineBasicBlock::const_iterator End) {
Andrew Trick463b2f12012-05-17 18:35:03 +0000295 for(; I != End; ++I) {
Andrew Trickcc45a282012-04-24 18:04:34 +0000296 if (!I->isDebugValue())
297 break;
298 }
299 return I;
300}
301
Andrew Trick2c4f8b72013-08-31 05:17:58 +0000302/// Non-const version.
303static MachineBasicBlock::iterator
304nextIfDebug(MachineBasicBlock::iterator I,
305 MachineBasicBlock::const_iterator End) {
Duncan P. N. Exon Smithdcbce9c2016-08-16 23:34:07 +0000306 return nextIfDebug(MachineBasicBlock::const_iterator(I), End)
307 .getNonConstIterator();
Andrew Trick2c4f8b72013-08-31 05:17:58 +0000308}
309
Andrew Trickdc4c1ad2013-09-24 17:11:19 +0000310/// Instantiate a ScheduleDAGInstrs that will be owned by the caller.
Andrew Trick978674b2013-09-20 05:14:41 +0000311ScheduleDAGInstrs *MachineScheduler::createMachineScheduler() {
312 // Select the scheduler, or set the default.
313 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
314 if (Ctor != useDefaultMachineSched)
315 return Ctor(this);
316
317 // Get the default scheduler set by the target for this function.
318 ScheduleDAGInstrs *Scheduler = PassConfig->createMachineScheduler(this);
319 if (Scheduler)
320 return Scheduler;
321
322 // Default to GenericScheduler.
Andrew Trickd14d7c22013-12-28 21:56:57 +0000323 return createGenericSchedLive(this);
Andrew Trick978674b2013-09-20 05:14:41 +0000324}
325
Andrew Trick17080b92013-12-28 21:56:51 +0000326/// Instantiate a ScheduleDAGInstrs for PostRA scheduling that will be owned by
327/// the caller. We don't have a command line option to override the postRA
328/// scheduler. The Target must configure it.
329ScheduleDAGInstrs *PostMachineScheduler::createPostMachineScheduler() {
330 // Get the postRA scheduler set by the target for this function.
331 ScheduleDAGInstrs *Scheduler = PassConfig->createPostMachineScheduler(this);
332 if (Scheduler)
333 return Scheduler;
334
335 // Default to GenericScheduler.
Andrew Trickd14d7c22013-12-28 21:56:57 +0000336 return createGenericSchedPostRA(this);
Andrew Trick17080b92013-12-28 21:56:51 +0000337}
338
Andrew Trick72515be2012-03-14 04:00:38 +0000339/// Top-level MachineScheduler pass driver.
340///
341/// Visit blocks in function order. Divide each block into scheduling regions
Andrew Trick8823dec2012-03-14 04:00:41 +0000342/// and visit them bottom-up. Visiting regions bottom-up is not required, but is
343/// consistent with the DAG builder, which traverses the interior of the
344/// scheduling regions bottom-up.
Andrew Trick72515be2012-03-14 04:00:38 +0000345///
346/// This design avoids exposing scheduling boundaries to the DAG builder,
Andrew Trick8823dec2012-03-14 04:00:41 +0000347/// simplifying the DAG builder's support for "special" target instructions.
348/// At the same time the design allows target schedulers to operate across
Andrew Trick72515be2012-03-14 04:00:38 +0000349/// scheduling boundaries, for example to bundle the boudary instructions
350/// without reordering them. This creates complexity, because the target
351/// scheduler must update the RegionBegin and RegionEnd positions cached by
352/// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
353/// design would be to split blocks at scheduling boundaries, but LLVM has a
354/// general bias against block splitting purely for implementation simplicity.
Andrew Tricke1c034f2012-01-17 06:55:03 +0000355bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000356 if (skipFunction(*mf.getFunction()))
Chad Rosier6338d7c2016-01-20 22:38:25 +0000357 return false;
358
Eric Christopher5f141b02015-03-11 22:56:10 +0000359 if (EnableMachineSched.getNumOccurrences()) {
360 if (!EnableMachineSched)
361 return false;
362 } else if (!mf.getSubtarget().enableMachineScheduler())
363 return false;
364
Matthias Braundc7580a2015-10-29 03:57:28 +0000365 DEBUG(dbgs() << "Before MISched:\n"; mf.print(dbgs()));
Andrew Trickc5d70082012-05-10 21:06:21 +0000366
Andrew Tricke77e84e2012-01-13 06:30:30 +0000367 // Initialize the context of the pass.
368 MF = &mf;
369 MLI = &getAnalysis<MachineLoopInfo>();
370 MDT = &getAnalysis<MachineDominatorTree>();
Andrew Trick45300682012-03-09 00:52:20 +0000371 PassConfig = &getAnalysis<TargetPassConfig>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000372 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Andrew Trick02a80da2012-03-08 01:41:12 +0000373
Lang Hamesad33d5a2012-01-27 22:36:19 +0000374 LIS = &getAnalysis<LiveIntervals>();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000375
Andrew Trick48f2a722013-03-08 05:40:34 +0000376 if (VerifyScheduling) {
Andrew Trick97064962013-07-25 07:26:26 +0000377 DEBUG(LIS->dump());
Andrew Trick48f2a722013-03-08 05:40:34 +0000378 MF->verify(this, "Before machine scheduling.");
379 }
Andrew Trick4d4b5462012-04-24 20:36:19 +0000380 RegClassInfo->runOnMachineFunction(*MF);
Andrew Trick88639922012-04-24 17:56:43 +0000381
Andrew Trick978674b2013-09-20 05:14:41 +0000382 // Instantiate the selected scheduler for this target, function, and
383 // optimization level.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000384 std::unique_ptr<ScheduleDAGInstrs> Scheduler(createMachineScheduler());
Matthias Braun93563e72015-11-03 01:53:29 +0000385 scheduleRegions(*Scheduler, false);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000386
387 DEBUG(LIS->dump());
388 if (VerifyScheduling)
389 MF->verify(this, "After machine scheduling.");
390 return true;
391}
392
Andrew Trick17080b92013-12-28 21:56:51 +0000393bool PostMachineScheduler::runOnMachineFunction(MachineFunction &mf) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000394 if (skipFunction(*mf.getFunction()))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000395 return false;
396
Chad Rosier816a1ab2016-01-20 23:08:32 +0000397 if (EnablePostRAMachineSched.getNumOccurrences()) {
398 if (!EnablePostRAMachineSched)
399 return false;
400 } else if (!mf.getSubtarget().enablePostRAScheduler()) {
Andrew Trick8d2ee372014-06-04 07:06:27 +0000401 DEBUG(dbgs() << "Subtarget disables post-MI-sched.\n");
402 return false;
403 }
Andrew Trick17080b92013-12-28 21:56:51 +0000404 DEBUG(dbgs() << "Before post-MI-sched:\n"; mf.print(dbgs()));
405
406 // Initialize the context of the pass.
407 MF = &mf;
408 PassConfig = &getAnalysis<TargetPassConfig>();
409
410 if (VerifyScheduling)
411 MF->verify(this, "Before post machine scheduling.");
412
413 // Instantiate the selected scheduler for this target, function, and
414 // optimization level.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000415 std::unique_ptr<ScheduleDAGInstrs> Scheduler(createPostMachineScheduler());
Matthias Braun93563e72015-11-03 01:53:29 +0000416 scheduleRegions(*Scheduler, true);
Andrew Trick17080b92013-12-28 21:56:51 +0000417
418 if (VerifyScheduling)
419 MF->verify(this, "After post machine scheduling.");
420 return true;
421}
422
Andrew Trickd14d7c22013-12-28 21:56:57 +0000423/// Return true of the given instruction should not be included in a scheduling
424/// region.
425///
426/// MachineScheduler does not currently support scheduling across calls. To
427/// handle calls, the DAG builder needs to be modified to create register
428/// anti/output dependencies on the registers clobbered by the call's regmask
429/// operand. In PreRA scheduling, the stack pointer adjustment already prevents
430/// scheduling across calls. In PostRA scheduling, we need the isCall to enforce
431/// the boundary, but there would be no benefit to postRA scheduling across
432/// calls this late anyway.
433static bool isSchedBoundary(MachineBasicBlock::iterator MI,
434 MachineBasicBlock *MBB,
435 MachineFunction *MF,
Matthias Braun93563e72015-11-03 01:53:29 +0000436 const TargetInstrInfo *TII) {
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000437 return MI->isCall() || TII->isSchedulingBoundary(*MI, MBB, *MF);
Andrew Trickd14d7c22013-12-28 21:56:57 +0000438}
439
Andrew Trickd7f890e2013-12-28 21:56:47 +0000440/// Main driver for both MachineScheduler and PostMachineScheduler.
Matthias Braun93563e72015-11-03 01:53:29 +0000441void MachineSchedulerBase::scheduleRegions(ScheduleDAGInstrs &Scheduler,
442 bool FixKillFlags) {
Eric Christopherfc6de422014-08-05 02:39:49 +0000443 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000444
445 // Visit all machine basic blocks.
Andrew Trick88639922012-04-24 17:56:43 +0000446 //
447 // TODO: Visit blocks in global postorder or postorder within the bottom-up
448 // loop tree. Then we can optionally compute global RegPressure.
Andrew Tricke77e84e2012-01-13 06:30:30 +0000449 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
450 MBB != MBBEnd; ++MBB) {
451
Duncan P. N. Exon Smith5ec15682015-10-09 19:40:45 +0000452 Scheduler.startBlock(&*MBB);
Andrew Trickedfe2ec2012-03-09 08:02:51 +0000453
Andrew Trick33e05d72013-12-28 21:57:02 +0000454#ifndef NDEBUG
455 if (SchedOnlyFunc.getNumOccurrences() && SchedOnlyFunc != MF->getName())
456 continue;
457 if (SchedOnlyBlock.getNumOccurrences()
458 && (int)SchedOnlyBlock != MBB->getNumber())
459 continue;
460#endif
461
Andrew Trick7e120f42012-01-14 02:17:09 +0000462 // Break the block into scheduling regions [I, RegionEnd), and schedule each
Sylvestre Ledru35521e22012-07-23 08:51:15 +0000463 // region as soon as it is discovered. RegionEnd points the scheduling
Andrew Trickaf1bee72012-03-09 22:34:56 +0000464 // boundary at the bottom of the region. The DAG does not include RegionEnd,
465 // but the region does (i.e. the next RegionEnd is above the previous
466 // RegionBegin). If the current block has no terminator then RegionEnd ==
467 // MBB->end() for the bottom region.
468 //
469 // The Scheduler may insert instructions during either schedule() or
470 // exitRegion(), even for empty regions. So the local iterators 'I' and
471 // 'RegionEnd' are invalid across these calls.
Andrew Trickd14d7c22013-12-28 21:56:57 +0000472 //
473 // MBB::size() uses instr_iterator to count. Here we need a bundle to count
474 // as a single instruction.
Andrew Tricka21daf72012-03-09 03:46:39 +0000475 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
Andrew Trickd7f890e2013-12-28 21:56:47 +0000476 RegionEnd != MBB->begin(); RegionEnd = Scheduler.begin()) {
Andrew Trick88639922012-04-24 17:56:43 +0000477
Andrew Trickedfe2ec2012-03-09 08:02:51 +0000478 // Avoid decrementing RegionEnd for blocks with no terminator.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000479 if (RegionEnd != MBB->end() ||
Matthias Braun93563e72015-11-03 01:53:29 +0000480 isSchedBoundary(&*std::prev(RegionEnd), &*MBB, MF, TII)) {
Andrew Trickedfe2ec2012-03-09 08:02:51 +0000481 --RegionEnd;
Andrew Trickedfe2ec2012-03-09 08:02:51 +0000482 }
483
Andrew Trick7e120f42012-01-14 02:17:09 +0000484 // The next region starts above the previous region. Look backward in the
485 // instruction stream until we find the nearest boundary.
Andrew Tricka53e1012013-08-23 17:48:33 +0000486 unsigned NumRegionInstrs = 0;
Andrew Trick7e120f42012-01-14 02:17:09 +0000487 MachineBasicBlock::iterator I = RegionEnd;
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +0000488 for (; I != MBB->begin(); --I) {
Duncan P. N. Exon Smith38eea4a2016-08-11 20:03:09 +0000489 MachineInstr &MI = *std::prev(I);
490 if (isSchedBoundary(&MI, &*MBB, MF, TII))
Andrew Trick7e120f42012-01-14 02:17:09 +0000491 break;
Duncan P. N. Exon Smith38eea4a2016-08-11 20:03:09 +0000492 if (!MI.isDebugValue())
Andrea Di Biagiod65fd9f2014-12-12 15:09:58 +0000493 ++NumRegionInstrs;
Andrew Trick7e120f42012-01-14 02:17:09 +0000494 }
Andrew Trick60cf03e2012-03-07 05:21:52 +0000495 // Notify the scheduler of the region, even if we may skip scheduling
496 // it. Perhaps it still needs to be bundled.
Duncan P. N. Exon Smith5ec15682015-10-09 19:40:45 +0000497 Scheduler.enterRegion(&*MBB, I, RegionEnd, NumRegionInstrs);
Andrew Trick60cf03e2012-03-07 05:21:52 +0000498
499 // Skip empty scheduling regions (0 or 1 schedulable instructions).
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000500 if (I == RegionEnd || I == std::prev(RegionEnd)) {
Andrew Trick60cf03e2012-03-07 05:21:52 +0000501 // Close the current region. Bundle the terminator if needed.
Andrew Trickaf1bee72012-03-09 22:34:56 +0000502 // This invalidates 'RegionEnd' and 'I'.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000503 Scheduler.exitRegion();
Andrew Trick7ccdc5c2012-01-17 06:55:07 +0000504 continue;
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000505 }
Matthias Braun93563e72015-11-03 01:53:29 +0000506 DEBUG(dbgs() << "********** MI Scheduling **********\n");
Craig Toppera538d832012-08-22 06:07:19 +0000507 DEBUG(dbgs() << MF->getName()
Andrew Trick54b2ce32013-01-25 07:45:31 +0000508 << ":BB#" << MBB->getNumber() << " " << MBB->getName()
509 << "\n From: " << *I << " To: ";
Andrew Tricke57583a2012-02-08 02:17:21 +0000510 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
511 else dbgs() << "End";
Matthias Braun858d1df2016-05-20 19:46:13 +0000512 dbgs() << " RegionInstrs: " << NumRegionInstrs << '\n');
Gerolf Hoflehnerb5220dc2014-08-07 21:49:44 +0000513 if (DumpCriticalPathLength) {
514 errs() << MF->getName();
515 errs() << ":BB# " << MBB->getNumber();
516 errs() << " " << MBB->getName() << " \n";
517 }
Andrew Trick7ccdc5c2012-01-17 06:55:07 +0000518
Andrew Trick1c0ec452012-03-09 03:46:42 +0000519 // Schedule a region: possibly reorder instructions.
Andrew Trickaf1bee72012-03-09 22:34:56 +0000520 // This invalidates 'RegionEnd' and 'I'.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000521 Scheduler.schedule();
Andrew Trick1c0ec452012-03-09 03:46:42 +0000522
523 // Close the current region.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000524 Scheduler.exitRegion();
Andrew Trick60cf03e2012-03-07 05:21:52 +0000525
526 // Scheduling has invalidated the current iterator 'I'. Ask the
527 // scheduler for the top of it's scheduled region.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000528 RegionEnd = Scheduler.begin();
Andrew Trick7e120f42012-01-14 02:17:09 +0000529 }
Andrew Trickd7f890e2013-12-28 21:56:47 +0000530 Scheduler.finishBlock();
Matthias Braun93563e72015-11-03 01:53:29 +0000531 // FIXME: Ideally, no further passes should rely on kill flags. However,
532 // thumb2 size reduction is currently an exception, so the PostMIScheduler
533 // needs to do this.
534 if (FixKillFlags)
Matthias Braun868bbd42017-05-27 02:50:50 +0000535 Scheduler.fixupKills(*MBB);
Andrew Tricke77e84e2012-01-13 06:30:30 +0000536 }
Andrew Trickd7f890e2013-12-28 21:56:47 +0000537 Scheduler.finalizeSchedule();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000538}
539
Andrew Trickd7f890e2013-12-28 21:56:47 +0000540void MachineSchedulerBase::print(raw_ostream &O, const Module* m) const {
Andrew Tricke77e84e2012-01-13 06:30:30 +0000541 // unimplemented
542}
543
Matthias Braun8c209aa2017-01-28 02:02:38 +0000544#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Sam Clegg705f7982017-06-21 22:19:17 +0000545LLVM_DUMP_METHOD void ReadyQueue::dump() const {
James Y Knighte72b0db2015-09-18 18:52:20 +0000546 dbgs() << "Queue " << Name << ": ";
Javed Absare3a0cc22017-06-21 09:10:10 +0000547 for (const SUnit *SU : Queue)
548 dbgs() << SU->NodeNum << " ";
Andrew Trick7a8e1002012-09-11 00:39:15 +0000549 dbgs() << "\n";
550}
Matthias Braun8c209aa2017-01-28 02:02:38 +0000551#endif
Andrew Trick8823dec2012-03-14 04:00:41 +0000552
553//===----------------------------------------------------------------------===//
Andrew Trickd7f890e2013-12-28 21:56:47 +0000554// ScheduleDAGMI - Basic machine instruction scheduling. This is
555// independent of PreRA/PostRA scheduling and involves no extra book-keeping for
556// virtual registers.
557// ===----------------------------------------------------------------------===/
Andrew Trick8823dec2012-03-14 04:00:41 +0000558
David Blaikie422b93d2014-04-21 20:32:32 +0000559// Provide a vtable anchor.
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +0000560ScheduleDAGMI::~ScheduleDAGMI() = default;
Andrew Trick44f750a2013-01-25 04:01:04 +0000561
Andrew Trick85a1d4c2013-04-24 15:54:43 +0000562bool ScheduleDAGMI::canAddEdge(SUnit *SuccSU, SUnit *PredSU) {
563 return SuccSU == &ExitSU || !Topo.IsReachable(PredSU, SuccSU);
564}
565
Andrew Tricka7714a02012-11-12 19:40:10 +0000566bool ScheduleDAGMI::addEdge(SUnit *SuccSU, const SDep &PredDep) {
Andrew Trick263280242012-11-12 19:52:20 +0000567 if (SuccSU != &ExitSU) {
568 // Do not use WillCreateCycle, it assumes SD scheduling.
569 // If Pred is reachable from Succ, then the edge creates a cycle.
570 if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
571 return false;
572 Topo.AddPred(SuccSU, PredDep.getSUnit());
573 }
Andrew Tricka7714a02012-11-12 19:40:10 +0000574 SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
575 // Return true regardless of whether a new edge needed to be inserted.
576 return true;
577}
578
Andrew Trick02a80da2012-03-08 01:41:12 +0000579/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
580/// NumPredsLeft reaches zero, release the successor node.
Andrew Trick61f1a272012-05-24 22:11:09 +0000581///
582/// FIXME: Adjust SuccSU height based on MinLatency.
Andrew Trick8823dec2012-03-14 04:00:41 +0000583void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
Andrew Trick02a80da2012-03-08 01:41:12 +0000584 SUnit *SuccSU = SuccEdge->getSUnit();
585
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000586 if (SuccEdge->isWeak()) {
587 --SuccSU->WeakPredsLeft;
Andrew Tricka7714a02012-11-12 19:40:10 +0000588 if (SuccEdge->isCluster())
589 NextClusterSucc = SuccSU;
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000590 return;
591 }
Andrew Trick02a80da2012-03-08 01:41:12 +0000592#ifndef NDEBUG
593 if (SuccSU->NumPredsLeft == 0) {
594 dbgs() << "*** Scheduling failed! ***\n";
595 SuccSU->dump(this);
596 dbgs() << " has been released too many times!\n";
Craig Topperc0196b12014-04-14 00:51:57 +0000597 llvm_unreachable(nullptr);
Andrew Trick02a80da2012-03-08 01:41:12 +0000598 }
599#endif
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000600 // SU->TopReadyCycle was set to CurrCycle when it was scheduled. However,
601 // CurrCycle may have advanced since then.
602 if (SuccSU->TopReadyCycle < SU->TopReadyCycle + SuccEdge->getLatency())
603 SuccSU->TopReadyCycle = SU->TopReadyCycle + SuccEdge->getLatency();
604
Andrew Trick02a80da2012-03-08 01:41:12 +0000605 --SuccSU->NumPredsLeft;
606 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
Andrew Trick8823dec2012-03-14 04:00:41 +0000607 SchedImpl->releaseTopNode(SuccSU);
Andrew Trick02a80da2012-03-08 01:41:12 +0000608}
609
610/// releaseSuccessors - Call releaseSucc on each of SU's successors.
Andrew Trick8823dec2012-03-14 04:00:41 +0000611void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
Javed Absare3a0cc22017-06-21 09:10:10 +0000612 for (SDep &Succ : SU->Succs)
613 releaseSucc(SU, &Succ);
Andrew Trick02a80da2012-03-08 01:41:12 +0000614}
615
Andrew Trick8823dec2012-03-14 04:00:41 +0000616/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
617/// NumSuccsLeft reaches zero, release the predecessor node.
Andrew Trick61f1a272012-05-24 22:11:09 +0000618///
619/// FIXME: Adjust PredSU height based on MinLatency.
Andrew Trick8823dec2012-03-14 04:00:41 +0000620void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
621 SUnit *PredSU = PredEdge->getSUnit();
622
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000623 if (PredEdge->isWeak()) {
624 --PredSU->WeakSuccsLeft;
Andrew Tricka7714a02012-11-12 19:40:10 +0000625 if (PredEdge->isCluster())
626 NextClusterPred = PredSU;
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000627 return;
628 }
Andrew Trick8823dec2012-03-14 04:00:41 +0000629#ifndef NDEBUG
630 if (PredSU->NumSuccsLeft == 0) {
631 dbgs() << "*** Scheduling failed! ***\n";
632 PredSU->dump(this);
633 dbgs() << " has been released too many times!\n";
Craig Topperc0196b12014-04-14 00:51:57 +0000634 llvm_unreachable(nullptr);
Andrew Trick8823dec2012-03-14 04:00:41 +0000635 }
636#endif
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000637 // SU->BotReadyCycle was set to CurrCycle when it was scheduled. However,
638 // CurrCycle may have advanced since then.
639 if (PredSU->BotReadyCycle < SU->BotReadyCycle + PredEdge->getLatency())
640 PredSU->BotReadyCycle = SU->BotReadyCycle + PredEdge->getLatency();
641
Andrew Trick8823dec2012-03-14 04:00:41 +0000642 --PredSU->NumSuccsLeft;
643 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
644 SchedImpl->releaseBottomNode(PredSU);
645}
646
647/// releasePredecessors - Call releasePred on each of SU's predecessors.
648void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
Javed Absare3a0cc22017-06-21 09:10:10 +0000649 for (SDep &Pred : SU->Preds)
650 releasePred(SU, &Pred);
Andrew Trick8823dec2012-03-14 04:00:41 +0000651}
652
Andrew Trickd7f890e2013-12-28 21:56:47 +0000653/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
654/// crossing a scheduling boundary. [begin, end) includes all instructions in
655/// the region, including the boundary itself and single-instruction regions
656/// that don't get scheduled.
657void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
658 MachineBasicBlock::iterator begin,
659 MachineBasicBlock::iterator end,
660 unsigned regioninstrs)
661{
662 ScheduleDAGInstrs::enterRegion(bb, begin, end, regioninstrs);
663
664 SchedImpl->initPolicy(begin, end, regioninstrs);
665}
666
Andrew Tricke833e1c2013-04-13 06:07:40 +0000667/// This is normally called from the main scheduler loop but may also be invoked
668/// by the scheduling strategy to perform additional code motion.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000669void ScheduleDAGMI::moveInstruction(
670 MachineInstr *MI, MachineBasicBlock::iterator InsertPos) {
Andrew Trick463b2f12012-05-17 18:35:03 +0000671 // Advance RegionBegin if the first instruction moves down.
Andrew Trick54f7def2012-03-21 04:12:10 +0000672 if (&*RegionBegin == MI)
Andrew Trick463b2f12012-05-17 18:35:03 +0000673 ++RegionBegin;
674
675 // Update the instruction stream.
Andrew Trick8823dec2012-03-14 04:00:41 +0000676 BB->splice(InsertPos, BB, MI);
Andrew Trick463b2f12012-05-17 18:35:03 +0000677
678 // Update LiveIntervals
Andrew Trickd7f890e2013-12-28 21:56:47 +0000679 if (LIS)
Duncan P. N. Exon Smithbe8f8c42016-02-27 20:14:29 +0000680 LIS->handleMove(*MI, /*UpdateFlags=*/true);
Andrew Trick463b2f12012-05-17 18:35:03 +0000681
682 // Recede RegionBegin if an instruction moves above the first.
Andrew Trick8823dec2012-03-14 04:00:41 +0000683 if (RegionBegin == InsertPos)
684 RegionBegin = MI;
685}
686
Andrew Trickde670c02012-03-21 04:12:07 +0000687bool ScheduleDAGMI::checkSchedLimit() {
688#ifndef NDEBUG
689 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
690 CurrentTop = CurrentBottom;
691 return false;
692 }
693 ++NumInstrsScheduled;
694#endif
695 return true;
696}
697
Andrew Trickd7f890e2013-12-28 21:56:47 +0000698/// Per-region scheduling driver, called back from
699/// MachineScheduler::runOnMachineFunction. This is a simplified driver that
700/// does not consider liveness or register pressure. It is useful for PostRA
701/// scheduling and potentially other custom schedulers.
702void ScheduleDAGMI::schedule() {
James Y Knighte72b0db2015-09-18 18:52:20 +0000703 DEBUG(dbgs() << "ScheduleDAGMI::schedule starting\n");
704 DEBUG(SchedImpl->dumpPolicy());
705
Andrew Trickd7f890e2013-12-28 21:56:47 +0000706 // Build the DAG.
707 buildSchedGraph(AA);
708
709 Topo.InitDAGTopologicalSorting();
710
711 postprocessDAG();
712
713 SmallVector<SUnit*, 8> TopRoots, BotRoots;
714 findRootsAndBiasEdges(TopRoots, BotRoots);
715
716 // Initialize the strategy before modifying the DAG.
717 // This may initialize a DFSResult to be used for queue priority.
718 SchedImpl->initialize(this);
719
Matthias Braun69f1d122016-11-11 22:37:28 +0000720 DEBUG(
721 if (EntrySU.getInstr() != nullptr)
722 EntrySU.dumpAll(this);
Javed Absare3a0cc22017-06-21 09:10:10 +0000723 for (const SUnit &SU : SUnits)
724 SU.dumpAll(this);
Matthias Braun69f1d122016-11-11 22:37:28 +0000725 if (ExitSU.getInstr() != nullptr)
726 ExitSU.dumpAll(this);
727 );
Andrew Trickd7f890e2013-12-28 21:56:47 +0000728 if (ViewMISchedDAGs) viewGraph();
729
730 // Initialize ready queues now that the DAG and priority data are finalized.
731 initQueues(TopRoots, BotRoots);
732
733 bool IsTopNode = false;
James Y Knighte72b0db2015-09-18 18:52:20 +0000734 while (true) {
735 DEBUG(dbgs() << "** ScheduleDAGMI::schedule picking next node\n");
736 SUnit *SU = SchedImpl->pickNode(IsTopNode);
737 if (!SU) break;
738
Andrew Trickd7f890e2013-12-28 21:56:47 +0000739 assert(!SU->isScheduled && "Node already scheduled");
740 if (!checkSchedLimit())
741 break;
742
743 MachineInstr *MI = SU->getInstr();
744 if (IsTopNode) {
745 assert(SU->isTopReady() && "node still has unscheduled dependencies");
746 if (&*CurrentTop == MI)
747 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
748 else
749 moveInstruction(MI, CurrentTop);
Matthias Braunb550b762016-04-21 01:54:13 +0000750 } else {
Andrew Trickd7f890e2013-12-28 21:56:47 +0000751 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
752 MachineBasicBlock::iterator priorII =
753 priorNonDebug(CurrentBottom, CurrentTop);
754 if (&*priorII == MI)
755 CurrentBottom = priorII;
756 else {
757 if (&*CurrentTop == MI)
758 CurrentTop = nextIfDebug(++CurrentTop, priorII);
759 moveInstruction(MI, CurrentBottom);
760 CurrentBottom = MI;
761 }
762 }
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000763 // Notify the scheduling strategy before updating the DAG.
Andrew Trick491e34a2014-06-12 22:36:28 +0000764 // This sets the scheduled node's ReadyCycle to CurrCycle. When updateQueues
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000765 // runs, it can then use the accurate ReadyCycle time to determine whether
766 // newly released nodes can move to the readyQ.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000767 SchedImpl->schedNode(SU, IsTopNode);
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000768
769 updateQueues(SU, IsTopNode);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000770 }
771 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
772
773 placeDebugValues();
774
775 DEBUG({
776 unsigned BBNum = begin()->getParent()->getNumber();
777 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
778 dumpSchedule();
779 dbgs() << '\n';
780 });
781}
782
783/// Apply each ScheduleDAGMutation step in order.
784void ScheduleDAGMI::postprocessDAG() {
Javed Absare3a0cc22017-06-21 09:10:10 +0000785 for (auto &m : Mutations)
786 m->apply(this);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000787}
788
789void ScheduleDAGMI::
790findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
791 SmallVectorImpl<SUnit*> &BotRoots) {
Javed Absare3a0cc22017-06-21 09:10:10 +0000792 for (SUnit &SU : SUnits) {
793 assert(!SU.isBoundaryNode() && "Boundary node should not be in SUnits");
Andrew Trickd7f890e2013-12-28 21:56:47 +0000794
795 // Order predecessors so DFSResult follows the critical path.
Javed Absare3a0cc22017-06-21 09:10:10 +0000796 SU.biasCriticalPath();
Andrew Trickd7f890e2013-12-28 21:56:47 +0000797
798 // A SUnit is ready to top schedule if it has no predecessors.
Javed Absare3a0cc22017-06-21 09:10:10 +0000799 if (!SU.NumPredsLeft)
800 TopRoots.push_back(&SU);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000801 // A SUnit is ready to bottom schedule if it has no successors.
Javed Absare3a0cc22017-06-21 09:10:10 +0000802 if (!SU.NumSuccsLeft)
803 BotRoots.push_back(&SU);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000804 }
805 ExitSU.biasCriticalPath();
806}
807
808/// Identify DAG roots and setup scheduler queues.
809void ScheduleDAGMI::initQueues(ArrayRef<SUnit*> TopRoots,
810 ArrayRef<SUnit*> BotRoots) {
Craig Topperc0196b12014-04-14 00:51:57 +0000811 NextClusterSucc = nullptr;
812 NextClusterPred = nullptr;
Andrew Trickd7f890e2013-12-28 21:56:47 +0000813
814 // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
815 //
816 // Nodes with unreleased weak edges can still be roots.
817 // Release top roots in forward order.
Javed Absare3a0cc22017-06-21 09:10:10 +0000818 for (SUnit *SU : TopRoots)
819 SchedImpl->releaseTopNode(SU);
820
Andrew Trickd7f890e2013-12-28 21:56:47 +0000821 // Release bottom roots in reverse order so the higher priority nodes appear
822 // first. This is more natural and slightly more efficient.
823 for (SmallVectorImpl<SUnit*>::const_reverse_iterator
824 I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I) {
825 SchedImpl->releaseBottomNode(*I);
826 }
827
828 releaseSuccessors(&EntrySU);
829 releasePredecessors(&ExitSU);
830
831 SchedImpl->registerRoots();
832
833 // Advance past initial DebugValues.
834 CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
835 CurrentBottom = RegionEnd;
836}
837
838/// Update scheduler queues after scheduling an instruction.
839void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
840 // Release dependent instructions for scheduling.
841 if (IsTopNode)
842 releaseSuccessors(SU);
843 else
844 releasePredecessors(SU);
845
846 SU->isScheduled = true;
847}
848
849/// Reinsert any remaining debug_values, just like the PostRA scheduler.
850void ScheduleDAGMI::placeDebugValues() {
851 // If first instruction was a DBG_VALUE then put it back.
852 if (FirstDbgValue) {
853 BB->splice(RegionBegin, BB, FirstDbgValue);
854 RegionBegin = FirstDbgValue;
855 }
856
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +0000857 for (std::vector<std::pair<MachineInstr *, MachineInstr *>>::iterator
Andrew Trickd7f890e2013-12-28 21:56:47 +0000858 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000859 std::pair<MachineInstr *, MachineInstr *> P = *std::prev(DI);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000860 MachineInstr *DbgValue = P.first;
861 MachineBasicBlock::iterator OrigPrevMI = P.second;
862 if (&*RegionBegin == DbgValue)
863 ++RegionBegin;
864 BB->splice(++OrigPrevMI, BB, DbgValue);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000865 if (OrigPrevMI == std::prev(RegionEnd))
Andrew Trickd7f890e2013-12-28 21:56:47 +0000866 RegionEnd = DbgValue;
867 }
868 DbgValues.clear();
Craig Topperc0196b12014-04-14 00:51:57 +0000869 FirstDbgValue = nullptr;
Andrew Trickd7f890e2013-12-28 21:56:47 +0000870}
871
872#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Matthias Braun8c209aa2017-01-28 02:02:38 +0000873LLVM_DUMP_METHOD void ScheduleDAGMI::dumpSchedule() const {
Andrew Trickd7f890e2013-12-28 21:56:47 +0000874 for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
875 if (SUnit *SU = getSUnit(&(*MI)))
876 SU->dump(this);
877 else
878 dbgs() << "Missing SUnit\n";
879 }
880}
881#endif
882
883//===----------------------------------------------------------------------===//
884// ScheduleDAGMILive - Base class for MachineInstr scheduling with LiveIntervals
885// preservation.
886//===----------------------------------------------------------------------===//
887
888ScheduleDAGMILive::~ScheduleDAGMILive() {
889 delete DFSResult;
890}
891
Matthias Braun40639882016-11-11 22:37:31 +0000892void ScheduleDAGMILive::collectVRegUses(SUnit &SU) {
893 const MachineInstr &MI = *SU.getInstr();
894 for (const MachineOperand &MO : MI.operands()) {
895 if (!MO.isReg())
896 continue;
897 if (!MO.readsReg())
898 continue;
899 if (TrackLaneMasks && !MO.isUse())
900 continue;
901
902 unsigned Reg = MO.getReg();
903 if (!TargetRegisterInfo::isVirtualRegister(Reg))
904 continue;
905
906 // Ignore re-defs.
907 if (TrackLaneMasks) {
908 bool FoundDef = false;
909 for (const MachineOperand &MO2 : MI.operands()) {
910 if (MO2.isReg() && MO2.isDef() && MO2.getReg() == Reg && !MO2.isDead()) {
911 FoundDef = true;
912 break;
913 }
914 }
915 if (FoundDef)
916 continue;
917 }
918
919 // Record this local VReg use.
920 VReg2SUnitMultiMap::iterator UI = VRegUses.find(Reg);
921 for (; UI != VRegUses.end(); ++UI) {
922 if (UI->SU == &SU)
923 break;
924 }
925 if (UI == VRegUses.end())
Krzysztof Parzyszek91b5cf82016-12-15 14:36:06 +0000926 VRegUses.insert(VReg2SUnit(Reg, LaneBitmask::getNone(), &SU));
Matthias Braun40639882016-11-11 22:37:31 +0000927 }
928}
929
Andrew Trick88639922012-04-24 17:56:43 +0000930/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
931/// crossing a scheduling boundary. [begin, end) includes all instructions in
932/// the region, including the boundary itself and single-instruction regions
933/// that don't get scheduled.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000934void ScheduleDAGMILive::enterRegion(MachineBasicBlock *bb,
Andrew Trick88639922012-04-24 17:56:43 +0000935 MachineBasicBlock::iterator begin,
936 MachineBasicBlock::iterator end,
Andrew Tricka53e1012013-08-23 17:48:33 +0000937 unsigned regioninstrs)
Andrew Trick88639922012-04-24 17:56:43 +0000938{
Andrew Trickd7f890e2013-12-28 21:56:47 +0000939 // ScheduleDAGMI initializes SchedImpl's per-region policy.
940 ScheduleDAGMI::enterRegion(bb, begin, end, regioninstrs);
Andrew Trick4add42f2012-05-10 21:06:10 +0000941
942 // For convenience remember the end of the liveness region.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000943 LiveRegionEnd = (RegionEnd == bb->end()) ? RegionEnd : std::next(RegionEnd);
Andrew Trick75e411c2013-09-06 17:32:34 +0000944
Andrew Trickb248b4a2013-09-06 17:32:47 +0000945 SUPressureDiffs.clear();
946
Andrew Trick75e411c2013-09-06 17:32:34 +0000947 ShouldTrackPressure = SchedImpl->shouldTrackPressure();
Matthias Braund4f64092016-01-20 00:23:32 +0000948 ShouldTrackLaneMasks = SchedImpl->shouldTrackLaneMasks();
949
Matthias Braunf9acaca2016-05-31 22:38:06 +0000950 assert((!ShouldTrackLaneMasks || ShouldTrackPressure) &&
951 "ShouldTrackLaneMasks requires ShouldTrackPressure");
Andrew Trick4add42f2012-05-10 21:06:10 +0000952}
953
954// Setup the register pressure trackers for the top scheduled top and bottom
955// scheduled regions.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000956void ScheduleDAGMILive::initRegPressure() {
Matthias Braun40639882016-11-11 22:37:31 +0000957 VRegUses.clear();
958 VRegUses.setUniverse(MRI.getNumVirtRegs());
959 for (SUnit &SU : SUnits)
960 collectVRegUses(SU);
961
Matthias Braund4f64092016-01-20 00:23:32 +0000962 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin,
963 ShouldTrackLaneMasks, false);
964 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
965 ShouldTrackLaneMasks, false);
Andrew Trick4add42f2012-05-10 21:06:10 +0000966
967 // Close the RPTracker to finalize live ins.
968 RPTracker.closeRegion();
969
Andrew Trick9c17eab2013-07-30 19:59:12 +0000970 DEBUG(RPTracker.dump());
Andrew Trick79d3eec2012-05-24 22:11:14 +0000971
Andrew Trick4add42f2012-05-10 21:06:10 +0000972 // Initialize the live ins and live outs.
Matthias Braun3e86de12015-09-17 21:12:24 +0000973 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
974 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
Andrew Trick4add42f2012-05-10 21:06:10 +0000975
976 // Close one end of the tracker so we can call
977 // getMaxUpward/DownwardPressureDelta before advancing across any
978 // instructions. This converts currently live regs into live ins/outs.
979 TopRPTracker.closeTop();
980 BotRPTracker.closeBottom();
981
Andrew Trick9c17eab2013-07-30 19:59:12 +0000982 BotRPTracker.initLiveThru(RPTracker);
983 if (!BotRPTracker.getLiveThru().empty()) {
984 TopRPTracker.initLiveThru(BotRPTracker.getLiveThru());
985 DEBUG(dbgs() << "Live Thru: ";
986 dumpRegSetPressure(BotRPTracker.getLiveThru(), TRI));
987 };
988
Andrew Trick2bc74c22013-08-30 04:36:57 +0000989 // For each live out vreg reduce the pressure change associated with other
990 // uses of the same vreg below the live-out reaching def.
Matthias Braun3e86de12015-09-17 21:12:24 +0000991 updatePressureDiffs(RPTracker.getPressure().LiveOutRegs);
Andrew Trick2bc74c22013-08-30 04:36:57 +0000992
Andrew Trick4add42f2012-05-10 21:06:10 +0000993 // Account for liveness generated by the region boundary.
Andrew Trick2bc74c22013-08-30 04:36:57 +0000994 if (LiveRegionEnd != RegionEnd) {
Matthias Braun5d458612016-01-20 00:23:26 +0000995 SmallVector<RegisterMaskPair, 8> LiveUses;
Andrew Trick2bc74c22013-08-30 04:36:57 +0000996 BotRPTracker.recede(&LiveUses);
997 updatePressureDiffs(LiveUses);
998 }
Andrew Trick4add42f2012-05-10 21:06:10 +0000999
Matthias Braune6edd482015-11-13 22:30:31 +00001000 DEBUG(
1001 dbgs() << "Top Pressure:\n";
1002 dumpRegSetPressure(TopRPTracker.getRegSetPressureAtPos(), TRI);
1003 dbgs() << "Bottom Pressure:\n";
1004 dumpRegSetPressure(BotRPTracker.getRegSetPressureAtPos(), TRI);
1005 );
1006
Andrew Trick4add42f2012-05-10 21:06:10 +00001007 assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
Andrew Trick22025772012-05-17 18:35:10 +00001008
1009 // Cache the list of excess pressure sets in this region. This will also track
1010 // the max pressure in the scheduled code for these sets.
1011 RegionCriticalPSets.clear();
Jakub Staszakc641ada2013-01-25 21:44:27 +00001012 const std::vector<unsigned> &RegionPressure =
1013 RPTracker.getPressure().MaxSetPressure;
Andrew Trick22025772012-05-17 18:35:10 +00001014 for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
Andrew Trick736dd9a2013-06-21 18:32:58 +00001015 unsigned Limit = RegClassInfo->getRegPressureSetLimit(i);
Andrew Trickb55db582013-06-21 18:33:01 +00001016 if (RegionPressure[i] > Limit) {
1017 DEBUG(dbgs() << TRI->getRegPressureSetName(i)
1018 << " Limit " << Limit
1019 << " Actual " << RegionPressure[i] << "\n");
Andrew Trick1a831342013-08-30 03:49:48 +00001020 RegionCriticalPSets.push_back(PressureChange(i));
Andrew Trickb55db582013-06-21 18:33:01 +00001021 }
Andrew Trick22025772012-05-17 18:35:10 +00001022 }
1023 DEBUG(dbgs() << "Excess PSets: ";
Javed Absare3a0cc22017-06-21 09:10:10 +00001024 for (const PressureChange &RCPS : RegionCriticalPSets)
Andrew Trick22025772012-05-17 18:35:10 +00001025 dbgs() << TRI->getRegPressureSetName(
Javed Absare3a0cc22017-06-21 09:10:10 +00001026 RCPS.getPSet()) << " ";
Andrew Trick22025772012-05-17 18:35:10 +00001027 dbgs() << "\n");
1028}
1029
Andrew Trickd7f890e2013-12-28 21:56:47 +00001030void ScheduleDAGMILive::
Andrew Trickb248b4a2013-09-06 17:32:47 +00001031updateScheduledPressure(const SUnit *SU,
1032 const std::vector<unsigned> &NewMaxPressure) {
1033 const PressureDiff &PDiff = getPressureDiff(SU);
1034 unsigned CritIdx = 0, CritEnd = RegionCriticalPSets.size();
Javed Absare3a0cc22017-06-21 09:10:10 +00001035 for (const PressureChange &PC : PDiff) {
1036 if (!PC.isValid())
Andrew Trickb248b4a2013-09-06 17:32:47 +00001037 break;
Javed Absare3a0cc22017-06-21 09:10:10 +00001038 unsigned ID = PC.getPSet();
Andrew Trickb248b4a2013-09-06 17:32:47 +00001039 while (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() < ID)
1040 ++CritIdx;
1041 if (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() == ID) {
1042 if ((int)NewMaxPressure[ID] > RegionCriticalPSets[CritIdx].getUnitInc()
Simon Pilgrim858d8e62017-02-23 12:00:34 +00001043 && NewMaxPressure[ID] <= (unsigned)std::numeric_limits<int16_t>::max())
Andrew Trickb248b4a2013-09-06 17:32:47 +00001044 RegionCriticalPSets[CritIdx].setUnitInc(NewMaxPressure[ID]);
1045 }
1046 unsigned Limit = RegClassInfo->getRegPressureSetLimit(ID);
1047 if (NewMaxPressure[ID] >= Limit - 2) {
1048 DEBUG(dbgs() << " " << TRI->getRegPressureSetName(ID) << ": "
Andrew Trick569dc65a2015-05-17 23:40:31 +00001049 << NewMaxPressure[ID]
1050 << ((NewMaxPressure[ID] > Limit) ? " > " : " <= ") << Limit
1051 << "(+ " << BotRPTracker.getLiveThru()[ID] << " livethru)\n");
Andrew Trickb248b4a2013-09-06 17:32:47 +00001052 }
Andrew Trick22025772012-05-17 18:35:10 +00001053 }
Andrew Trick88639922012-04-24 17:56:43 +00001054}
1055
Andrew Trick2bc74c22013-08-30 04:36:57 +00001056/// Update the PressureDiff array for liveness after scheduling this
1057/// instruction.
Matthias Braun5d458612016-01-20 00:23:26 +00001058void ScheduleDAGMILive::updatePressureDiffs(
1059 ArrayRef<RegisterMaskPair> LiveUses) {
1060 for (const RegisterMaskPair &P : LiveUses) {
Matthias Braun5d458612016-01-20 00:23:26 +00001061 unsigned Reg = P.RegUnit;
Matthias Braund4f64092016-01-20 00:23:32 +00001062 /// FIXME: Currently assuming single-use physregs.
Andrew Trick2bc74c22013-08-30 04:36:57 +00001063 if (!TRI->isVirtualRegister(Reg))
1064 continue;
Andrew Trickffdbefb2013-09-06 17:32:39 +00001065
Matthias Braund4f64092016-01-20 00:23:32 +00001066 if (ShouldTrackLaneMasks) {
1067 // If the register has just become live then other uses won't change
1068 // this fact anymore => decrement pressure.
1069 // If the register has just become dead then other uses make it come
1070 // back to life => increment pressure.
Krzysztof Parzyszekea9f8ce2016-12-16 19:11:56 +00001071 bool Decrement = P.LaneMask.any();
Matthias Braund4f64092016-01-20 00:23:32 +00001072
1073 for (const VReg2SUnit &V2SU
1074 : make_range(VRegUses.find(Reg), VRegUses.end())) {
1075 SUnit &SU = *V2SU.SU;
1076 if (SU.isScheduled || &SU == &ExitSU)
1077 continue;
1078
1079 PressureDiff &PDiff = getPressureDiff(&SU);
Stanislav Mekhanoshin42259cf2017-02-24 21:56:16 +00001080 PDiff.addPressureChange(Reg, Decrement, &MRI);
Matthias Braund4f64092016-01-20 00:23:32 +00001081 DEBUG(
1082 dbgs() << " UpdateRegP: SU(" << SU.NodeNum << ") "
1083 << PrintReg(Reg, TRI) << ':' << PrintLaneMask(P.LaneMask)
1084 << ' ' << *SU.getInstr();
1085 dbgs() << " to ";
1086 PDiff.dump(*TRI);
1087 );
1088 }
1089 } else {
Krzysztof Parzyszekea9f8ce2016-12-16 19:11:56 +00001090 assert(P.LaneMask.any());
Matthias Braund4f64092016-01-20 00:23:32 +00001091 DEBUG(dbgs() << " LiveReg: " << PrintVRegOrUnit(Reg, TRI) << "\n");
1092 // This may be called before CurrentBottom has been initialized. However,
1093 // BotRPTracker must have a valid position. We want the value live into the
1094 // instruction or live out of the block, so ask for the previous
1095 // instruction's live-out.
1096 const LiveInterval &LI = LIS->getInterval(Reg);
1097 VNInfo *VNI;
1098 MachineBasicBlock::const_iterator I =
1099 nextIfDebug(BotRPTracker.getPos(), BB->end());
1100 if (I == BB->end())
1101 VNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
1102 else {
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001103 LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(*I));
Matthias Braund4f64092016-01-20 00:23:32 +00001104 VNI = LRQ.valueIn();
1105 }
1106 // RegisterPressureTracker guarantees that readsReg is true for LiveUses.
1107 assert(VNI && "No live value at use.");
1108 for (const VReg2SUnit &V2SU
1109 : make_range(VRegUses.find(Reg), VRegUses.end())) {
1110 SUnit *SU = V2SU.SU;
1111 // If this use comes before the reaching def, it cannot be a last use,
1112 // so decrease its pressure change.
1113 if (!SU->isScheduled && SU != &ExitSU) {
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001114 LiveQueryResult LRQ =
1115 LI.Query(LIS->getInstructionIndex(*SU->getInstr()));
Matthias Braund4f64092016-01-20 00:23:32 +00001116 if (LRQ.valueIn() == VNI) {
1117 PressureDiff &PDiff = getPressureDiff(SU);
Stanislav Mekhanoshin42259cf2017-02-24 21:56:16 +00001118 PDiff.addPressureChange(Reg, true, &MRI);
Matthias Braund4f64092016-01-20 00:23:32 +00001119 DEBUG(
1120 dbgs() << " UpdateRegP: SU(" << SU->NodeNum << ") "
1121 << *SU->getInstr();
1122 dbgs() << " to ";
1123 PDiff.dump(*TRI);
1124 );
1125 }
Matthias Braun9198c672015-11-06 20:59:02 +00001126 }
Andrew Trick2bc74c22013-08-30 04:36:57 +00001127 }
1128 }
1129 }
1130}
1131
Andrew Trick8823dec2012-03-14 04:00:41 +00001132/// schedule - Called back from MachineScheduler::runOnMachineFunction
Andrew Trick88639922012-04-24 17:56:43 +00001133/// after setting up the current scheduling region. [RegionBegin, RegionEnd)
1134/// only includes instructions that have DAG nodes, not scheduling boundaries.
Andrew Trick7a8e1002012-09-11 00:39:15 +00001135///
1136/// This is a skeletal driver, with all the functionality pushed into helpers,
Nick Lewycky06b0ea22015-08-18 22:41:58 +00001137/// so that it can be easily extended by experimental schedulers. Generally,
Andrew Trick7a8e1002012-09-11 00:39:15 +00001138/// implementing MachineSchedStrategy should be sufficient to implement a new
1139/// scheduling algorithm. However, if a scheduler further subclasses
Andrew Trickd7f890e2013-12-28 21:56:47 +00001140/// ScheduleDAGMILive then it will want to override this virtual method in order
1141/// to update any specialized state.
1142void ScheduleDAGMILive::schedule() {
James Y Knighte72b0db2015-09-18 18:52:20 +00001143 DEBUG(dbgs() << "ScheduleDAGMILive::schedule starting\n");
1144 DEBUG(SchedImpl->dumpPolicy());
Andrew Trick7a8e1002012-09-11 00:39:15 +00001145 buildDAGWithRegPressure();
1146
Andrew Tricka7714a02012-11-12 19:40:10 +00001147 Topo.InitDAGTopologicalSorting();
1148
Andrew Tricka2733e92012-09-14 17:22:42 +00001149 postprocessDAG();
1150
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001151 SmallVector<SUnit*, 8> TopRoots, BotRoots;
1152 findRootsAndBiasEdges(TopRoots, BotRoots);
1153
1154 // Initialize the strategy before modifying the DAG.
1155 // This may initialize a DFSResult to be used for queue priority.
1156 SchedImpl->initialize(this);
1157
Matthias Braun9198c672015-11-06 20:59:02 +00001158 DEBUG(
Matthias Braun69f1d122016-11-11 22:37:28 +00001159 if (EntrySU.getInstr() != nullptr)
1160 EntrySU.dumpAll(this);
Matthias Braun9198c672015-11-06 20:59:02 +00001161 for (const SUnit &SU : SUnits) {
1162 SU.dumpAll(this);
1163 if (ShouldTrackPressure) {
1164 dbgs() << " Pressure Diff : ";
1165 getPressureDiff(&SU).dump(*TRI);
1166 }
Javed Absar3d594372017-03-27 20:46:37 +00001167 dbgs() << " Single Issue : ";
1168 if (SchedModel.mustBeginGroup(SU.getInstr()) &&
1169 SchedModel.mustEndGroup(SU.getInstr()))
1170 dbgs() << "true;";
1171 else
1172 dbgs() << "false;";
Matthias Braun9198c672015-11-06 20:59:02 +00001173 dbgs() << '\n';
1174 }
Matthias Braun69f1d122016-11-11 22:37:28 +00001175 if (ExitSU.getInstr() != nullptr)
1176 ExitSU.dumpAll(this);
Matthias Braun9198c672015-11-06 20:59:02 +00001177 );
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001178 if (ViewMISchedDAGs) viewGraph();
Andrew Trick7a8e1002012-09-11 00:39:15 +00001179
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001180 // Initialize ready queues now that the DAG and priority data are finalized.
1181 initQueues(TopRoots, BotRoots);
Andrew Trick7a8e1002012-09-11 00:39:15 +00001182
1183 bool IsTopNode = false;
James Y Knighte72b0db2015-09-18 18:52:20 +00001184 while (true) {
1185 DEBUG(dbgs() << "** ScheduleDAGMILive::schedule picking next node\n");
1186 SUnit *SU = SchedImpl->pickNode(IsTopNode);
1187 if (!SU) break;
1188
Andrew Trick984d98b2012-10-08 18:53:53 +00001189 assert(!SU->isScheduled && "Node already scheduled");
Andrew Trick7a8e1002012-09-11 00:39:15 +00001190 if (!checkSchedLimit())
1191 break;
1192
1193 scheduleMI(SU, IsTopNode);
1194
Andrew Trickd7f890e2013-12-28 21:56:47 +00001195 if (DFSResult) {
1196 unsigned SubtreeID = DFSResult->getSubtreeID(SU);
1197 if (!ScheduledTrees.test(SubtreeID)) {
1198 ScheduledTrees.set(SubtreeID);
1199 DFSResult->scheduleTree(SubtreeID);
1200 SchedImpl->scheduleTree(SubtreeID);
1201 }
1202 }
1203
1204 // Notify the scheduling strategy after updating the DAG.
1205 SchedImpl->schedNode(SU, IsTopNode);
Andrew Trick43adfb32015-03-27 06:10:13 +00001206
1207 updateQueues(SU, IsTopNode);
Andrew Trick7a8e1002012-09-11 00:39:15 +00001208 }
1209 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
1210
1211 placeDebugValues();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001212
1213 DEBUG({
Andrew Trickcf7e6972012-11-28 03:42:47 +00001214 unsigned BBNum = begin()->getParent()->getNumber();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001215 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
1216 dumpSchedule();
1217 dbgs() << '\n';
1218 });
Andrew Trick7a8e1002012-09-11 00:39:15 +00001219}
1220
1221/// Build the DAG and setup three register pressure trackers.
Andrew Trickd7f890e2013-12-28 21:56:47 +00001222void ScheduleDAGMILive::buildDAGWithRegPressure() {
Andrew Trickb6e74712013-09-04 20:59:59 +00001223 if (!ShouldTrackPressure) {
1224 RPTracker.reset();
1225 RegionCriticalPSets.clear();
1226 buildSchedGraph(AA);
1227 return;
1228 }
1229
Andrew Trick4add42f2012-05-10 21:06:10 +00001230 // Initialize the register pressure tracker used by buildSchedGraph.
Andrew Trick9c17eab2013-07-30 19:59:12 +00001231 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
Matthias Braund4f64092016-01-20 00:23:32 +00001232 ShouldTrackLaneMasks, /*TrackUntiedDefs=*/true);
Andrew Trick88639922012-04-24 17:56:43 +00001233
Andrew Trick4add42f2012-05-10 21:06:10 +00001234 // Account for liveness generate by the region boundary.
1235 if (LiveRegionEnd != RegionEnd)
1236 RPTracker.recede();
1237
1238 // Build the DAG, and compute current register pressure.
Matthias Braund4f64092016-01-20 00:23:32 +00001239 buildSchedGraph(AA, &RPTracker, &SUPressureDiffs, LIS, ShouldTrackLaneMasks);
Andrew Trick02a80da2012-03-08 01:41:12 +00001240
Andrew Trick4add42f2012-05-10 21:06:10 +00001241 // Initialize top/bottom trackers after computing region pressure.
1242 initRegPressure();
Andrew Trick7a8e1002012-09-11 00:39:15 +00001243}
Andrew Trick4add42f2012-05-10 21:06:10 +00001244
Andrew Trickd7f890e2013-12-28 21:56:47 +00001245void ScheduleDAGMILive::computeDFSResult() {
Andrew Trick44f750a2013-01-25 04:01:04 +00001246 if (!DFSResult)
1247 DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize);
1248 DFSResult->clear();
Andrew Trick44f750a2013-01-25 04:01:04 +00001249 ScheduledTrees.clear();
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001250 DFSResult->resize(SUnits.size());
1251 DFSResult->compute(SUnits);
Andrew Trick44f750a2013-01-25 04:01:04 +00001252 ScheduledTrees.resize(DFSResult->getNumSubtrees());
1253}
1254
Andrew Trick483f4192013-08-29 18:04:49 +00001255/// Compute the max cyclic critical path through the DAG. The scheduling DAG
1256/// only provides the critical path for single block loops. To handle loops that
1257/// span blocks, we could use the vreg path latencies provided by
1258/// MachineTraceMetrics instead. However, MachineTraceMetrics is not currently
1259/// available for use in the scheduler.
1260///
1261/// The cyclic path estimation identifies a def-use pair that crosses the back
Andrew Trickef80f502013-08-30 02:02:12 +00001262/// edge and considers the depth and height of the nodes. For example, consider
Andrew Trick483f4192013-08-29 18:04:49 +00001263/// the following instruction sequence where each instruction has unit latency
1264/// and defines an epomymous virtual register:
1265///
1266/// a->b(a,c)->c(b)->d(c)->exit
1267///
1268/// The cyclic critical path is a two cycles: b->c->b
1269/// The acyclic critical path is four cycles: a->b->c->d->exit
1270/// LiveOutHeight = height(c) = len(c->d->exit) = 2
1271/// LiveOutDepth = depth(c) + 1 = len(a->b->c) + 1 = 3
1272/// LiveInHeight = height(b) + 1 = len(b->c->d->exit) + 1 = 4
1273/// LiveInDepth = depth(b) = len(a->b) = 1
1274///
1275/// LiveOutDepth - LiveInDepth = 3 - 1 = 2
1276/// LiveInHeight - LiveOutHeight = 4 - 2 = 2
1277/// CyclicCriticalPath = min(2, 2) = 2
Andrew Trickd7f890e2013-12-28 21:56:47 +00001278///
1279/// This could be relevant to PostRA scheduling, but is currently implemented
1280/// assuming LiveIntervals.
1281unsigned ScheduleDAGMILive::computeCyclicCriticalPath() {
Andrew Trick483f4192013-08-29 18:04:49 +00001282 // This only applies to single block loop.
1283 if (!BB->isSuccessor(BB))
1284 return 0;
1285
1286 unsigned MaxCyclicLatency = 0;
1287 // Visit each live out vreg def to find def/use pairs that cross iterations.
Matthias Braun5d458612016-01-20 00:23:26 +00001288 for (const RegisterMaskPair &P : RPTracker.getPressure().LiveOutRegs) {
1289 unsigned Reg = P.RegUnit;
Andrew Trick483f4192013-08-29 18:04:49 +00001290 if (!TRI->isVirtualRegister(Reg))
1291 continue;
1292 const LiveInterval &LI = LIS->getInterval(Reg);
1293 const VNInfo *DefVNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
1294 if (!DefVNI)
1295 continue;
1296
1297 MachineInstr *DefMI = LIS->getInstructionFromIndex(DefVNI->def);
1298 const SUnit *DefSU = getSUnit(DefMI);
1299 if (!DefSU)
1300 continue;
1301
1302 unsigned LiveOutHeight = DefSU->getHeight();
1303 unsigned LiveOutDepth = DefSU->getDepth() + DefSU->Latency;
1304 // Visit all local users of the vreg def.
Matthias Braunb0c437b2015-10-29 03:57:17 +00001305 for (const VReg2SUnit &V2SU
1306 : make_range(VRegUses.find(Reg), VRegUses.end())) {
1307 SUnit *SU = V2SU.SU;
1308 if (SU == &ExitSU)
Andrew Trick483f4192013-08-29 18:04:49 +00001309 continue;
1310
1311 // Only consider uses of the phi.
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001312 LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(*SU->getInstr()));
Andrew Trick483f4192013-08-29 18:04:49 +00001313 if (!LRQ.valueIn()->isPHIDef())
1314 continue;
1315
1316 // Assume that a path spanning two iterations is a cycle, which could
1317 // overestimate in strange cases. This allows cyclic latency to be
1318 // estimated as the minimum slack of the vreg's depth or height.
1319 unsigned CyclicLatency = 0;
Matthias Braunb0c437b2015-10-29 03:57:17 +00001320 if (LiveOutDepth > SU->getDepth())
1321 CyclicLatency = LiveOutDepth - SU->getDepth();
Andrew Trick483f4192013-08-29 18:04:49 +00001322
Matthias Braunb0c437b2015-10-29 03:57:17 +00001323 unsigned LiveInHeight = SU->getHeight() + DefSU->Latency;
Andrew Trick483f4192013-08-29 18:04:49 +00001324 if (LiveInHeight > LiveOutHeight) {
1325 if (LiveInHeight - LiveOutHeight < CyclicLatency)
1326 CyclicLatency = LiveInHeight - LiveOutHeight;
Matthias Braunb550b762016-04-21 01:54:13 +00001327 } else
Andrew Trick483f4192013-08-29 18:04:49 +00001328 CyclicLatency = 0;
1329
1330 DEBUG(dbgs() << "Cyclic Path: SU(" << DefSU->NodeNum << ") -> SU("
Matthias Braunb0c437b2015-10-29 03:57:17 +00001331 << SU->NodeNum << ") = " << CyclicLatency << "c\n");
Andrew Trick483f4192013-08-29 18:04:49 +00001332 if (CyclicLatency > MaxCyclicLatency)
1333 MaxCyclicLatency = CyclicLatency;
1334 }
1335 }
1336 DEBUG(dbgs() << "Cyclic Critical Path: " << MaxCyclicLatency << "c\n");
1337 return MaxCyclicLatency;
1338}
1339
Krzysztof Parzyszek7ea9a522016-04-28 19:17:44 +00001340/// Release ExitSU predecessors and setup scheduler queues. Re-position
1341/// the Top RP tracker in case the region beginning has changed.
1342void ScheduleDAGMILive::initQueues(ArrayRef<SUnit*> TopRoots,
1343 ArrayRef<SUnit*> BotRoots) {
1344 ScheduleDAGMI::initQueues(TopRoots, BotRoots);
1345 if (ShouldTrackPressure) {
1346 assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
1347 TopRPTracker.setPos(CurrentTop);
1348 }
1349}
1350
Andrew Trick7a8e1002012-09-11 00:39:15 +00001351/// Move an instruction and update register pressure.
Andrew Trickd7f890e2013-12-28 21:56:47 +00001352void ScheduleDAGMILive::scheduleMI(SUnit *SU, bool IsTopNode) {
Andrew Trick7a8e1002012-09-11 00:39:15 +00001353 // Move the instruction to its new location in the instruction stream.
1354 MachineInstr *MI = SU->getInstr();
Andrew Trick02a80da2012-03-08 01:41:12 +00001355
Andrew Trick7a8e1002012-09-11 00:39:15 +00001356 if (IsTopNode) {
1357 assert(SU->isTopReady() && "node still has unscheduled dependencies");
1358 if (&*CurrentTop == MI)
1359 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
Andrew Trick8823dec2012-03-14 04:00:41 +00001360 else {
Andrew Trick7a8e1002012-09-11 00:39:15 +00001361 moveInstruction(MI, CurrentTop);
1362 TopRPTracker.setPos(MI);
Andrew Trick8823dec2012-03-14 04:00:41 +00001363 }
Andrew Trickc3ea0052012-04-24 18:04:37 +00001364
Andrew Trickb6e74712013-09-04 20:59:59 +00001365 if (ShouldTrackPressure) {
1366 // Update top scheduled pressure.
Matthias Braund4f64092016-01-20 00:23:32 +00001367 RegisterOperands RegOpers;
1368 RegOpers.collect(*MI, *TRI, MRI, ShouldTrackLaneMasks, false);
1369 if (ShouldTrackLaneMasks) {
1370 // Adjust liveness and add missing dead+read-undef flags.
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001371 SlotIndex SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot();
Matthias Braund4f64092016-01-20 00:23:32 +00001372 RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx, MI);
1373 } else {
1374 // Adjust for missing dead-def flags.
1375 RegOpers.detectDeadDefs(*MI, *LIS);
1376 }
1377
1378 TopRPTracker.advance(RegOpers);
Andrew Trickb6e74712013-09-04 20:59:59 +00001379 assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
Matthias Braun9198c672015-11-06 20:59:02 +00001380 DEBUG(
1381 dbgs() << "Top Pressure:\n";
1382 dumpRegSetPressure(TopRPTracker.getRegSetPressureAtPos(), TRI);
1383 );
1384
Andrew Trickb248b4a2013-09-06 17:32:47 +00001385 updateScheduledPressure(SU, TopRPTracker.getPressure().MaxSetPressure);
Andrew Trickb6e74712013-09-04 20:59:59 +00001386 }
Matthias Braunb550b762016-04-21 01:54:13 +00001387 } else {
Andrew Trick7a8e1002012-09-11 00:39:15 +00001388 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
1389 MachineBasicBlock::iterator priorII =
1390 priorNonDebug(CurrentBottom, CurrentTop);
1391 if (&*priorII == MI)
1392 CurrentBottom = priorII;
1393 else {
1394 if (&*CurrentTop == MI) {
1395 CurrentTop = nextIfDebug(++CurrentTop, priorII);
1396 TopRPTracker.setPos(CurrentTop);
1397 }
1398 moveInstruction(MI, CurrentBottom);
1399 CurrentBottom = MI;
1400 }
Andrew Trickb6e74712013-09-04 20:59:59 +00001401 if (ShouldTrackPressure) {
Matthias Braund4f64092016-01-20 00:23:32 +00001402 RegisterOperands RegOpers;
1403 RegOpers.collect(*MI, *TRI, MRI, ShouldTrackLaneMasks, false);
1404 if (ShouldTrackLaneMasks) {
1405 // Adjust liveness and add missing dead+read-undef flags.
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001406 SlotIndex SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot();
Matthias Braund4f64092016-01-20 00:23:32 +00001407 RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx, MI);
1408 } else {
1409 // Adjust for missing dead-def flags.
1410 RegOpers.detectDeadDefs(*MI, *LIS);
1411 }
1412
1413 BotRPTracker.recedeSkipDebugValues();
Matthias Braun5d458612016-01-20 00:23:26 +00001414 SmallVector<RegisterMaskPair, 8> LiveUses;
Matthias Braund4f64092016-01-20 00:23:32 +00001415 BotRPTracker.recede(RegOpers, &LiveUses);
Andrew Trickb6e74712013-09-04 20:59:59 +00001416 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
Matthias Braun9198c672015-11-06 20:59:02 +00001417 DEBUG(
1418 dbgs() << "Bottom Pressure:\n";
1419 dumpRegSetPressure(BotRPTracker.getRegSetPressureAtPos(), TRI);
1420 );
1421
Andrew Trickb248b4a2013-09-06 17:32:47 +00001422 updateScheduledPressure(SU, BotRPTracker.getPressure().MaxSetPressure);
Andrew Trickb6e74712013-09-04 20:59:59 +00001423 updatePressureDiffs(LiveUses);
Andrew Trickb6e74712013-09-04 20:59:59 +00001424 }
Andrew Trick7a8e1002012-09-11 00:39:15 +00001425 }
1426}
1427
Andrew Trick263280242012-11-12 19:52:20 +00001428//===----------------------------------------------------------------------===//
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001429// BaseMemOpClusterMutation - DAG post-processing to cluster loads or stores.
Andrew Trick263280242012-11-12 19:52:20 +00001430//===----------------------------------------------------------------------===//
1431
Andrew Tricka7714a02012-11-12 19:40:10 +00001432namespace {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001433
Andrew Tricka7714a02012-11-12 19:40:10 +00001434/// \brief Post-process the DAG to create cluster edges between neighboring
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001435/// loads or between neighboring stores.
1436class BaseMemOpClusterMutation : public ScheduleDAGMutation {
1437 struct MemOpInfo {
Andrew Tricka7714a02012-11-12 19:40:10 +00001438 SUnit *SU;
1439 unsigned BaseReg;
Chad Rosierc27a18f2016-03-09 16:00:35 +00001440 int64_t Offset;
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001441
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001442 MemOpInfo(SUnit *su, unsigned reg, int64_t ofs)
1443 : SU(su), BaseReg(reg), Offset(ofs) {}
Benjamin Kramerb0f74b22014-03-07 21:35:39 +00001444
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001445 bool operator<(const MemOpInfo&RHS) const {
Mandeep Singh Grange82678a2016-10-18 00:11:19 +00001446 return std::tie(BaseReg, Offset, SU->NodeNum) <
1447 std::tie(RHS.BaseReg, RHS.Offset, RHS.SU->NodeNum);
Benjamin Kramerb0f74b22014-03-07 21:35:39 +00001448 }
Andrew Tricka7714a02012-11-12 19:40:10 +00001449 };
Andrew Tricka7714a02012-11-12 19:40:10 +00001450
1451 const TargetInstrInfo *TII;
1452 const TargetRegisterInfo *TRI;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001453 bool IsLoad;
1454
Andrew Tricka7714a02012-11-12 19:40:10 +00001455public:
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001456 BaseMemOpClusterMutation(const TargetInstrInfo *tii,
1457 const TargetRegisterInfo *tri, bool IsLoad)
1458 : TII(tii), TRI(tri), IsLoad(IsLoad) {}
Andrew Tricka7714a02012-11-12 19:40:10 +00001459
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001460 void apply(ScheduleDAGInstrs *DAGInstrs) override;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001461
Andrew Tricka7714a02012-11-12 19:40:10 +00001462protected:
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001463 void clusterNeighboringMemOps(ArrayRef<SUnit *> MemOps, ScheduleDAGMI *DAG);
1464};
1465
1466class StoreClusterMutation : public BaseMemOpClusterMutation {
1467public:
1468 StoreClusterMutation(const TargetInstrInfo *tii,
1469 const TargetRegisterInfo *tri)
1470 : BaseMemOpClusterMutation(tii, tri, false) {}
1471};
1472
1473class LoadClusterMutation : public BaseMemOpClusterMutation {
1474public:
1475 LoadClusterMutation(const TargetInstrInfo *tii, const TargetRegisterInfo *tri)
1476 : BaseMemOpClusterMutation(tii, tri, true) {}
Andrew Tricka7714a02012-11-12 19:40:10 +00001477};
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001478
1479} // end anonymous namespace
Andrew Tricka7714a02012-11-12 19:40:10 +00001480
Tom Stellard68726a52016-08-19 19:59:18 +00001481namespace llvm {
1482
1483std::unique_ptr<ScheduleDAGMutation>
1484createLoadClusterDAGMutation(const TargetInstrInfo *TII,
1485 const TargetRegisterInfo *TRI) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001486 return EnableMemOpCluster ? llvm::make_unique<LoadClusterMutation>(TII, TRI)
Matthias Braun115efcd2016-11-28 20:11:54 +00001487 : nullptr;
Tom Stellard68726a52016-08-19 19:59:18 +00001488}
1489
1490std::unique_ptr<ScheduleDAGMutation>
1491createStoreClusterDAGMutation(const TargetInstrInfo *TII,
1492 const TargetRegisterInfo *TRI) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001493 return EnableMemOpCluster ? llvm::make_unique<StoreClusterMutation>(TII, TRI)
Matthias Braun115efcd2016-11-28 20:11:54 +00001494 : nullptr;
Tom Stellard68726a52016-08-19 19:59:18 +00001495}
1496
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001497} // end namespace llvm
Tom Stellard68726a52016-08-19 19:59:18 +00001498
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001499void BaseMemOpClusterMutation::clusterNeighboringMemOps(
1500 ArrayRef<SUnit *> MemOps, ScheduleDAGMI *DAG) {
1501 SmallVector<MemOpInfo, 32> MemOpRecords;
Javed Absare3a0cc22017-06-21 09:10:10 +00001502 for (SUnit *SU : MemOps) {
Andrew Tricka7714a02012-11-12 19:40:10 +00001503 unsigned BaseReg;
Chad Rosierc27a18f2016-03-09 16:00:35 +00001504 int64_t Offset;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001505 if (TII->getMemOpBaseRegImmOfs(*SU->getInstr(), BaseReg, Offset, TRI))
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001506 MemOpRecords.push_back(MemOpInfo(SU, BaseReg, Offset));
Andrew Tricka7714a02012-11-12 19:40:10 +00001507 }
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001508 if (MemOpRecords.size() < 2)
Andrew Tricka7714a02012-11-12 19:40:10 +00001509 return;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001510
1511 std::sort(MemOpRecords.begin(), MemOpRecords.end());
Andrew Tricka7714a02012-11-12 19:40:10 +00001512 unsigned ClusterLength = 1;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001513 for (unsigned Idx = 0, End = MemOpRecords.size(); Idx < (End - 1); ++Idx) {
1514 if (MemOpRecords[Idx].BaseReg != MemOpRecords[Idx+1].BaseReg) {
Andrew Tricka7714a02012-11-12 19:40:10 +00001515 ClusterLength = 1;
1516 continue;
1517 }
1518
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001519 SUnit *SUa = MemOpRecords[Idx].SU;
1520 SUnit *SUb = MemOpRecords[Idx+1].SU;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001521 if (TII->shouldClusterMemOps(*SUa->getInstr(), *SUb->getInstr(),
1522 ClusterLength) &&
1523 DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001524 DEBUG(dbgs() << "Cluster ld/st SU(" << SUa->NodeNum << ") - SU("
Andrew Tricka7714a02012-11-12 19:40:10 +00001525 << SUb->NodeNum << ")\n");
1526 // Copy successor edges from SUa to SUb. Interleaving computation
1527 // dependent on SUa can prevent load combining due to register reuse.
1528 // Predecessor edges do not need to be copied from SUb to SUa since nearby
1529 // loads should have effectively the same inputs.
Javed Absare3a0cc22017-06-21 09:10:10 +00001530 for (const SDep &Succ : SUa->Succs) {
1531 if (Succ.getSUnit() == SUb)
Andrew Tricka7714a02012-11-12 19:40:10 +00001532 continue;
Javed Absare3a0cc22017-06-21 09:10:10 +00001533 DEBUG(dbgs() << " Copy Succ SU(" << Succ.getSUnit()->NodeNum << ")\n");
1534 DAG->addEdge(Succ.getSUnit(), SDep(SUb, SDep::Artificial));
Andrew Tricka7714a02012-11-12 19:40:10 +00001535 }
1536 ++ClusterLength;
Matthias Braunb550b762016-04-21 01:54:13 +00001537 } else
Andrew Tricka7714a02012-11-12 19:40:10 +00001538 ClusterLength = 1;
1539 }
1540}
1541
1542/// \brief Callback from DAG postProcessing to create cluster edges for loads.
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001543void BaseMemOpClusterMutation::apply(ScheduleDAGInstrs *DAGInstrs) {
1544
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001545 ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs);
1546
Andrew Tricka7714a02012-11-12 19:40:10 +00001547 // Map DAG NodeNum to store chain ID.
1548 DenseMap<unsigned, unsigned> StoreChainIDs;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001549 // Map each store chain to a set of dependent MemOps.
Andrew Tricka7714a02012-11-12 19:40:10 +00001550 SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
Javed Absare3a0cc22017-06-21 09:10:10 +00001551 for (SUnit &SU : DAG->SUnits) {
1552 if ((IsLoad && !SU.getInstr()->mayLoad()) ||
1553 (!IsLoad && !SU.getInstr()->mayStore()))
Andrew Tricka7714a02012-11-12 19:40:10 +00001554 continue;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001555
Andrew Tricka7714a02012-11-12 19:40:10 +00001556 unsigned ChainPredID = DAG->SUnits.size();
Javed Absare3a0cc22017-06-21 09:10:10 +00001557 for (const SDep &Pred : SU.Preds) {
1558 if (Pred.isCtrl()) {
1559 ChainPredID = Pred.getSUnit()->NodeNum;
Andrew Tricka7714a02012-11-12 19:40:10 +00001560 break;
1561 }
1562 }
1563 // Check if this chain-like pred has been seen
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001564 // before. ChainPredID==MaxNodeID at the top of the schedule.
Andrew Tricka7714a02012-11-12 19:40:10 +00001565 unsigned NumChains = StoreChainDependents.size();
1566 std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
1567 StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
1568 if (Result.second)
1569 StoreChainDependents.resize(NumChains + 1);
Javed Absare3a0cc22017-06-21 09:10:10 +00001570 StoreChainDependents[Result.first->second].push_back(&SU);
Andrew Tricka7714a02012-11-12 19:40:10 +00001571 }
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001572
Andrew Tricka7714a02012-11-12 19:40:10 +00001573 // Iterate over the store chains.
Javed Absare3a0cc22017-06-21 09:10:10 +00001574 for (auto &SCD : StoreChainDependents)
1575 clusterNeighboringMemOps(SCD, DAG);
Andrew Tricka7714a02012-11-12 19:40:10 +00001576}
1577
Andrew Trick02a80da2012-03-08 01:41:12 +00001578//===----------------------------------------------------------------------===//
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001579// CopyConstrain - DAG post-processing to encourage copy elimination.
1580//===----------------------------------------------------------------------===//
1581
1582namespace {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001583
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001584/// \brief Post-process the DAG to create weak edges from all uses of a copy to
1585/// the one use that defines the copy's source vreg, most likely an induction
1586/// variable increment.
1587class CopyConstrain : public ScheduleDAGMutation {
1588 // Transient state.
1589 SlotIndex RegionBeginIdx;
Andrew Trick2e875172013-04-24 23:19:56 +00001590 // RegionEndIdx is the slot index of the last non-debug instruction in the
1591 // scheduling region. So we may have RegionBeginIdx == RegionEndIdx.
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001592 SlotIndex RegionEndIdx;
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001593
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001594public:
1595 CopyConstrain(const TargetInstrInfo *, const TargetRegisterInfo *) {}
1596
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001597 void apply(ScheduleDAGInstrs *DAGInstrs) override;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001598
1599protected:
Andrew Trickd7f890e2013-12-28 21:56:47 +00001600 void constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG);
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001601};
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001602
1603} // end anonymous namespace
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001604
Tom Stellard68726a52016-08-19 19:59:18 +00001605namespace llvm {
1606
1607std::unique_ptr<ScheduleDAGMutation>
1608createCopyConstrainDAGMutation(const TargetInstrInfo *TII,
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001609 const TargetRegisterInfo *TRI) {
1610 return llvm::make_unique<CopyConstrain>(TII, TRI);
Tom Stellard68726a52016-08-19 19:59:18 +00001611}
1612
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001613} // end namespace llvm
Tom Stellard68726a52016-08-19 19:59:18 +00001614
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001615/// constrainLocalCopy handles two possibilities:
1616/// 1) Local src:
1617/// I0: = dst
1618/// I1: src = ...
1619/// I2: = dst
1620/// I3: dst = src (copy)
1621/// (create pred->succ edges I0->I1, I2->I1)
1622///
1623/// 2) Local copy:
1624/// I0: dst = src (copy)
1625/// I1: = dst
1626/// I2: src = ...
1627/// I3: = dst
1628/// (create pred->succ edges I1->I2, I3->I2)
1629///
1630/// Although the MachineScheduler is currently constrained to single blocks,
1631/// this algorithm should handle extended blocks. An EBB is a set of
1632/// contiguously numbered blocks such that the previous block in the EBB is
1633/// always the single predecessor.
Andrew Trickd7f890e2013-12-28 21:56:47 +00001634void CopyConstrain::constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG) {
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001635 LiveIntervals *LIS = DAG->getLIS();
1636 MachineInstr *Copy = CopySU->getInstr();
1637
1638 // Check for pure vreg copies.
Matthias Braun7511abd2016-04-04 21:23:46 +00001639 const MachineOperand &SrcOp = Copy->getOperand(1);
1640 unsigned SrcReg = SrcOp.getReg();
1641 if (!TargetRegisterInfo::isVirtualRegister(SrcReg) || !SrcOp.readsReg())
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001642 return;
1643
Matthias Braun7511abd2016-04-04 21:23:46 +00001644 const MachineOperand &DstOp = Copy->getOperand(0);
1645 unsigned DstReg = DstOp.getReg();
1646 if (!TargetRegisterInfo::isVirtualRegister(DstReg) || DstOp.isDead())
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001647 return;
1648
1649 // Check if either the dest or source is local. If it's live across a back
1650 // edge, it's not local. Note that if both vregs are live across the back
1651 // edge, we cannot successfully contrain the copy without cyclic scheduling.
Michael Kuperstein54c61ed2015-01-19 07:30:47 +00001652 // If both the copy's source and dest are local live intervals, then we
1653 // should treat the dest as the global for the purpose of adding
1654 // constraints. This adds edges from source's other uses to the copy.
1655 unsigned LocalReg = SrcReg;
1656 unsigned GlobalReg = DstReg;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001657 LiveInterval *LocalLI = &LIS->getInterval(LocalReg);
1658 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx)) {
Michael Kuperstein54c61ed2015-01-19 07:30:47 +00001659 LocalReg = DstReg;
1660 GlobalReg = SrcReg;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001661 LocalLI = &LIS->getInterval(LocalReg);
1662 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx))
1663 return;
1664 }
1665 LiveInterval *GlobalLI = &LIS->getInterval(GlobalReg);
1666
1667 // Find the global segment after the start of the local LI.
1668 LiveInterval::iterator GlobalSegment = GlobalLI->find(LocalLI->beginIndex());
1669 // If GlobalLI does not overlap LocalLI->start, then a copy directly feeds a
1670 // local live range. We could create edges from other global uses to the local
1671 // start, but the coalescer should have already eliminated these cases, so
1672 // don't bother dealing with it.
1673 if (GlobalSegment == GlobalLI->end())
1674 return;
1675
1676 // If GlobalSegment is killed at the LocalLI->start, the call to find()
1677 // returned the next global segment. But if GlobalSegment overlaps with
1678 // LocalLI->start, then advance to the next segement. If a hole in GlobalLI
1679 // exists in LocalLI's vicinity, GlobalSegment will be the end of the hole.
1680 if (GlobalSegment->contains(LocalLI->beginIndex()))
1681 ++GlobalSegment;
1682
1683 if (GlobalSegment == GlobalLI->end())
1684 return;
1685
1686 // Check if GlobalLI contains a hole in the vicinity of LocalLI.
1687 if (GlobalSegment != GlobalLI->begin()) {
1688 // Two address defs have no hole.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001689 if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->end,
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001690 GlobalSegment->start)) {
1691 return;
1692 }
Andrew Trickd9761772013-07-30 19:59:08 +00001693 // If the prior global segment may be defined by the same two-address
1694 // instruction that also defines LocalLI, then can't make a hole here.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001695 if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->start,
Andrew Trickd9761772013-07-30 19:59:08 +00001696 LocalLI->beginIndex())) {
1697 return;
1698 }
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001699 // If GlobalLI has a prior segment, it must be live into the EBB. Otherwise
1700 // it would be a disconnected component in the live range.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001701 assert(std::prev(GlobalSegment)->start < LocalLI->beginIndex() &&
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001702 "Disconnected LRG within the scheduling region.");
1703 }
1704 MachineInstr *GlobalDef = LIS->getInstructionFromIndex(GlobalSegment->start);
1705 if (!GlobalDef)
1706 return;
1707
1708 SUnit *GlobalSU = DAG->getSUnit(GlobalDef);
1709 if (!GlobalSU)
1710 return;
1711
1712 // GlobalDef is the bottom of the GlobalLI hole. Open the hole by
1713 // constraining the uses of the last local def to precede GlobalDef.
1714 SmallVector<SUnit*,8> LocalUses;
1715 const VNInfo *LastLocalVN = LocalLI->getVNInfoBefore(LocalLI->endIndex());
1716 MachineInstr *LastLocalDef = LIS->getInstructionFromIndex(LastLocalVN->def);
1717 SUnit *LastLocalSU = DAG->getSUnit(LastLocalDef);
Javed Absare3a0cc22017-06-21 09:10:10 +00001718 for (const SDep &Succ : LastLocalSU->Succs) {
1719 if (Succ.getKind() != SDep::Data || Succ.getReg() != LocalReg)
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001720 continue;
Javed Absare3a0cc22017-06-21 09:10:10 +00001721 if (Succ.getSUnit() == GlobalSU)
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001722 continue;
Javed Absare3a0cc22017-06-21 09:10:10 +00001723 if (!DAG->canAddEdge(GlobalSU, Succ.getSUnit()))
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001724 return;
Javed Absare3a0cc22017-06-21 09:10:10 +00001725 LocalUses.push_back(Succ.getSUnit());
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001726 }
1727 // Open the top of the GlobalLI hole by constraining any earlier global uses
1728 // to precede the start of LocalLI.
1729 SmallVector<SUnit*,8> GlobalUses;
1730 MachineInstr *FirstLocalDef =
1731 LIS->getInstructionFromIndex(LocalLI->beginIndex());
1732 SUnit *FirstLocalSU = DAG->getSUnit(FirstLocalDef);
Javed Absare3a0cc22017-06-21 09:10:10 +00001733 for (const SDep &Pred : GlobalSU->Preds) {
1734 if (Pred.getKind() != SDep::Anti || Pred.getReg() != GlobalReg)
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001735 continue;
Javed Absare3a0cc22017-06-21 09:10:10 +00001736 if (Pred.getSUnit() == FirstLocalSU)
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001737 continue;
Javed Absare3a0cc22017-06-21 09:10:10 +00001738 if (!DAG->canAddEdge(FirstLocalSU, Pred.getSUnit()))
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001739 return;
Javed Absare3a0cc22017-06-21 09:10:10 +00001740 GlobalUses.push_back(Pred.getSUnit());
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001741 }
1742 DEBUG(dbgs() << "Constraining copy SU(" << CopySU->NodeNum << ")\n");
1743 // Add the weak edges.
1744 for (SmallVectorImpl<SUnit*>::const_iterator
1745 I = LocalUses.begin(), E = LocalUses.end(); I != E; ++I) {
1746 DEBUG(dbgs() << " Local use SU(" << (*I)->NodeNum << ") -> SU("
1747 << GlobalSU->NodeNum << ")\n");
1748 DAG->addEdge(GlobalSU, SDep(*I, SDep::Weak));
1749 }
1750 for (SmallVectorImpl<SUnit*>::const_iterator
1751 I = GlobalUses.begin(), E = GlobalUses.end(); I != E; ++I) {
1752 DEBUG(dbgs() << " Global use SU(" << (*I)->NodeNum << ") -> SU("
1753 << FirstLocalSU->NodeNum << ")\n");
1754 DAG->addEdge(FirstLocalSU, SDep(*I, SDep::Weak));
1755 }
1756}
1757
1758/// \brief Callback from DAG postProcessing to create weak edges to encourage
1759/// copy elimination.
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001760void CopyConstrain::apply(ScheduleDAGInstrs *DAGInstrs) {
1761 ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs);
Andrew Trickd7f890e2013-12-28 21:56:47 +00001762 assert(DAG->hasVRegLiveness() && "Expect VRegs with LiveIntervals");
1763
Andrew Trick2e875172013-04-24 23:19:56 +00001764 MachineBasicBlock::iterator FirstPos = nextIfDebug(DAG->begin(), DAG->end());
1765 if (FirstPos == DAG->end())
1766 return;
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001767 RegionBeginIdx = DAG->getLIS()->getInstructionIndex(*FirstPos);
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001768 RegionEndIdx = DAG->getLIS()->getInstructionIndex(
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001769 *priorNonDebug(DAG->end(), DAG->begin()));
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001770
Javed Absare3a0cc22017-06-21 09:10:10 +00001771 for (SUnit &SU : DAG->SUnits) {
1772 if (!SU.getInstr()->isCopy())
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001773 continue;
1774
Javed Absare3a0cc22017-06-21 09:10:10 +00001775 constrainLocalCopy(&SU, static_cast<ScheduleDAGMILive*>(DAG));
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001776 }
1777}
1778
1779//===----------------------------------------------------------------------===//
Andrew Trickfc127d12013-12-07 05:59:44 +00001780// MachineSchedStrategy helpers used by GenericScheduler, GenericPostScheduler
1781// and possibly other custom schedulers.
Andrew Trickd14d7c22013-12-28 21:56:57 +00001782//===----------------------------------------------------------------------===//
Andrew Tricke1c034f2012-01-17 06:55:03 +00001783
Andrew Trick5a22df42013-12-05 17:56:02 +00001784static const unsigned InvalidCycle = ~0U;
1785
Andrew Trickfc127d12013-12-07 05:59:44 +00001786SchedBoundary::~SchedBoundary() { delete HazardRec; }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001787
Andrew Trickfc127d12013-12-07 05:59:44 +00001788void SchedBoundary::reset() {
1789 // A new HazardRec is created for each DAG and owned by SchedBoundary.
1790 // Destroying and reconstructing it is very expensive though. So keep
1791 // invalid, placeholder HazardRecs.
1792 if (HazardRec && HazardRec->isEnabled()) {
1793 delete HazardRec;
Craig Topperc0196b12014-04-14 00:51:57 +00001794 HazardRec = nullptr;
Andrew Trickfc127d12013-12-07 05:59:44 +00001795 }
1796 Available.clear();
1797 Pending.clear();
1798 CheckPending = false;
Andrew Trickfc127d12013-12-07 05:59:44 +00001799 CurrCycle = 0;
1800 CurrMOps = 0;
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001801 MinReadyCycle = std::numeric_limits<unsigned>::max();
Andrew Trickfc127d12013-12-07 05:59:44 +00001802 ExpectedLatency = 0;
1803 DependentLatency = 0;
1804 RetiredMOps = 0;
1805 MaxExecutedResCount = 0;
1806 ZoneCritResIdx = 0;
1807 IsResourceLimited = false;
1808 ReservedCycles.clear();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001809#ifndef NDEBUG
Andrew Trickd14d7c22013-12-28 21:56:57 +00001810 // Track the maximum number of stall cycles that could arise either from the
1811 // latency of a DAG edge or the number of cycles that a processor resource is
1812 // reserved (SchedBoundary::ReservedCycles).
Andrew Trick7f1ebbe2014-06-07 01:48:43 +00001813 MaxObservedStall = 0;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001814#endif
Andrew Trickfc127d12013-12-07 05:59:44 +00001815 // Reserve a zero-count for invalid CritResIdx.
1816 ExecutedResCounts.resize(1);
1817 assert(!ExecutedResCounts[0] && "nonzero count for bad resource");
1818}
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001819
Andrew Trickfc127d12013-12-07 05:59:44 +00001820void SchedRemainder::
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001821init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
1822 reset();
1823 if (!SchedModel->hasInstrSchedModel())
1824 return;
1825 RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
Javed Absare3a0cc22017-06-21 09:10:10 +00001826 for (SUnit &SU : DAG->SUnits) {
1827 const MCSchedClassDesc *SC = DAG->getSchedClass(&SU);
1828 RemIssueCount += SchedModel->getNumMicroOps(SU.getInstr(), SC)
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001829 * SchedModel->getMicroOpFactor();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001830 for (TargetSchedModel::ProcResIter
1831 PI = SchedModel->getWriteProcResBegin(SC),
1832 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1833 unsigned PIdx = PI->ProcResourceIdx;
1834 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1835 RemainingCounts[PIdx] += (Factor * PI->Cycles);
1836 }
1837 }
1838}
1839
Andrew Trickfc127d12013-12-07 05:59:44 +00001840void SchedBoundary::
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001841init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
1842 reset();
1843 DAG = dag;
1844 SchedModel = smodel;
1845 Rem = rem;
Andrew Trick5a22df42013-12-05 17:56:02 +00001846 if (SchedModel->hasInstrSchedModel()) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001847 ExecutedResCounts.resize(SchedModel->getNumProcResourceKinds());
Andrew Trick5a22df42013-12-05 17:56:02 +00001848 ReservedCycles.resize(SchedModel->getNumProcResourceKinds(), InvalidCycle);
1849 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001850}
1851
Andrew Trick880e5732013-12-05 17:55:58 +00001852/// Compute the stall cycles based on this SUnit's ready time. Heuristics treat
1853/// these "soft stalls" differently than the hard stall cycles based on CPU
1854/// resources and computed by checkHazard(). A fully in-order model
1855/// (MicroOpBufferSize==0) will not make use of this since instructions are not
1856/// available for scheduling until they are ready. However, a weaker in-order
1857/// model may use this for heuristics. For example, if a processor has in-order
1858/// behavior when reading certain resources, this may come into play.
Andrew Trickfc127d12013-12-07 05:59:44 +00001859unsigned SchedBoundary::getLatencyStallCycles(SUnit *SU) {
Andrew Trick880e5732013-12-05 17:55:58 +00001860 if (!SU->isUnbuffered)
1861 return 0;
1862
1863 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
1864 if (ReadyCycle > CurrCycle)
1865 return ReadyCycle - CurrCycle;
1866 return 0;
1867}
1868
Andrew Trick5a22df42013-12-05 17:56:02 +00001869/// Compute the next cycle at which the given processor resource can be
1870/// scheduled.
Andrew Trickfc127d12013-12-07 05:59:44 +00001871unsigned SchedBoundary::
Andrew Trick5a22df42013-12-05 17:56:02 +00001872getNextResourceCycle(unsigned PIdx, unsigned Cycles) {
1873 unsigned NextUnreserved = ReservedCycles[PIdx];
1874 // If this resource has never been used, always return cycle zero.
1875 if (NextUnreserved == InvalidCycle)
1876 return 0;
1877 // For bottom-up scheduling add the cycles needed for the current operation.
1878 if (!isTop())
1879 NextUnreserved += Cycles;
1880 return NextUnreserved;
1881}
1882
Andrew Trick8c9e6722012-06-29 03:23:24 +00001883/// Does this SU have a hazard within the current instruction group.
1884///
1885/// The scheduler supports two modes of hazard recognition. The first is the
1886/// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
1887/// supports highly complicated in-order reservation tables
1888/// (ScoreboardHazardRecognizer) and arbitraty target-specific logic.
1889///
1890/// The second is a streamlined mechanism that checks for hazards based on
1891/// simple counters that the scheduler itself maintains. It explicitly checks
1892/// for instruction dispatch limitations, including the number of micro-ops that
1893/// can dispatch per cycle.
1894///
1895/// TODO: Also check whether the SU must start a new group.
Andrew Trickfc127d12013-12-07 05:59:44 +00001896bool SchedBoundary::checkHazard(SUnit *SU) {
Andrew Trickd14d7c22013-12-28 21:56:57 +00001897 if (HazardRec->isEnabled()
1898 && HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard) {
1899 return true;
1900 }
Javed Absar3d594372017-03-27 20:46:37 +00001901
Andrew Trickdd79f0f2012-10-10 05:43:09 +00001902 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
Andrew Tricke2ff5752013-06-15 04:49:49 +00001903 if ((CurrMOps > 0) && (CurrMOps + uops > SchedModel->getIssueWidth())) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001904 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") uops="
1905 << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
Andrew Trick8c9e6722012-06-29 03:23:24 +00001906 return true;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001907 }
Javed Absar3d594372017-03-27 20:46:37 +00001908
1909 if (CurrMOps > 0 &&
1910 ((isTop() && SchedModel->mustBeginGroup(SU->getInstr())) ||
1911 (!isTop() && SchedModel->mustEndGroup(SU->getInstr())))) {
1912 DEBUG(dbgs() << " hazard: SU(" << SU->NodeNum << ") must "
1913 << (isTop()? "begin" : "end") << " group\n");
1914 return true;
1915 }
1916
Andrew Trick5a22df42013-12-05 17:56:02 +00001917 if (SchedModel->hasInstrSchedModel() && SU->hasReservedResource) {
1918 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1919 for (TargetSchedModel::ProcResIter
1920 PI = SchedModel->getWriteProcResBegin(SC),
1921 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
Andrew Trick56327222014-06-27 04:57:05 +00001922 unsigned NRCycle = getNextResourceCycle(PI->ProcResourceIdx, PI->Cycles);
1923 if (NRCycle > CurrCycle) {
Andrew Trick040c0da2014-06-27 05:09:36 +00001924#ifndef NDEBUG
Chad Rosieraba845e2014-07-02 16:46:08 +00001925 MaxObservedStall = std::max(PI->Cycles, MaxObservedStall);
Andrew Trick040c0da2014-06-27 05:09:36 +00001926#endif
Andrew Trick56327222014-06-27 04:57:05 +00001927 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") "
1928 << SchedModel->getResourceName(PI->ProcResourceIdx)
1929 << "=" << NRCycle << "c\n");
Andrew Trick5a22df42013-12-05 17:56:02 +00001930 return true;
Andrew Trick56327222014-06-27 04:57:05 +00001931 }
Andrew Trick5a22df42013-12-05 17:56:02 +00001932 }
1933 }
Andrew Trick8c9e6722012-06-29 03:23:24 +00001934 return false;
1935}
1936
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001937// Find the unscheduled node in ReadySUs with the highest latency.
Andrew Trickfc127d12013-12-07 05:59:44 +00001938unsigned SchedBoundary::
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001939findMaxLatency(ArrayRef<SUnit*> ReadySUs) {
Craig Topperc0196b12014-04-14 00:51:57 +00001940 SUnit *LateSU = nullptr;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001941 unsigned RemLatency = 0;
Javed Absare3a0cc22017-06-21 09:10:10 +00001942 for (SUnit *SU : ReadySUs) {
1943 unsigned L = getUnscheduledLatency(SU);
Andrew Trickf5b8ef22013-06-15 04:49:44 +00001944 if (L > RemLatency) {
Andrew Trickd6d5ad32012-12-18 20:52:56 +00001945 RemLatency = L;
Javed Absare3a0cc22017-06-21 09:10:10 +00001946 LateSU = SU;
Andrew Trickf5b8ef22013-06-15 04:49:44 +00001947 }
Andrew Trickd6d5ad32012-12-18 20:52:56 +00001948 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001949 if (LateSU) {
1950 DEBUG(dbgs() << Available.getName() << " RemLatency SU("
1951 << LateSU->NodeNum << ") " << RemLatency << "c\n");
Andrew Trickd6d5ad32012-12-18 20:52:56 +00001952 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001953 return RemLatency;
1954}
Andrew Trickf5b8ef22013-06-15 04:49:44 +00001955
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001956// Count resources in this zone and the remaining unscheduled
1957// instruction. Return the max count, scaled. Set OtherCritIdx to the critical
1958// resource index, or zero if the zone is issue limited.
Andrew Trickfc127d12013-12-07 05:59:44 +00001959unsigned SchedBoundary::
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001960getOtherResourceCount(unsigned &OtherCritIdx) {
Alexey Samsonov64c391d2013-07-19 08:55:18 +00001961 OtherCritIdx = 0;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001962 if (!SchedModel->hasInstrSchedModel())
1963 return 0;
1964
1965 unsigned OtherCritCount = Rem->RemIssueCount
1966 + (RetiredMOps * SchedModel->getMicroOpFactor());
1967 DEBUG(dbgs() << " " << Available.getName() << " + Remain MOps: "
1968 << OtherCritCount / SchedModel->getMicroOpFactor() << '\n');
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001969 for (unsigned PIdx = 1, PEnd = SchedModel->getNumProcResourceKinds();
1970 PIdx != PEnd; ++PIdx) {
1971 unsigned OtherCount = getResourceCount(PIdx) + Rem->RemainingCounts[PIdx];
1972 if (OtherCount > OtherCritCount) {
1973 OtherCritCount = OtherCount;
1974 OtherCritIdx = PIdx;
1975 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001976 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001977 if (OtherCritIdx) {
1978 DEBUG(dbgs() << " " << Available.getName() << " + Remain CritRes: "
1979 << OtherCritCount / SchedModel->getResourceFactor(OtherCritIdx)
Andrew Trickfc127d12013-12-07 05:59:44 +00001980 << " " << SchedModel->getResourceName(OtherCritIdx) << "\n");
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001981 }
1982 return OtherCritCount;
1983}
1984
Andrew Trickfc127d12013-12-07 05:59:44 +00001985void SchedBoundary::releaseNode(SUnit *SU, unsigned ReadyCycle) {
Andrew Trick7f1ebbe2014-06-07 01:48:43 +00001986 assert(SU->getInstr() && "Scheduled SUnit must have instr");
1987
1988#ifndef NDEBUG
Andrew Trick491e34a2014-06-12 22:36:28 +00001989 // ReadyCycle was been bumped up to the CurrCycle when this node was
1990 // scheduled, but CurrCycle may have been eagerly advanced immediately after
1991 // scheduling, so may now be greater than ReadyCycle.
1992 if (ReadyCycle > CurrCycle)
1993 MaxObservedStall = std::max(ReadyCycle - CurrCycle, MaxObservedStall);
Andrew Trick7f1ebbe2014-06-07 01:48:43 +00001994#endif
1995
Andrew Trick61f1a272012-05-24 22:11:09 +00001996 if (ReadyCycle < MinReadyCycle)
1997 MinReadyCycle = ReadyCycle;
1998
1999 // Check for interlocks first. For the purpose of other heuristics, an
2000 // instruction that cannot issue appears as if it's not in the ReadyQueue.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002001 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
Matthias Braun6493bc22016-04-22 19:09:17 +00002002 if ((!IsBuffered && ReadyCycle > CurrCycle) || checkHazard(SU) ||
2003 Available.size() >= ReadyListLimit)
Andrew Trick61f1a272012-05-24 22:11:09 +00002004 Pending.push(SU);
2005 else
2006 Available.push(SU);
2007}
2008
2009/// Move the boundary of scheduled code by one cycle.
Andrew Trickfc127d12013-12-07 05:59:44 +00002010void SchedBoundary::bumpCycle(unsigned NextCycle) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002011 if (SchedModel->getMicroOpBufferSize() == 0) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00002012 assert(MinReadyCycle < std::numeric_limits<unsigned>::max() &&
2013 "MinReadyCycle uninitialized");
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002014 if (MinReadyCycle > NextCycle)
2015 NextCycle = MinReadyCycle;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002016 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002017 // Update the current micro-ops, which will issue in the next cycle.
2018 unsigned DecMOps = SchedModel->getIssueWidth() * (NextCycle - CurrCycle);
2019 CurrMOps = (CurrMOps <= DecMOps) ? 0 : CurrMOps - DecMOps;
2020
2021 // Decrement DependentLatency based on the next cycle.
Andrew Trickf5b8ef22013-06-15 04:49:44 +00002022 if ((NextCycle - CurrCycle) > DependentLatency)
2023 DependentLatency = 0;
2024 else
2025 DependentLatency -= (NextCycle - CurrCycle);
Andrew Trick61f1a272012-05-24 22:11:09 +00002026
2027 if (!HazardRec->isEnabled()) {
Andrew Trick45446062012-06-05 21:11:27 +00002028 // Bypass HazardRec virtual calls.
Andrew Trick61f1a272012-05-24 22:11:09 +00002029 CurrCycle = NextCycle;
Matthias Braunb550b762016-04-21 01:54:13 +00002030 } else {
Andrew Trick45446062012-06-05 21:11:27 +00002031 // Bypass getHazardType calls in case of long latency.
Andrew Trick61f1a272012-05-24 22:11:09 +00002032 for (; CurrCycle != NextCycle; ++CurrCycle) {
2033 if (isTop())
2034 HazardRec->AdvanceCycle();
2035 else
2036 HazardRec->RecedeCycle();
2037 }
2038 }
2039 CheckPending = true;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002040 unsigned LFactor = SchedModel->getLatencyFactor();
2041 IsResourceLimited =
2042 (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
2043 > (int)LFactor;
Andrew Trick61f1a272012-05-24 22:11:09 +00002044
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002045 DEBUG(dbgs() << "Cycle: " << CurrCycle << ' ' << Available.getName() << '\n');
2046}
2047
Andrew Trickfc127d12013-12-07 05:59:44 +00002048void SchedBoundary::incExecutedResources(unsigned PIdx, unsigned Count) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002049 ExecutedResCounts[PIdx] += Count;
2050 if (ExecutedResCounts[PIdx] > MaxExecutedResCount)
2051 MaxExecutedResCount = ExecutedResCounts[PIdx];
Andrew Trick61f1a272012-05-24 22:11:09 +00002052}
2053
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002054/// Add the given processor resource to this scheduled zone.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002055///
2056/// \param Cycles indicates the number of consecutive (non-pipelined) cycles
2057/// during which this resource is consumed.
2058///
2059/// \return the next cycle at which the instruction may execute without
2060/// oversubscribing resources.
Andrew Trickfc127d12013-12-07 05:59:44 +00002061unsigned SchedBoundary::
Andrew Trick5a22df42013-12-05 17:56:02 +00002062countResource(unsigned PIdx, unsigned Cycles, unsigned NextCycle) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002063 unsigned Factor = SchedModel->getResourceFactor(PIdx);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002064 unsigned Count = Factor * Cycles;
Andrew Trickfc127d12013-12-07 05:59:44 +00002065 DEBUG(dbgs() << " " << SchedModel->getResourceName(PIdx)
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002066 << " +" << Cycles << "x" << Factor << "u\n");
2067
2068 // Update Executed resources counts.
2069 incExecutedResources(PIdx, Count);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002070 assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
2071 Rem->RemainingCounts[PIdx] -= Count;
2072
Andrew Trickb13ef172013-07-19 00:20:07 +00002073 // Check if this resource exceeds the current critical resource. If so, it
2074 // becomes the critical resource.
2075 if (ZoneCritResIdx != PIdx && (getResourceCount(PIdx) > getCriticalCount())) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002076 ZoneCritResIdx = PIdx;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002077 DEBUG(dbgs() << " *** Critical resource "
Andrew Trickfc127d12013-12-07 05:59:44 +00002078 << SchedModel->getResourceName(PIdx) << ": "
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002079 << getResourceCount(PIdx) / SchedModel->getLatencyFactor() << "c\n");
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002080 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002081 // For reserved resources, record the highest cycle using the resource.
2082 unsigned NextAvailable = getNextResourceCycle(PIdx, Cycles);
2083 if (NextAvailable > CurrCycle) {
2084 DEBUG(dbgs() << " Resource conflict: "
2085 << SchedModel->getProcResource(PIdx)->Name << " reserved until @"
2086 << NextAvailable << "\n");
2087 }
2088 return NextAvailable;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002089}
2090
Andrew Trick45446062012-06-05 21:11:27 +00002091/// Move the boundary of scheduled code by one SUnit.
Andrew Trickfc127d12013-12-07 05:59:44 +00002092void SchedBoundary::bumpNode(SUnit *SU) {
Andrew Trick45446062012-06-05 21:11:27 +00002093 // Update the reservation table.
2094 if (HazardRec->isEnabled()) {
2095 if (!isTop() && SU->isCall) {
2096 // Calls are scheduled with their preceding instructions. For bottom-up
2097 // scheduling, clear the pipeline state before emitting.
2098 HazardRec->Reset();
2099 }
2100 HazardRec->EmitInstruction(SU);
2101 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002102 // checkHazard should prevent scheduling multiple instructions per cycle that
2103 // exceed the issue width.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002104 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
2105 unsigned IncMOps = SchedModel->getNumMicroOps(SU->getInstr());
Daniel Jasper0d92abd2013-12-06 08:58:22 +00002106 assert(
2107 (CurrMOps == 0 || (CurrMOps + IncMOps) <= SchedModel->getIssueWidth()) &&
Andrew Trickf7760a22013-12-06 17:19:20 +00002108 "Cannot schedule this instruction's MicroOps in the current cycle.");
Andrew Trick5a22df42013-12-05 17:56:02 +00002109
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002110 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
2111 DEBUG(dbgs() << " Ready @" << ReadyCycle << "c\n");
2112
Andrew Trick5a22df42013-12-05 17:56:02 +00002113 unsigned NextCycle = CurrCycle;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002114 switch (SchedModel->getMicroOpBufferSize()) {
2115 case 0:
2116 assert(ReadyCycle <= CurrCycle && "Broken PendingQueue");
2117 break;
2118 case 1:
2119 if (ReadyCycle > NextCycle) {
2120 NextCycle = ReadyCycle;
2121 DEBUG(dbgs() << " *** Stall until: " << ReadyCycle << "\n");
2122 }
2123 break;
2124 default:
2125 // We don't currently model the OOO reorder buffer, so consider all
Andrew Trick880e5732013-12-05 17:55:58 +00002126 // scheduled MOps to be "retired". We do loosely model in-order resource
2127 // latency. If this instruction uses an in-order resource, account for any
2128 // likely stall cycles.
2129 if (SU->isUnbuffered && ReadyCycle > NextCycle)
2130 NextCycle = ReadyCycle;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002131 break;
2132 }
2133 RetiredMOps += IncMOps;
2134
2135 // Update resource counts and critical resource.
2136 if (SchedModel->hasInstrSchedModel()) {
2137 unsigned DecRemIssue = IncMOps * SchedModel->getMicroOpFactor();
2138 assert(Rem->RemIssueCount >= DecRemIssue && "MOps double counted");
2139 Rem->RemIssueCount -= DecRemIssue;
2140 if (ZoneCritResIdx) {
2141 // Scale scheduled micro-ops for comparing with the critical resource.
2142 unsigned ScaledMOps =
2143 RetiredMOps * SchedModel->getMicroOpFactor();
2144
2145 // If scaled micro-ops are now more than the previous critical resource by
2146 // a full cycle, then micro-ops issue becomes critical.
2147 if ((int)(ScaledMOps - getResourceCount(ZoneCritResIdx))
2148 >= (int)SchedModel->getLatencyFactor()) {
2149 ZoneCritResIdx = 0;
2150 DEBUG(dbgs() << " *** Critical resource NumMicroOps: "
2151 << ScaledMOps / SchedModel->getLatencyFactor() << "c\n");
2152 }
2153 }
2154 for (TargetSchedModel::ProcResIter
2155 PI = SchedModel->getWriteProcResBegin(SC),
2156 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2157 unsigned RCycle =
Andrew Trick5a22df42013-12-05 17:56:02 +00002158 countResource(PI->ProcResourceIdx, PI->Cycles, NextCycle);
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002159 if (RCycle > NextCycle)
2160 NextCycle = RCycle;
2161 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002162 if (SU->hasReservedResource) {
2163 // For reserved resources, record the highest cycle using the resource.
2164 // For top-down scheduling, this is the cycle in which we schedule this
2165 // instruction plus the number of cycles the operations reserves the
2166 // resource. For bottom-up is it simply the instruction's cycle.
2167 for (TargetSchedModel::ProcResIter
2168 PI = SchedModel->getWriteProcResBegin(SC),
2169 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2170 unsigned PIdx = PI->ProcResourceIdx;
Andrew Trickd14d7c22013-12-28 21:56:57 +00002171 if (SchedModel->getProcResource(PIdx)->BufferSize == 0) {
Chad Rosieraba845e2014-07-02 16:46:08 +00002172 if (isTop()) {
2173 ReservedCycles[PIdx] =
2174 std::max(getNextResourceCycle(PIdx, 0), NextCycle + PI->Cycles);
2175 }
2176 else
2177 ReservedCycles[PIdx] = NextCycle;
Andrew Trickd14d7c22013-12-28 21:56:57 +00002178 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002179 }
2180 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002181 }
2182 // Update ExpectedLatency and DependentLatency.
2183 unsigned &TopLatency = isTop() ? ExpectedLatency : DependentLatency;
2184 unsigned &BotLatency = isTop() ? DependentLatency : ExpectedLatency;
2185 if (SU->getDepth() > TopLatency) {
2186 TopLatency = SU->getDepth();
2187 DEBUG(dbgs() << " " << Available.getName()
2188 << " TopLatency SU(" << SU->NodeNum << ") " << TopLatency << "c\n");
2189 }
2190 if (SU->getHeight() > BotLatency) {
2191 BotLatency = SU->getHeight();
2192 DEBUG(dbgs() << " " << Available.getName()
2193 << " BotLatency SU(" << SU->NodeNum << ") " << BotLatency << "c\n");
2194 }
2195 // If we stall for any reason, bump the cycle.
2196 if (NextCycle > CurrCycle) {
2197 bumpCycle(NextCycle);
Matthias Braunb550b762016-04-21 01:54:13 +00002198 } else {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002199 // After updating ZoneCritResIdx and ExpectedLatency, check if we're
Alp Tokercb402912014-01-24 17:20:08 +00002200 // resource limited. If a stall occurred, bumpCycle does this.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002201 unsigned LFactor = SchedModel->getLatencyFactor();
2202 IsResourceLimited =
2203 (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
2204 > (int)LFactor;
2205 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002206 // Update CurrMOps after calling bumpCycle to handle stalls, since bumpCycle
2207 // resets CurrMOps. Loop to handle instructions with more MOps than issue in
2208 // one cycle. Since we commonly reach the max MOps here, opportunistically
2209 // bump the cycle to avoid uselessly checking everything in the readyQ.
2210 CurrMOps += IncMOps;
Javed Absar3d594372017-03-27 20:46:37 +00002211
2212 // Bump the cycle count for issue group constraints.
2213 // This must be done after NextCycle has been adjust for all other stalls.
2214 // Calling bumpCycle(X) will reduce CurrMOps by one issue group and set
2215 // currCycle to X.
2216 if ((isTop() && SchedModel->mustEndGroup(SU->getInstr())) ||
2217 (!isTop() && SchedModel->mustBeginGroup(SU->getInstr()))) {
2218 DEBUG(dbgs() << " Bump cycle to "
2219 << (isTop() ? "end" : "begin") << " group\n");
2220 bumpCycle(++NextCycle);
2221 }
2222
Andrew Trick5a22df42013-12-05 17:56:02 +00002223 while (CurrMOps >= SchedModel->getIssueWidth()) {
Andrew Trick5a22df42013-12-05 17:56:02 +00002224 DEBUG(dbgs() << " *** Max MOps " << CurrMOps
2225 << " at cycle " << CurrCycle << '\n');
Andrew Trickd14d7c22013-12-28 21:56:57 +00002226 bumpCycle(++NextCycle);
Andrew Trick5a22df42013-12-05 17:56:02 +00002227 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002228 DEBUG(dumpScheduledState());
Andrew Trick45446062012-06-05 21:11:27 +00002229}
2230
Andrew Trick61f1a272012-05-24 22:11:09 +00002231/// Release pending ready nodes in to the available queue. This makes them
2232/// visible to heuristics.
Andrew Trickfc127d12013-12-07 05:59:44 +00002233void SchedBoundary::releasePending() {
Andrew Trick61f1a272012-05-24 22:11:09 +00002234 // If the available queue is empty, it is safe to reset MinReadyCycle.
2235 if (Available.empty())
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00002236 MinReadyCycle = std::numeric_limits<unsigned>::max();
Andrew Trick61f1a272012-05-24 22:11:09 +00002237
2238 // Check to see if any of the pending instructions are ready to issue. If
2239 // so, add them to the available queue.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002240 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
Andrew Trick61f1a272012-05-24 22:11:09 +00002241 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
2242 SUnit *SU = *(Pending.begin()+i);
Andrew Trick45446062012-06-05 21:11:27 +00002243 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
Andrew Trick61f1a272012-05-24 22:11:09 +00002244
2245 if (ReadyCycle < MinReadyCycle)
2246 MinReadyCycle = ReadyCycle;
2247
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002248 if (!IsBuffered && ReadyCycle > CurrCycle)
Andrew Trick61f1a272012-05-24 22:11:09 +00002249 continue;
2250
Andrew Trick8c9e6722012-06-29 03:23:24 +00002251 if (checkHazard(SU))
Andrew Trick61f1a272012-05-24 22:11:09 +00002252 continue;
2253
Matthias Braun6493bc22016-04-22 19:09:17 +00002254 if (Available.size() >= ReadyListLimit)
2255 break;
2256
Andrew Trick61f1a272012-05-24 22:11:09 +00002257 Available.push(SU);
2258 Pending.remove(Pending.begin()+i);
2259 --i; --e;
2260 }
2261 CheckPending = false;
2262}
2263
2264/// Remove SU from the ready set for this boundary.
Andrew Trickfc127d12013-12-07 05:59:44 +00002265void SchedBoundary::removeReady(SUnit *SU) {
Andrew Trick61f1a272012-05-24 22:11:09 +00002266 if (Available.isInQueue(SU))
2267 Available.remove(Available.find(SU));
2268 else {
2269 assert(Pending.isInQueue(SU) && "bad ready count");
2270 Pending.remove(Pending.find(SU));
2271 }
2272}
2273
2274/// If this queue only has one ready candidate, return it. As a side effect,
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002275/// defer any nodes that now hit a hazard, and advance the cycle until at least
2276/// one node is ready. If multiple instructions are ready, return NULL.
Andrew Trickfc127d12013-12-07 05:59:44 +00002277SUnit *SchedBoundary::pickOnlyChoice() {
Andrew Trick61f1a272012-05-24 22:11:09 +00002278 if (CheckPending)
2279 releasePending();
2280
Andrew Tricke2ff5752013-06-15 04:49:49 +00002281 if (CurrMOps > 0) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002282 // Defer any ready instrs that now have a hazard.
2283 for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
2284 if (checkHazard(*I)) {
2285 Pending.push(*I);
2286 I = Available.remove(I);
2287 continue;
2288 }
2289 ++I;
2290 }
2291 }
Andrew Trick61f1a272012-05-24 22:11:09 +00002292 for (unsigned i = 0; Available.empty(); ++i) {
Chad Rosieraba845e2014-07-02 16:46:08 +00002293// FIXME: Re-enable assert once PR20057 is resolved.
2294// assert(i <= (HazardRec->getMaxLookAhead() + MaxObservedStall) &&
2295// "permanent hazard");
2296 (void)i;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002297 bumpCycle(CurrCycle + 1);
Andrew Trick61f1a272012-05-24 22:11:09 +00002298 releasePending();
2299 }
Matthias Braund29d31e2016-06-23 21:27:38 +00002300
2301 DEBUG(Pending.dump());
2302 DEBUG(Available.dump());
2303
Andrew Trick61f1a272012-05-24 22:11:09 +00002304 if (Available.size() == 1)
2305 return *Available.begin();
Craig Topperc0196b12014-04-14 00:51:57 +00002306 return nullptr;
Andrew Trick61f1a272012-05-24 22:11:09 +00002307}
2308
Matthias Braun8c209aa2017-01-28 02:02:38 +00002309#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002310// This is useful information to dump after bumpNode.
2311// Note that the Queue contents are more useful before pickNodeFromQueue.
Sam Clegg705f7982017-06-21 22:19:17 +00002312LLVM_DUMP_METHOD void SchedBoundary::dumpScheduledState() const {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002313 unsigned ResFactor;
2314 unsigned ResCount;
2315 if (ZoneCritResIdx) {
2316 ResFactor = SchedModel->getResourceFactor(ZoneCritResIdx);
2317 ResCount = getResourceCount(ZoneCritResIdx);
Matthias Braunb550b762016-04-21 01:54:13 +00002318 } else {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002319 ResFactor = SchedModel->getMicroOpFactor();
2320 ResCount = RetiredMOps * SchedModel->getMicroOpFactor();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002321 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002322 unsigned LFactor = SchedModel->getLatencyFactor();
2323 dbgs() << Available.getName() << " @" << CurrCycle << "c\n"
2324 << " Retired: " << RetiredMOps;
2325 dbgs() << "\n Executed: " << getExecutedCount() / LFactor << "c";
2326 dbgs() << "\n Critical: " << ResCount / LFactor << "c, "
Andrew Trickfc127d12013-12-07 05:59:44 +00002327 << ResCount / ResFactor << " "
2328 << SchedModel->getResourceName(ZoneCritResIdx)
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002329 << "\n ExpectedLatency: " << ExpectedLatency << "c\n"
2330 << (IsResourceLimited ? " - Resource" : " - Latency")
2331 << " limited.\n";
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002332}
Andrew Trick8e8415f2013-06-15 05:46:47 +00002333#endif
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002334
Andrew Trickfc127d12013-12-07 05:59:44 +00002335//===----------------------------------------------------------------------===//
Andrew Trickd14d7c22013-12-28 21:56:57 +00002336// GenericScheduler - Generic implementation of MachineSchedStrategy.
Andrew Trickfc127d12013-12-07 05:59:44 +00002337//===----------------------------------------------------------------------===//
2338
Andrew Trickd14d7c22013-12-28 21:56:57 +00002339void GenericSchedulerBase::SchedCandidate::
2340initResourceDelta(const ScheduleDAGMI *DAG,
2341 const TargetSchedModel *SchedModel) {
2342 if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
2343 return;
2344
2345 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
2346 for (TargetSchedModel::ProcResIter
2347 PI = SchedModel->getWriteProcResBegin(SC),
2348 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2349 if (PI->ProcResourceIdx == Policy.ReduceResIdx)
2350 ResDelta.CritResources += PI->Cycles;
2351 if (PI->ProcResourceIdx == Policy.DemandResIdx)
2352 ResDelta.DemandedResources += PI->Cycles;
2353 }
2354}
2355
2356/// Set the CandPolicy given a scheduling zone given the current resources and
2357/// latencies inside and outside the zone.
Matthias Braunb550b762016-04-21 01:54:13 +00002358void GenericSchedulerBase::setPolicy(CandPolicy &Policy, bool IsPostRA,
Andrew Trickd14d7c22013-12-28 21:56:57 +00002359 SchedBoundary &CurrZone,
2360 SchedBoundary *OtherZone) {
Eric Christopher572e03a2015-06-19 01:53:21 +00002361 // Apply preemptive heuristics based on the total latency and resources
Andrew Trickd14d7c22013-12-28 21:56:57 +00002362 // inside and outside this zone. Potential stalls should be considered before
2363 // following this policy.
2364
2365 // Compute remaining latency. We need this both to determine whether the
2366 // overall schedule has become latency-limited and whether the instructions
2367 // outside this zone are resource or latency limited.
2368 //
2369 // The "dependent" latency is updated incrementally during scheduling as the
2370 // max height/depth of scheduled nodes minus the cycles since it was
2371 // scheduled:
2372 // DLat = max (N.depth - (CurrCycle - N.ReadyCycle) for N in Zone
2373 //
2374 // The "independent" latency is the max ready queue depth:
2375 // ILat = max N.depth for N in Available|Pending
2376 //
2377 // RemainingLatency is the greater of independent and dependent latency.
2378 unsigned RemLatency = CurrZone.getDependentLatency();
2379 RemLatency = std::max(RemLatency,
2380 CurrZone.findMaxLatency(CurrZone.Available.elements()));
2381 RemLatency = std::max(RemLatency,
2382 CurrZone.findMaxLatency(CurrZone.Pending.elements()));
2383
2384 // Compute the critical resource outside the zone.
Andrew Trick7afe4812013-12-28 22:25:57 +00002385 unsigned OtherCritIdx = 0;
Andrew Trickd14d7c22013-12-28 21:56:57 +00002386 unsigned OtherCount =
2387 OtherZone ? OtherZone->getOtherResourceCount(OtherCritIdx) : 0;
2388
2389 bool OtherResLimited = false;
2390 if (SchedModel->hasInstrSchedModel()) {
2391 unsigned LFactor = SchedModel->getLatencyFactor();
2392 OtherResLimited = (int)(OtherCount - (RemLatency * LFactor)) > (int)LFactor;
2393 }
2394 // Schedule aggressively for latency in PostRA mode. We don't check for
2395 // acyclic latency during PostRA, and highly out-of-order processors will
2396 // skip PostRA scheduling.
2397 if (!OtherResLimited) {
2398 if (IsPostRA || (RemLatency + CurrZone.getCurrCycle() > Rem.CriticalPath)) {
2399 Policy.ReduceLatency |= true;
2400 DEBUG(dbgs() << " " << CurrZone.Available.getName()
2401 << " RemainingLatency " << RemLatency << " + "
2402 << CurrZone.getCurrCycle() << "c > CritPath "
2403 << Rem.CriticalPath << "\n");
2404 }
2405 }
2406 // If the same resource is limiting inside and outside the zone, do nothing.
2407 if (CurrZone.getZoneCritResIdx() == OtherCritIdx)
2408 return;
2409
2410 DEBUG(
2411 if (CurrZone.isResourceLimited()) {
2412 dbgs() << " " << CurrZone.Available.getName() << " ResourceLimited: "
2413 << SchedModel->getResourceName(CurrZone.getZoneCritResIdx())
2414 << "\n";
2415 }
2416 if (OtherResLimited)
2417 dbgs() << " RemainingLimit: "
2418 << SchedModel->getResourceName(OtherCritIdx) << "\n";
2419 if (!CurrZone.isResourceLimited() && !OtherResLimited)
2420 dbgs() << " Latency limited both directions.\n");
2421
2422 if (CurrZone.isResourceLimited() && !Policy.ReduceResIdx)
2423 Policy.ReduceResIdx = CurrZone.getZoneCritResIdx();
2424
2425 if (OtherResLimited)
2426 Policy.DemandResIdx = OtherCritIdx;
2427}
2428
2429#ifndef NDEBUG
2430const char *GenericSchedulerBase::getReasonStr(
2431 GenericSchedulerBase::CandReason Reason) {
2432 switch (Reason) {
2433 case NoCand: return "NOCAND ";
Matthias Braun49cb6e92016-05-27 22:14:26 +00002434 case Only1: return "ONLY1 ";
2435 case PhysRegCopy: return "PREG-COPY ";
Andrew Trickd14d7c22013-12-28 21:56:57 +00002436 case RegExcess: return "REG-EXCESS";
2437 case RegCritical: return "REG-CRIT ";
2438 case Stall: return "STALL ";
2439 case Cluster: return "CLUSTER ";
2440 case Weak: return "WEAK ";
2441 case RegMax: return "REG-MAX ";
2442 case ResourceReduce: return "RES-REDUCE";
2443 case ResourceDemand: return "RES-DEMAND";
2444 case TopDepthReduce: return "TOP-DEPTH ";
2445 case TopPathReduce: return "TOP-PATH ";
2446 case BotHeightReduce:return "BOT-HEIGHT";
2447 case BotPathReduce: return "BOT-PATH ";
2448 case NextDefUse: return "DEF-USE ";
2449 case NodeOrder: return "ORDER ";
2450 };
2451 llvm_unreachable("Unknown reason!");
2452}
2453
2454void GenericSchedulerBase::traceCandidate(const SchedCandidate &Cand) {
2455 PressureChange P;
2456 unsigned ResIdx = 0;
2457 unsigned Latency = 0;
2458 switch (Cand.Reason) {
2459 default:
2460 break;
2461 case RegExcess:
2462 P = Cand.RPDelta.Excess;
2463 break;
2464 case RegCritical:
2465 P = Cand.RPDelta.CriticalMax;
2466 break;
2467 case RegMax:
2468 P = Cand.RPDelta.CurrentMax;
2469 break;
2470 case ResourceReduce:
2471 ResIdx = Cand.Policy.ReduceResIdx;
2472 break;
2473 case ResourceDemand:
2474 ResIdx = Cand.Policy.DemandResIdx;
2475 break;
2476 case TopDepthReduce:
2477 Latency = Cand.SU->getDepth();
2478 break;
2479 case TopPathReduce:
2480 Latency = Cand.SU->getHeight();
2481 break;
2482 case BotHeightReduce:
2483 Latency = Cand.SU->getHeight();
2484 break;
2485 case BotPathReduce:
2486 Latency = Cand.SU->getDepth();
2487 break;
2488 }
James Y Knighte72b0db2015-09-18 18:52:20 +00002489 dbgs() << " Cand SU(" << Cand.SU->NodeNum << ") " << getReasonStr(Cand.Reason);
Andrew Trickd14d7c22013-12-28 21:56:57 +00002490 if (P.isValid())
2491 dbgs() << " " << TRI->getRegPressureSetName(P.getPSet())
2492 << ":" << P.getUnitInc() << " ";
2493 else
2494 dbgs() << " ";
2495 if (ResIdx)
2496 dbgs() << " " << SchedModel->getProcResource(ResIdx)->Name << " ";
2497 else
2498 dbgs() << " ";
2499 if (Latency)
2500 dbgs() << " " << Latency << " cycles ";
2501 else
2502 dbgs() << " ";
2503 dbgs() << '\n';
2504}
2505#endif
2506
2507/// Return true if this heuristic determines order.
2508static bool tryLess(int TryVal, int CandVal,
2509 GenericSchedulerBase::SchedCandidate &TryCand,
2510 GenericSchedulerBase::SchedCandidate &Cand,
2511 GenericSchedulerBase::CandReason Reason) {
2512 if (TryVal < CandVal) {
2513 TryCand.Reason = Reason;
2514 return true;
2515 }
2516 if (TryVal > CandVal) {
2517 if (Cand.Reason > Reason)
2518 Cand.Reason = Reason;
2519 return true;
2520 }
Andrew Trickd14d7c22013-12-28 21:56:57 +00002521 return false;
2522}
2523
2524static bool tryGreater(int TryVal, int CandVal,
2525 GenericSchedulerBase::SchedCandidate &TryCand,
2526 GenericSchedulerBase::SchedCandidate &Cand,
2527 GenericSchedulerBase::CandReason Reason) {
2528 if (TryVal > CandVal) {
2529 TryCand.Reason = Reason;
2530 return true;
2531 }
2532 if (TryVal < CandVal) {
2533 if (Cand.Reason > Reason)
2534 Cand.Reason = Reason;
2535 return true;
2536 }
Andrew Trickd14d7c22013-12-28 21:56:57 +00002537 return false;
2538}
2539
2540static bool tryLatency(GenericSchedulerBase::SchedCandidate &TryCand,
2541 GenericSchedulerBase::SchedCandidate &Cand,
2542 SchedBoundary &Zone) {
2543 if (Zone.isTop()) {
2544 if (Cand.SU->getDepth() > Zone.getScheduledLatency()) {
2545 if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2546 TryCand, Cand, GenericSchedulerBase::TopDepthReduce))
2547 return true;
2548 }
2549 if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2550 TryCand, Cand, GenericSchedulerBase::TopPathReduce))
2551 return true;
Matthias Braunb550b762016-04-21 01:54:13 +00002552 } else {
Andrew Trickd14d7c22013-12-28 21:56:57 +00002553 if (Cand.SU->getHeight() > Zone.getScheduledLatency()) {
2554 if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2555 TryCand, Cand, GenericSchedulerBase::BotHeightReduce))
2556 return true;
2557 }
2558 if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2559 TryCand, Cand, GenericSchedulerBase::BotPathReduce))
2560 return true;
2561 }
2562 return false;
2563}
2564
Matthias Braun49cb6e92016-05-27 22:14:26 +00002565static void tracePick(GenericSchedulerBase::CandReason Reason, bool IsTop) {
2566 DEBUG(dbgs() << "Pick " << (IsTop ? "Top " : "Bot ")
2567 << GenericSchedulerBase::getReasonStr(Reason) << '\n');
2568}
2569
Matthias Braun6ad3d052016-06-25 00:23:00 +00002570static void tracePick(const GenericSchedulerBase::SchedCandidate &Cand) {
2571 tracePick(Cand.Reason, Cand.AtTop);
Andrew Trickd14d7c22013-12-28 21:56:57 +00002572}
2573
Andrew Trickfc127d12013-12-07 05:59:44 +00002574void GenericScheduler::initialize(ScheduleDAGMI *dag) {
Andrew Trickd7f890e2013-12-28 21:56:47 +00002575 assert(dag->hasVRegLiveness() &&
2576 "(PreRA)GenericScheduler needs vreg liveness");
2577 DAG = static_cast<ScheduleDAGMILive*>(dag);
Andrew Trickfc127d12013-12-07 05:59:44 +00002578 SchedModel = DAG->getSchedModel();
2579 TRI = DAG->TRI;
2580
2581 Rem.init(DAG, SchedModel);
2582 Top.init(DAG, SchedModel, &Rem);
2583 Bot.init(DAG, SchedModel, &Rem);
2584
2585 // Initialize resource counts.
2586
2587 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
2588 // are disabled, then these HazardRecs will be disabled.
2589 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
Andrew Trickfc127d12013-12-07 05:59:44 +00002590 if (!Top.HazardRec) {
2591 Top.HazardRec =
Eric Christopher99556d72014-10-14 06:56:25 +00002592 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
Eric Christopherd9134482014-08-04 21:25:23 +00002593 Itin, DAG);
Andrew Trickfc127d12013-12-07 05:59:44 +00002594 }
2595 if (!Bot.HazardRec) {
2596 Bot.HazardRec =
Eric Christopher99556d72014-10-14 06:56:25 +00002597 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
Eric Christopherd9134482014-08-04 21:25:23 +00002598 Itin, DAG);
Andrew Trickfc127d12013-12-07 05:59:44 +00002599 }
Matthias Brauncc676c42016-06-25 02:03:36 +00002600 TopCand.SU = nullptr;
2601 BotCand.SU = nullptr;
Andrew Trickfc127d12013-12-07 05:59:44 +00002602}
2603
2604/// Initialize the per-region scheduling policy.
2605void GenericScheduler::initPolicy(MachineBasicBlock::iterator Begin,
2606 MachineBasicBlock::iterator End,
2607 unsigned NumRegionInstrs) {
Eric Christopher99556d72014-10-14 06:56:25 +00002608 const MachineFunction &MF = *Begin->getParent()->getParent();
2609 const TargetLowering *TLI = MF.getSubtarget().getTargetLowering();
Andrew Trickfc127d12013-12-07 05:59:44 +00002610
2611 // Avoid setting up the register pressure tracker for small regions to save
2612 // compile time. As a rough heuristic, only track pressure when the number of
2613 // schedulable instructions exceeds half the integer register file.
Andrew Trick350ff2c2014-01-21 21:27:37 +00002614 RegionPolicy.ShouldTrackPressure = true;
Andrew Trick46753512014-01-22 03:38:55 +00002615 for (unsigned VT = MVT::i32; VT > (unsigned)MVT::i1; --VT) {
2616 MVT::SimpleValueType LegalIntVT = (MVT::SimpleValueType)VT;
2617 if (TLI->isTypeLegal(LegalIntVT)) {
Andrew Trick350ff2c2014-01-21 21:27:37 +00002618 unsigned NIntRegs = Context->RegClassInfo->getNumAllocatableRegs(
Andrew Trick46753512014-01-22 03:38:55 +00002619 TLI->getRegClassFor(LegalIntVT));
Andrew Trick350ff2c2014-01-21 21:27:37 +00002620 RegionPolicy.ShouldTrackPressure = NumRegionInstrs > (NIntRegs / 2);
2621 }
2622 }
Andrew Trickfc127d12013-12-07 05:59:44 +00002623
2624 // For generic targets, we default to bottom-up, because it's simpler and more
2625 // compile-time optimizations have been implemented in that direction.
2626 RegionPolicy.OnlyBottomUp = true;
2627
2628 // Allow the subtarget to override default policy.
Duncan P. N. Exon Smith63298722016-07-01 00:23:27 +00002629 MF.getSubtarget().overrideSchedPolicy(RegionPolicy, NumRegionInstrs);
Andrew Trickfc127d12013-12-07 05:59:44 +00002630
2631 // After subtarget overrides, apply command line options.
2632 if (!EnableRegPressure)
2633 RegionPolicy.ShouldTrackPressure = false;
2634
2635 // Check -misched-topdown/bottomup can force or unforce scheduling direction.
2636 // e.g. -misched-bottomup=false allows scheduling in both directions.
2637 assert((!ForceTopDown || !ForceBottomUp) &&
2638 "-misched-topdown incompatible with -misched-bottomup");
2639 if (ForceBottomUp.getNumOccurrences() > 0) {
2640 RegionPolicy.OnlyBottomUp = ForceBottomUp;
2641 if (RegionPolicy.OnlyBottomUp)
2642 RegionPolicy.OnlyTopDown = false;
2643 }
2644 if (ForceTopDown.getNumOccurrences() > 0) {
2645 RegionPolicy.OnlyTopDown = ForceTopDown;
2646 if (RegionPolicy.OnlyTopDown)
2647 RegionPolicy.OnlyBottomUp = false;
2648 }
2649}
2650
Sam Clegg705f7982017-06-21 22:19:17 +00002651void GenericScheduler::dumpPolicy() const {
Matthias Braun8c209aa2017-01-28 02:02:38 +00002652 // Cannot completely remove virtual function even in release mode.
2653#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
James Y Knighte72b0db2015-09-18 18:52:20 +00002654 dbgs() << "GenericScheduler RegionPolicy: "
2655 << " ShouldTrackPressure=" << RegionPolicy.ShouldTrackPressure
2656 << " OnlyTopDown=" << RegionPolicy.OnlyTopDown
2657 << " OnlyBottomUp=" << RegionPolicy.OnlyBottomUp
2658 << "\n";
Matthias Braun8c209aa2017-01-28 02:02:38 +00002659#endif
James Y Knighte72b0db2015-09-18 18:52:20 +00002660}
2661
Andrew Trickfc127d12013-12-07 05:59:44 +00002662/// Set IsAcyclicLatencyLimited if the acyclic path is longer than the cyclic
2663/// critical path by more cycles than it takes to drain the instruction buffer.
2664/// We estimate an upper bounds on in-flight instructions as:
2665///
2666/// CyclesPerIteration = max( CyclicPath, Loop-Resource-Height )
2667/// InFlightIterations = AcyclicPath / CyclesPerIteration
2668/// InFlightResources = InFlightIterations * LoopResources
2669///
2670/// TODO: Check execution resources in addition to IssueCount.
2671void GenericScheduler::checkAcyclicLatency() {
2672 if (Rem.CyclicCritPath == 0 || Rem.CyclicCritPath >= Rem.CriticalPath)
2673 return;
2674
2675 // Scaled number of cycles per loop iteration.
2676 unsigned IterCount =
2677 std::max(Rem.CyclicCritPath * SchedModel->getLatencyFactor(),
2678 Rem.RemIssueCount);
2679 // Scaled acyclic critical path.
2680 unsigned AcyclicCount = Rem.CriticalPath * SchedModel->getLatencyFactor();
2681 // InFlightCount = (AcyclicPath / IterCycles) * InstrPerLoop
2682 unsigned InFlightCount =
2683 (AcyclicCount * Rem.RemIssueCount + IterCount-1) / IterCount;
2684 unsigned BufferLimit =
2685 SchedModel->getMicroOpBufferSize() * SchedModel->getMicroOpFactor();
2686
2687 Rem.IsAcyclicLatencyLimited = InFlightCount > BufferLimit;
2688
2689 DEBUG(dbgs() << "IssueCycles="
2690 << Rem.RemIssueCount / SchedModel->getLatencyFactor() << "c "
2691 << "IterCycles=" << IterCount / SchedModel->getLatencyFactor()
2692 << "c NumIters=" << (AcyclicCount + IterCount-1) / IterCount
2693 << " InFlight=" << InFlightCount / SchedModel->getMicroOpFactor()
2694 << "m BufferLim=" << SchedModel->getMicroOpBufferSize() << "m\n";
2695 if (Rem.IsAcyclicLatencyLimited)
2696 dbgs() << " ACYCLIC LATENCY LIMIT\n");
2697}
2698
2699void GenericScheduler::registerRoots() {
2700 Rem.CriticalPath = DAG->ExitSU.getDepth();
2701
2702 // Some roots may not feed into ExitSU. Check all of them in case.
Javed Absare3a0cc22017-06-21 09:10:10 +00002703 for (const SUnit *SU : Bot.Available) {
2704 if (SU->getDepth() > Rem.CriticalPath)
2705 Rem.CriticalPath = SU->getDepth();
Andrew Trickfc127d12013-12-07 05:59:44 +00002706 }
Gerolf Hoflehnerb5220dc2014-08-07 21:49:44 +00002707 DEBUG(dbgs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << '\n');
2708 if (DumpCriticalPathLength) {
2709 errs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << " \n";
2710 }
Andrew Trickfc127d12013-12-07 05:59:44 +00002711
Matthias Braun99551052017-04-12 18:09:05 +00002712 if (EnableCyclicPath && SchedModel->getMicroOpBufferSize() > 0) {
Andrew Trickfc127d12013-12-07 05:59:44 +00002713 Rem.CyclicCritPath = DAG->computeCyclicCriticalPath();
2714 checkAcyclicLatency();
2715 }
2716}
2717
Andrew Trick1a831342013-08-30 03:49:48 +00002718static bool tryPressure(const PressureChange &TryP,
2719 const PressureChange &CandP,
Andrew Trickd14d7c22013-12-28 21:56:57 +00002720 GenericSchedulerBase::SchedCandidate &TryCand,
2721 GenericSchedulerBase::SchedCandidate &Cand,
Tom Stellard5ce53062015-12-16 18:31:01 +00002722 GenericSchedulerBase::CandReason Reason,
2723 const TargetRegisterInfo *TRI,
2724 const MachineFunction &MF) {
Andrew Trickb1a45b62013-08-30 04:27:29 +00002725 // If one candidate decreases and the other increases, go with it.
2726 // Invalid candidates have UnitInc==0.
Hal Finkel7a87f8a2014-10-10 17:06:20 +00002727 if (tryGreater(TryP.getUnitInc() < 0, CandP.getUnitInc() < 0, TryCand, Cand,
2728 Reason)) {
Andrew Trickb1a45b62013-08-30 04:27:29 +00002729 return true;
2730 }
Matthias Braun6ad3d052016-06-25 00:23:00 +00002731 // Do not compare the magnitude of pressure changes between top and bottom
2732 // boundary.
2733 if (Cand.AtTop != TryCand.AtTop)
2734 return false;
2735
2736 // If both candidates affect the same set in the same boundary, go with the
2737 // smallest increase.
2738 unsigned TryPSet = TryP.getPSetOrMax();
2739 unsigned CandPSet = CandP.getPSetOrMax();
2740 if (TryPSet == CandPSet) {
2741 return tryLess(TryP.getUnitInc(), CandP.getUnitInc(), TryCand, Cand,
2742 Reason);
2743 }
Tom Stellard5ce53062015-12-16 18:31:01 +00002744
2745 int TryRank = TryP.isValid() ? TRI->getRegPressureSetScore(MF, TryPSet) :
2746 std::numeric_limits<int>::max();
2747
2748 int CandRank = CandP.isValid() ? TRI->getRegPressureSetScore(MF, CandPSet) :
2749 std::numeric_limits<int>::max();
2750
Andrew Trick401b6952013-07-25 07:26:35 +00002751 // If the candidates are decreasing pressure, reverse priority.
Andrew Trick1a831342013-08-30 03:49:48 +00002752 if (TryP.getUnitInc() < 0)
Andrew Trick401b6952013-07-25 07:26:35 +00002753 std::swap(TryRank, CandRank);
2754 return tryGreater(TryRank, CandRank, TryCand, Cand, Reason);
2755}
2756
Andrew Tricka7714a02012-11-12 19:40:10 +00002757static unsigned getWeakLeft(const SUnit *SU, bool isTop) {
2758 return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
2759}
2760
Andrew Tricke833e1c2013-04-13 06:07:40 +00002761/// Minimize physical register live ranges. Regalloc wants them adjacent to
2762/// their physreg def/use.
2763///
2764/// FIXME: This is an unnecessary check on the critical path. Most are root/leaf
2765/// copies which can be prescheduled. The rest (e.g. x86 MUL) could be bundled
2766/// with the operation that produces or consumes the physreg. We'll do this when
2767/// regalloc has support for parallel copies.
2768static int biasPhysRegCopy(const SUnit *SU, bool isTop) {
2769 const MachineInstr *MI = SU->getInstr();
2770 if (!MI->isCopy())
2771 return 0;
2772
2773 unsigned ScheduledOper = isTop ? 1 : 0;
2774 unsigned UnscheduledOper = isTop ? 0 : 1;
2775 // If we have already scheduled the physreg produce/consumer, immediately
2776 // schedule the copy.
2777 if (TargetRegisterInfo::isPhysicalRegister(
2778 MI->getOperand(ScheduledOper).getReg()))
2779 return 1;
2780 // If the physreg is at the boundary, defer it. Otherwise schedule it
2781 // immediately to free the dependent. We can hoist the copy later.
2782 bool AtBoundary = isTop ? !SU->NumSuccsLeft : !SU->NumPredsLeft;
2783 if (TargetRegisterInfo::isPhysicalRegister(
2784 MI->getOperand(UnscheduledOper).getReg()))
2785 return AtBoundary ? -1 : 1;
2786 return 0;
2787}
2788
Matthias Braun4f573772016-04-22 19:10:15 +00002789void GenericScheduler::initCandidate(SchedCandidate &Cand, SUnit *SU,
2790 bool AtTop,
2791 const RegPressureTracker &RPTracker,
2792 RegPressureTracker &TempTracker) {
2793 Cand.SU = SU;
Matthias Braun6ad3d052016-06-25 00:23:00 +00002794 Cand.AtTop = AtTop;
Matthias Braun4f573772016-04-22 19:10:15 +00002795 if (DAG->isTrackingPressure()) {
2796 if (AtTop) {
2797 TempTracker.getMaxDownwardPressureDelta(
2798 Cand.SU->getInstr(),
2799 Cand.RPDelta,
2800 DAG->getRegionCriticalPSets(),
2801 DAG->getRegPressure().MaxSetPressure);
2802 } else {
2803 if (VerifyScheduling) {
2804 TempTracker.getMaxUpwardPressureDelta(
2805 Cand.SU->getInstr(),
2806 &DAG->getPressureDiff(Cand.SU),
2807 Cand.RPDelta,
2808 DAG->getRegionCriticalPSets(),
2809 DAG->getRegPressure().MaxSetPressure);
2810 } else {
2811 RPTracker.getUpwardPressureDelta(
2812 Cand.SU->getInstr(),
2813 DAG->getPressureDiff(Cand.SU),
2814 Cand.RPDelta,
2815 DAG->getRegionCriticalPSets(),
2816 DAG->getRegPressure().MaxSetPressure);
2817 }
2818 }
2819 }
2820 DEBUG(if (Cand.RPDelta.Excess.isValid())
2821 dbgs() << " Try SU(" << Cand.SU->NodeNum << ") "
2822 << TRI->getRegPressureSetName(Cand.RPDelta.Excess.getPSet())
2823 << ":" << Cand.RPDelta.Excess.getUnitInc() << "\n");
2824}
2825
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002826/// Apply a set of heursitics to a new candidate. Heuristics are currently
2827/// hierarchical. This may be more efficient than a graduated cost model because
2828/// we don't need to evaluate all aspects of the model for each node in the
2829/// queue. But it's really done to make the heuristics easier to debug and
2830/// statistically analyze.
2831///
2832/// \param Cand provides the policy and current best candidate.
2833/// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
Matthias Braun6ad3d052016-06-25 00:23:00 +00002834/// \param Zone describes the scheduled zone that we are extending, or nullptr
2835// if Cand is from a different zone than TryCand.
Andrew Trick665d3ec2013-09-19 23:10:59 +00002836void GenericScheduler::tryCandidate(SchedCandidate &Cand,
Andrew Trickbb1247b2013-12-05 17:55:47 +00002837 SchedCandidate &TryCand,
Matthias Braun6ad3d052016-06-25 00:23:00 +00002838 SchedBoundary *Zone) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002839 // Initialize the candidate if needed.
2840 if (!Cand.isValid()) {
2841 TryCand.Reason = NodeOrder;
2842 return;
2843 }
Andrew Tricke833e1c2013-04-13 06:07:40 +00002844
Matthias Braun6ad3d052016-06-25 00:23:00 +00002845 if (tryGreater(biasPhysRegCopy(TryCand.SU, TryCand.AtTop),
2846 biasPhysRegCopy(Cand.SU, Cand.AtTop),
Andrew Tricke833e1c2013-04-13 06:07:40 +00002847 TryCand, Cand, PhysRegCopy))
2848 return;
2849
Andrew Tricke02d5da2015-05-17 23:40:27 +00002850 // Avoid exceeding the target's limit.
Andrew Trick66c3dfb2013-09-04 21:00:11 +00002851 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.Excess,
2852 Cand.RPDelta.Excess,
Tom Stellard5ce53062015-12-16 18:31:01 +00002853 TryCand, Cand, RegExcess, TRI,
2854 DAG->MF))
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002855 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002856
2857 // Avoid increasing the max critical pressure in the scheduled region.
Andrew Trick66c3dfb2013-09-04 21:00:11 +00002858 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CriticalMax,
2859 Cand.RPDelta.CriticalMax,
Tom Stellard5ce53062015-12-16 18:31:01 +00002860 TryCand, Cand, RegCritical, TRI,
2861 DAG->MF))
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002862 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002863
Matthias Braun6ad3d052016-06-25 00:23:00 +00002864 // We only compare a subset of features when comparing nodes between
2865 // Top and Bottom boundary. Some properties are simply incomparable, in many
2866 // other instances we should only override the other boundary if something
2867 // is a clear good pick on one boundary. Skip heuristics that are more
2868 // "tie-breaking" in nature.
2869 bool SameBoundary = Zone != nullptr;
2870 if (SameBoundary) {
2871 // For loops that are acyclic path limited, aggressively schedule for
Jonas Paulssonbaeb4022016-11-04 08:31:14 +00002872 // latency. Within an single cycle, whenever CurrMOps > 0, allow normal
2873 // heuristics to take precedence.
Matthias Braun6ad3d052016-06-25 00:23:00 +00002874 if (Rem.IsAcyclicLatencyLimited && !Zone->getCurrMOps() &&
2875 tryLatency(TryCand, Cand, *Zone))
2876 return;
Andrew Trickddffae92013-09-06 17:32:36 +00002877
Matthias Braun6ad3d052016-06-25 00:23:00 +00002878 // Prioritize instructions that read unbuffered resources by stall cycles.
2879 if (tryLess(Zone->getLatencyStallCycles(TryCand.SU),
2880 Zone->getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
2881 return;
2882 }
Andrew Trick880e5732013-12-05 17:55:58 +00002883
Andrew Tricka7714a02012-11-12 19:40:10 +00002884 // Keep clustered nodes together to encourage downstream peephole
2885 // optimizations which may reduce resource requirements.
2886 //
2887 // This is a best effort to set things up for a post-RA pass. Optimizations
2888 // like generating loads of multiple registers should ideally be done within
2889 // the scheduler pass by combining the loads during DAG postprocessing.
Matthias Braun6ad3d052016-06-25 00:23:00 +00002890 const SUnit *CandNextClusterSU =
2891 Cand.AtTop ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
2892 const SUnit *TryCandNextClusterSU =
2893 TryCand.AtTop ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
2894 if (tryGreater(TryCand.SU == TryCandNextClusterSU,
2895 Cand.SU == CandNextClusterSU,
Andrew Tricka7714a02012-11-12 19:40:10 +00002896 TryCand, Cand, Cluster))
2897 return;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00002898
Matthias Braun6ad3d052016-06-25 00:23:00 +00002899 if (SameBoundary) {
2900 // Weak edges are for clustering and other constraints.
2901 if (tryLess(getWeakLeft(TryCand.SU, TryCand.AtTop),
2902 getWeakLeft(Cand.SU, Cand.AtTop),
2903 TryCand, Cand, Weak))
2904 return;
Andrew Tricka7714a02012-11-12 19:40:10 +00002905 }
Matthias Braun6ad3d052016-06-25 00:23:00 +00002906
Andrew Trick71f08a32013-06-17 21:45:13 +00002907 // Avoid increasing the max pressure of the entire region.
Andrew Trick66c3dfb2013-09-04 21:00:11 +00002908 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CurrentMax,
2909 Cand.RPDelta.CurrentMax,
Tom Stellard5ce53062015-12-16 18:31:01 +00002910 TryCand, Cand, RegMax, TRI,
2911 DAG->MF))
Andrew Trick71f08a32013-06-17 21:45:13 +00002912 return;
2913
Matthias Braun6ad3d052016-06-25 00:23:00 +00002914 if (SameBoundary) {
2915 // Avoid critical resource consumption and balance the schedule.
2916 TryCand.initResourceDelta(DAG, SchedModel);
2917 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
2918 TryCand, Cand, ResourceReduce))
2919 return;
2920 if (tryGreater(TryCand.ResDelta.DemandedResources,
2921 Cand.ResDelta.DemandedResources,
2922 TryCand, Cand, ResourceDemand))
2923 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002924
Matthias Braun6ad3d052016-06-25 00:23:00 +00002925 // Avoid serializing long latency dependence chains.
2926 // For acyclic path limited loops, latency was already checked above.
2927 if (!RegionPolicy.DisableLatencyHeuristic && TryCand.Policy.ReduceLatency &&
2928 !Rem.IsAcyclicLatencyLimited && tryLatency(TryCand, Cand, *Zone))
2929 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002930
Matthias Braun6ad3d052016-06-25 00:23:00 +00002931 // Fall through to original instruction order.
2932 if ((Zone->isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
2933 || (!Zone->isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
2934 TryCand.Reason = NodeOrder;
2935 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002936 }
2937}
Andrew Trick419eae22012-05-10 21:06:19 +00002938
Andrew Trickc573cd92013-09-06 17:32:44 +00002939/// Pick the best candidate from the queue.
Andrew Trick7ee9de52012-05-10 21:06:16 +00002940///
2941/// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
2942/// DAG building. To adjust for the current scheduling location we need to
2943/// maintain the number of vreg uses remaining to be top-scheduled.
Andrew Trick665d3ec2013-09-19 23:10:59 +00002944void GenericScheduler::pickNodeFromQueue(SchedBoundary &Zone,
Matthias Braun6ad3d052016-06-25 00:23:00 +00002945 const CandPolicy &ZonePolicy,
Andrew Trickbb1247b2013-12-05 17:55:47 +00002946 const RegPressureTracker &RPTracker,
2947 SchedCandidate &Cand) {
Andrew Trick7ee9de52012-05-10 21:06:16 +00002948 // getMaxPressureDelta temporarily modifies the tracker.
2949 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
2950
Matthias Braund29d31e2016-06-23 21:27:38 +00002951 ReadyQueue &Q = Zone.Available;
Javed Absare3a0cc22017-06-21 09:10:10 +00002952 for (SUnit *SU : Q) {
Andrew Trick7ee9de52012-05-10 21:06:16 +00002953
Matthias Braun6ad3d052016-06-25 00:23:00 +00002954 SchedCandidate TryCand(ZonePolicy);
Javed Absare3a0cc22017-06-21 09:10:10 +00002955 initCandidate(TryCand, SU, Zone.isTop(), RPTracker, TempTracker);
Matthias Braun6ad3d052016-06-25 00:23:00 +00002956 // Pass SchedBoundary only when comparing nodes from the same boundary.
2957 SchedBoundary *ZoneArg = Cand.AtTop == TryCand.AtTop ? &Zone : nullptr;
2958 tryCandidate(Cand, TryCand, ZoneArg);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002959 if (TryCand.Reason != NoCand) {
2960 // Initialize resource delta if needed in case future heuristics query it.
2961 if (TryCand.ResDelta == SchedResourceDelta())
2962 TryCand.initResourceDelta(DAG, SchedModel);
2963 Cand.setBest(TryCand);
Andrew Trick419d4912013-04-05 00:31:29 +00002964 DEBUG(traceCandidate(Cand));
Andrew Trick22025772012-05-17 18:35:10 +00002965 }
Andrew Trick7ee9de52012-05-10 21:06:16 +00002966 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002967}
2968
Andrew Trick22025772012-05-17 18:35:10 +00002969/// Pick the best candidate node from either the top or bottom queue.
Andrew Trick665d3ec2013-09-19 23:10:59 +00002970SUnit *GenericScheduler::pickNodeBidirectional(bool &IsTopNode) {
Andrew Trick22025772012-05-17 18:35:10 +00002971 // Schedule as far as possible in the direction of no choice. This is most
2972 // efficient, but also provides the best heuristics for CriticalPSets.
Andrew Trick61f1a272012-05-24 22:11:09 +00002973 if (SUnit *SU = Bot.pickOnlyChoice()) {
Andrew Trick22025772012-05-17 18:35:10 +00002974 IsTopNode = false;
Matthias Braun49cb6e92016-05-27 22:14:26 +00002975 tracePick(Only1, false);
Andrew Trick61f1a272012-05-24 22:11:09 +00002976 return SU;
Andrew Trick22025772012-05-17 18:35:10 +00002977 }
Andrew Trick61f1a272012-05-24 22:11:09 +00002978 if (SUnit *SU = Top.pickOnlyChoice()) {
Andrew Trick22025772012-05-17 18:35:10 +00002979 IsTopNode = true;
Matthias Braun49cb6e92016-05-27 22:14:26 +00002980 tracePick(Only1, true);
Andrew Trick61f1a272012-05-24 22:11:09 +00002981 return SU;
Andrew Trick22025772012-05-17 18:35:10 +00002982 }
Andrew Trickfc127d12013-12-07 05:59:44 +00002983 // Set the bottom-up policy based on the state of the current bottom zone and
2984 // the instructions outside the zone, including the top zone.
Matthias Braun6ad3d052016-06-25 00:23:00 +00002985 CandPolicy BotPolicy;
2986 setPolicy(BotPolicy, /*IsPostRA=*/false, Bot, &Top);
Andrew Trickfc127d12013-12-07 05:59:44 +00002987 // Set the top-down policy based on the state of the current top zone and
2988 // the instructions outside the zone, including the bottom zone.
Matthias Braun6ad3d052016-06-25 00:23:00 +00002989 CandPolicy TopPolicy;
2990 setPolicy(TopPolicy, /*IsPostRA=*/false, Top, &Bot);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002991
Matthias Brauncc676c42016-06-25 02:03:36 +00002992 // See if BotCand is still valid (because we previously scheduled from Top).
Matthias Braund29d31e2016-06-23 21:27:38 +00002993 DEBUG(dbgs() << "Picking from Bot:\n");
Matthias Brauncc676c42016-06-25 02:03:36 +00002994 if (!BotCand.isValid() || BotCand.SU->isScheduled ||
2995 BotCand.Policy != BotPolicy) {
2996 BotCand.reset(CandPolicy());
2997 pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), BotCand);
2998 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
2999 } else {
3000 DEBUG(traceCandidate(BotCand));
3001#ifndef NDEBUG
3002 if (VerifyScheduling) {
3003 SchedCandidate TCand;
3004 TCand.reset(CandPolicy());
3005 pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), TCand);
3006 assert(TCand.SU == BotCand.SU &&
3007 "Last pick result should correspond to re-picking right now");
3008 }
3009#endif
3010 }
Andrew Trick22025772012-05-17 18:35:10 +00003011
Andrew Trick22025772012-05-17 18:35:10 +00003012 // Check if the top Q has a better candidate.
Matthias Braund29d31e2016-06-23 21:27:38 +00003013 DEBUG(dbgs() << "Picking from Top:\n");
Matthias Brauncc676c42016-06-25 02:03:36 +00003014 if (!TopCand.isValid() || TopCand.SU->isScheduled ||
3015 TopCand.Policy != TopPolicy) {
3016 TopCand.reset(CandPolicy());
3017 pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TopCand);
3018 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
3019 } else {
3020 DEBUG(traceCandidate(TopCand));
3021#ifndef NDEBUG
3022 if (VerifyScheduling) {
3023 SchedCandidate TCand;
3024 TCand.reset(CandPolicy());
3025 pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TCand);
3026 assert(TCand.SU == TopCand.SU &&
3027 "Last pick result should correspond to re-picking right now");
3028 }
3029#endif
3030 }
3031
3032 // Pick best from BotCand and TopCand.
3033 assert(BotCand.isValid());
3034 assert(TopCand.isValid());
3035 SchedCandidate Cand = BotCand;
3036 TopCand.Reason = NoCand;
3037 tryCandidate(Cand, TopCand, nullptr);
3038 if (TopCand.Reason != NoCand) {
3039 Cand.setBest(TopCand);
3040 DEBUG(traceCandidate(Cand));
3041 }
Andrew Trick22025772012-05-17 18:35:10 +00003042
Matthias Braun6ad3d052016-06-25 00:23:00 +00003043 IsTopNode = Cand.AtTop;
3044 tracePick(Cand);
3045 return Cand.SU;
Andrew Trick22025772012-05-17 18:35:10 +00003046}
3047
3048/// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
Andrew Trick665d3ec2013-09-19 23:10:59 +00003049SUnit *GenericScheduler::pickNode(bool &IsTopNode) {
Andrew Trick7ee9de52012-05-10 21:06:16 +00003050 if (DAG->top() == DAG->bottom()) {
Andrew Trick61f1a272012-05-24 22:11:09 +00003051 assert(Top.Available.empty() && Top.Pending.empty() &&
3052 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
Craig Topperc0196b12014-04-14 00:51:57 +00003053 return nullptr;
Andrew Trick7ee9de52012-05-10 21:06:16 +00003054 }
Andrew Trick7ee9de52012-05-10 21:06:16 +00003055 SUnit *SU;
Andrew Trick984d98b2012-10-08 18:53:53 +00003056 do {
Andrew Trick75e411c2013-09-06 17:32:34 +00003057 if (RegionPolicy.OnlyTopDown) {
Andrew Trick984d98b2012-10-08 18:53:53 +00003058 SU = Top.pickOnlyChoice();
3059 if (!SU) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003060 CandPolicy NoPolicy;
Matthias Brauncc676c42016-06-25 02:03:36 +00003061 TopCand.reset(NoPolicy);
Matthias Braun6ad3d052016-06-25 00:23:00 +00003062 pickNodeFromQueue(Top, NoPolicy, DAG->getTopRPTracker(), TopCand);
Andrew Trick1ab16d92013-09-04 21:00:13 +00003063 assert(TopCand.Reason != NoCand && "failed to find a candidate");
Matthias Braun6ad3d052016-06-25 00:23:00 +00003064 tracePick(TopCand);
Andrew Trick984d98b2012-10-08 18:53:53 +00003065 SU = TopCand.SU;
3066 }
3067 IsTopNode = true;
Matthias Braunb550b762016-04-21 01:54:13 +00003068 } else if (RegionPolicy.OnlyBottomUp) {
Andrew Trick984d98b2012-10-08 18:53:53 +00003069 SU = Bot.pickOnlyChoice();
3070 if (!SU) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003071 CandPolicy NoPolicy;
Matthias Brauncc676c42016-06-25 02:03:36 +00003072 BotCand.reset(NoPolicy);
Matthias Braun6ad3d052016-06-25 00:23:00 +00003073 pickNodeFromQueue(Bot, NoPolicy, DAG->getBotRPTracker(), BotCand);
Andrew Trick1ab16d92013-09-04 21:00:13 +00003074 assert(BotCand.Reason != NoCand && "failed to find a candidate");
Matthias Braun6ad3d052016-06-25 00:23:00 +00003075 tracePick(BotCand);
Andrew Trick984d98b2012-10-08 18:53:53 +00003076 SU = BotCand.SU;
3077 }
3078 IsTopNode = false;
Matthias Braunb550b762016-04-21 01:54:13 +00003079 } else {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003080 SU = pickNodeBidirectional(IsTopNode);
Andrew Trick984d98b2012-10-08 18:53:53 +00003081 }
3082 } while (SU->isScheduled);
3083
Andrew Trick61f1a272012-05-24 22:11:09 +00003084 if (SU->isTopReady())
3085 Top.removeReady(SU);
3086 if (SU->isBottomReady())
3087 Bot.removeReady(SU);
Andrew Trick4e7f6a72012-05-25 02:02:39 +00003088
Andrew Trick1f0bb692013-04-13 06:07:49 +00003089 DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " << *SU->getInstr());
Andrew Trick7ee9de52012-05-10 21:06:16 +00003090 return SU;
3091}
3092
Andrew Trick665d3ec2013-09-19 23:10:59 +00003093void GenericScheduler::reschedulePhysRegCopies(SUnit *SU, bool isTop) {
Andrew Tricke833e1c2013-04-13 06:07:40 +00003094 MachineBasicBlock::iterator InsertPos = SU->getInstr();
3095 if (!isTop)
3096 ++InsertPos;
3097 SmallVectorImpl<SDep> &Deps = isTop ? SU->Preds : SU->Succs;
3098
3099 // Find already scheduled copies with a single physreg dependence and move
3100 // them just above the scheduled instruction.
Javed Absare3a0cc22017-06-21 09:10:10 +00003101 for (SDep &Dep : Deps) {
3102 if (Dep.getKind() != SDep::Data || !TRI->isPhysicalRegister(Dep.getReg()))
Andrew Tricke833e1c2013-04-13 06:07:40 +00003103 continue;
Javed Absare3a0cc22017-06-21 09:10:10 +00003104 SUnit *DepSU = Dep.getSUnit();
Andrew Tricke833e1c2013-04-13 06:07:40 +00003105 if (isTop ? DepSU->Succs.size() > 1 : DepSU->Preds.size() > 1)
3106 continue;
3107 MachineInstr *Copy = DepSU->getInstr();
3108 if (!Copy->isCopy())
3109 continue;
3110 DEBUG(dbgs() << " Rescheduling physreg copy ";
Javed Absare3a0cc22017-06-21 09:10:10 +00003111 Dep.getSUnit()->dump(DAG));
Andrew Tricke833e1c2013-04-13 06:07:40 +00003112 DAG->moveInstruction(Copy, InsertPos);
3113 }
3114}
3115
Andrew Trick61f1a272012-05-24 22:11:09 +00003116/// Update the scheduler's state after scheduling a node. This is the same node
Andrew Trickd14d7c22013-12-28 21:56:57 +00003117/// that was just returned by pickNode(). However, ScheduleDAGMILive needs to
3118/// update it's state based on the current cycle before MachineSchedStrategy
3119/// does.
Andrew Tricke833e1c2013-04-13 06:07:40 +00003120///
3121/// FIXME: Eventually, we may bundle physreg copies rather than rescheduling
3122/// them here. See comments in biasPhysRegCopy.
Andrew Trick665d3ec2013-09-19 23:10:59 +00003123void GenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
Andrew Trick45446062012-06-05 21:11:27 +00003124 if (IsTopNode) {
Andrew Trickfc127d12013-12-07 05:59:44 +00003125 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
Andrew Trickce27bb92012-06-29 03:23:22 +00003126 Top.bumpNode(SU);
Andrew Tricke833e1c2013-04-13 06:07:40 +00003127 if (SU->hasPhysRegUses)
3128 reschedulePhysRegCopies(SU, true);
Matthias Braunb550b762016-04-21 01:54:13 +00003129 } else {
Andrew Trickfc127d12013-12-07 05:59:44 +00003130 SU->BotReadyCycle = std::max(SU->BotReadyCycle, Bot.getCurrCycle());
Andrew Trickce27bb92012-06-29 03:23:22 +00003131 Bot.bumpNode(SU);
Andrew Tricke833e1c2013-04-13 06:07:40 +00003132 if (SU->hasPhysRegDefs)
3133 reschedulePhysRegCopies(SU, false);
Andrew Trick61f1a272012-05-24 22:11:09 +00003134 }
3135}
3136
Andrew Trick8823dec2012-03-14 04:00:41 +00003137/// Create the standard converging machine scheduler. This will be used as the
3138/// default scheduler if the target does not set a default.
Matthias Braun115efcd2016-11-28 20:11:54 +00003139ScheduleDAGMILive *llvm::createGenericSchedLive(MachineSchedContext *C) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003140 ScheduleDAGMILive *DAG =
3141 new ScheduleDAGMILive(C, llvm::make_unique<GenericScheduler>(C));
Andrew Tricka7714a02012-11-12 19:40:10 +00003142 // Register DAG post-processors.
Andrew Trick85a1d4c2013-04-24 15:54:43 +00003143 //
3144 // FIXME: extend the mutation API to allow earlier mutations to instantiate
3145 // data and pass it to later mutations. Have a single mutation that gathers
3146 // the interesting nodes in one pass.
Tom Stellard68726a52016-08-19 19:59:18 +00003147 DAG->addMutation(createCopyConstrainDAGMutation(DAG->TII, DAG->TRI));
Andrew Tricka7714a02012-11-12 19:40:10 +00003148 return DAG;
Andrew Tricke1c034f2012-01-17 06:55:03 +00003149}
Andrew Trickd14d7c22013-12-28 21:56:57 +00003150
Matthias Braun115efcd2016-11-28 20:11:54 +00003151static ScheduleDAGInstrs *createConveringSched(MachineSchedContext *C) {
3152 return createGenericSchedLive(C);
3153}
3154
Andrew Tricke1c034f2012-01-17 06:55:03 +00003155static MachineSchedRegistry
Andrew Trick665d3ec2013-09-19 23:10:59 +00003156GenericSchedRegistry("converge", "Standard converging scheduler.",
Matthias Braun115efcd2016-11-28 20:11:54 +00003157 createConveringSched);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003158
3159//===----------------------------------------------------------------------===//
3160// PostGenericScheduler - Generic PostRA implementation of MachineSchedStrategy.
3161//===----------------------------------------------------------------------===//
3162
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003163void PostGenericScheduler::initialize(ScheduleDAGMI *Dag) {
3164 DAG = Dag;
3165 SchedModel = DAG->getSchedModel();
3166 TRI = DAG->TRI;
Andrew Trickd14d7c22013-12-28 21:56:57 +00003167
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003168 Rem.init(DAG, SchedModel);
3169 Top.init(DAG, SchedModel, &Rem);
3170 BotRoots.clear();
Andrew Trickd14d7c22013-12-28 21:56:57 +00003171
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003172 // Initialize the HazardRecognizers. If itineraries don't exist, are empty,
3173 // or are disabled, then these HazardRecs will be disabled.
3174 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003175 if (!Top.HazardRec) {
3176 Top.HazardRec =
Eric Christopher99556d72014-10-14 06:56:25 +00003177 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
Eric Christopherd9134482014-08-04 21:25:23 +00003178 Itin, DAG);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003179 }
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003180}
Andrew Trickd14d7c22013-12-28 21:56:57 +00003181
Andrew Trickd14d7c22013-12-28 21:56:57 +00003182void PostGenericScheduler::registerRoots() {
3183 Rem.CriticalPath = DAG->ExitSU.getDepth();
3184
3185 // Some roots may not feed into ExitSU. Check all of them in case.
Javed Absare3a0cc22017-06-21 09:10:10 +00003186 for (const SUnit *SU : BotRoots) {
3187 if (SU->getDepth() > Rem.CriticalPath)
3188 Rem.CriticalPath = SU->getDepth();
Andrew Trickd14d7c22013-12-28 21:56:57 +00003189 }
Gerolf Hoflehnerb5220dc2014-08-07 21:49:44 +00003190 DEBUG(dbgs() << "Critical Path: (PGS-RR) " << Rem.CriticalPath << '\n');
3191 if (DumpCriticalPathLength) {
3192 errs() << "Critical Path(PGS-RR ): " << Rem.CriticalPath << " \n";
3193 }
Andrew Trickd14d7c22013-12-28 21:56:57 +00003194}
3195
3196/// Apply a set of heursitics to a new candidate for PostRA scheduling.
3197///
3198/// \param Cand provides the policy and current best candidate.
3199/// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
3200void PostGenericScheduler::tryCandidate(SchedCandidate &Cand,
3201 SchedCandidate &TryCand) {
3202
3203 // Initialize the candidate if needed.
3204 if (!Cand.isValid()) {
3205 TryCand.Reason = NodeOrder;
3206 return;
3207 }
3208
3209 // Prioritize instructions that read unbuffered resources by stall cycles.
3210 if (tryLess(Top.getLatencyStallCycles(TryCand.SU),
3211 Top.getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
3212 return;
3213
Florian Hahnabb42182017-05-23 09:33:34 +00003214 // Keep clustered nodes together.
3215 if (tryGreater(TryCand.SU == DAG->getNextClusterSucc(),
3216 Cand.SU == DAG->getNextClusterSucc(),
3217 TryCand, Cand, Cluster))
3218 return;
3219
Andrew Trickd14d7c22013-12-28 21:56:57 +00003220 // Avoid critical resource consumption and balance the schedule.
3221 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
3222 TryCand, Cand, ResourceReduce))
3223 return;
3224 if (tryGreater(TryCand.ResDelta.DemandedResources,
3225 Cand.ResDelta.DemandedResources,
3226 TryCand, Cand, ResourceDemand))
3227 return;
3228
3229 // Avoid serializing long latency dependence chains.
3230 if (Cand.Policy.ReduceLatency && tryLatency(TryCand, Cand, Top)) {
3231 return;
3232 }
3233
3234 // Fall through to original instruction order.
3235 if (TryCand.SU->NodeNum < Cand.SU->NodeNum)
3236 TryCand.Reason = NodeOrder;
3237}
3238
3239void PostGenericScheduler::pickNodeFromQueue(SchedCandidate &Cand) {
3240 ReadyQueue &Q = Top.Available;
Javed Absare3a0cc22017-06-21 09:10:10 +00003241 for (SUnit *SU : Q) {
Andrew Trickd14d7c22013-12-28 21:56:57 +00003242 SchedCandidate TryCand(Cand.Policy);
Javed Absare3a0cc22017-06-21 09:10:10 +00003243 TryCand.SU = SU;
Matthias Braun6ad3d052016-06-25 00:23:00 +00003244 TryCand.AtTop = true;
Andrew Trickd14d7c22013-12-28 21:56:57 +00003245 TryCand.initResourceDelta(DAG, SchedModel);
3246 tryCandidate(Cand, TryCand);
3247 if (TryCand.Reason != NoCand) {
3248 Cand.setBest(TryCand);
3249 DEBUG(traceCandidate(Cand));
3250 }
3251 }
3252}
3253
3254/// Pick the next node to schedule.
3255SUnit *PostGenericScheduler::pickNode(bool &IsTopNode) {
3256 if (DAG->top() == DAG->bottom()) {
3257 assert(Top.Available.empty() && Top.Pending.empty() && "ReadyQ garbage");
Craig Topperc0196b12014-04-14 00:51:57 +00003258 return nullptr;
Andrew Trickd14d7c22013-12-28 21:56:57 +00003259 }
3260 SUnit *SU;
3261 do {
3262 SU = Top.pickOnlyChoice();
Matthias Braun49cb6e92016-05-27 22:14:26 +00003263 if (SU) {
3264 tracePick(Only1, true);
3265 } else {
Andrew Trickd14d7c22013-12-28 21:56:57 +00003266 CandPolicy NoPolicy;
3267 SchedCandidate TopCand(NoPolicy);
3268 // Set the top-down policy based on the state of the current top zone and
3269 // the instructions outside the zone, including the bottom zone.
Craig Topperc0196b12014-04-14 00:51:57 +00003270 setPolicy(TopCand.Policy, /*IsPostRA=*/true, Top, nullptr);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003271 pickNodeFromQueue(TopCand);
3272 assert(TopCand.Reason != NoCand && "failed to find a candidate");
Matthias Braun6ad3d052016-06-25 00:23:00 +00003273 tracePick(TopCand);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003274 SU = TopCand.SU;
3275 }
3276 } while (SU->isScheduled);
3277
3278 IsTopNode = true;
3279 Top.removeReady(SU);
3280
3281 DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " << *SU->getInstr());
3282 return SU;
3283}
3284
3285/// Called after ScheduleDAGMI has scheduled an instruction and updated
3286/// scheduled/remaining flags in the DAG nodes.
3287void PostGenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
3288 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
3289 Top.bumpNode(SU);
3290}
3291
Matthias Braun115efcd2016-11-28 20:11:54 +00003292ScheduleDAGMI *llvm::createGenericSchedPostRA(MachineSchedContext *C) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003293 return new ScheduleDAGMI(C, llvm::make_unique<PostGenericScheduler>(C),
Jonas Paulsson28f29482016-11-09 09:59:27 +00003294 /*RemoveKillFlags=*/true);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003295}
Andrew Tricke1c034f2012-01-17 06:55:03 +00003296
3297//===----------------------------------------------------------------------===//
Andrew Trick90f711d2012-10-15 18:02:27 +00003298// ILP Scheduler. Currently for experimental analysis of heuristics.
3299//===----------------------------------------------------------------------===//
3300
3301namespace {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003302
Andrew Trick90f711d2012-10-15 18:02:27 +00003303/// \brief Order nodes by the ILP metric.
3304struct ILPOrder {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003305 const SchedDFSResult *DFSResult = nullptr;
3306 const BitVector *ScheduledTrees = nullptr;
Andrew Trick90f711d2012-10-15 18:02:27 +00003307 bool MaximizeILP;
3308
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003309 ILPOrder(bool MaxILP) : MaximizeILP(MaxILP) {}
Andrew Trick90f711d2012-10-15 18:02:27 +00003310
3311 /// \brief Apply a less-than relation on node priority.
Andrew Trick48d392e2012-11-28 05:13:28 +00003312 ///
3313 /// (Return true if A comes after B in the Q.)
Andrew Trick90f711d2012-10-15 18:02:27 +00003314 bool operator()(const SUnit *A, const SUnit *B) const {
Andrew Trick48d392e2012-11-28 05:13:28 +00003315 unsigned SchedTreeA = DFSResult->getSubtreeID(A);
3316 unsigned SchedTreeB = DFSResult->getSubtreeID(B);
3317 if (SchedTreeA != SchedTreeB) {
3318 // Unscheduled trees have lower priority.
3319 if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
3320 return ScheduledTrees->test(SchedTreeB);
3321
3322 // Trees with shallower connections have have lower priority.
3323 if (DFSResult->getSubtreeLevel(SchedTreeA)
3324 != DFSResult->getSubtreeLevel(SchedTreeB)) {
3325 return DFSResult->getSubtreeLevel(SchedTreeA)
3326 < DFSResult->getSubtreeLevel(SchedTreeB);
3327 }
3328 }
Andrew Trick90f711d2012-10-15 18:02:27 +00003329 if (MaximizeILP)
Andrew Trick48d392e2012-11-28 05:13:28 +00003330 return DFSResult->getILP(A) < DFSResult->getILP(B);
Andrew Trick90f711d2012-10-15 18:02:27 +00003331 else
Andrew Trick48d392e2012-11-28 05:13:28 +00003332 return DFSResult->getILP(A) > DFSResult->getILP(B);
Andrew Trick90f711d2012-10-15 18:02:27 +00003333 }
3334};
3335
3336/// \brief Schedule based on the ILP metric.
3337class ILPScheduler : public MachineSchedStrategy {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003338 ScheduleDAGMILive *DAG = nullptr;
Andrew Trick90f711d2012-10-15 18:02:27 +00003339 ILPOrder Cmp;
3340
3341 std::vector<SUnit*> ReadyQ;
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003342
Andrew Trick90f711d2012-10-15 18:02:27 +00003343public:
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003344 ILPScheduler(bool MaximizeILP) : Cmp(MaximizeILP) {}
Andrew Trick90f711d2012-10-15 18:02:27 +00003345
Craig Topper4584cd52014-03-07 09:26:03 +00003346 void initialize(ScheduleDAGMI *dag) override {
Andrew Trickd7f890e2013-12-28 21:56:47 +00003347 assert(dag->hasVRegLiveness() && "ILPScheduler needs vreg liveness");
3348 DAG = static_cast<ScheduleDAGMILive*>(dag);
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00003349 DAG->computeDFSResult();
Andrew Trick44f750a2013-01-25 04:01:04 +00003350 Cmp.DFSResult = DAG->getDFSResult();
3351 Cmp.ScheduledTrees = &DAG->getScheduledTrees();
Andrew Trick90f711d2012-10-15 18:02:27 +00003352 ReadyQ.clear();
Andrew Trick90f711d2012-10-15 18:02:27 +00003353 }
3354
Craig Topper4584cd52014-03-07 09:26:03 +00003355 void registerRoots() override {
Benjamin Krameraa598b32012-11-29 14:36:26 +00003356 // Restore the heap in ReadyQ with the updated DFS results.
3357 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
Andrew Trick90f711d2012-10-15 18:02:27 +00003358 }
3359
3360 /// Implement MachineSchedStrategy interface.
3361 /// -----------------------------------------
3362
Andrew Trick48d392e2012-11-28 05:13:28 +00003363 /// Callback to select the highest priority node from the ready Q.
Craig Topper4584cd52014-03-07 09:26:03 +00003364 SUnit *pickNode(bool &IsTopNode) override {
Craig Topperc0196b12014-04-14 00:51:57 +00003365 if (ReadyQ.empty()) return nullptr;
Matt Arsenault4ab769f2013-03-21 00:57:21 +00003366 std::pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
Andrew Trick90f711d2012-10-15 18:02:27 +00003367 SUnit *SU = ReadyQ.back();
3368 ReadyQ.pop_back();
3369 IsTopNode = false;
Andrew Trick1f0bb692013-04-13 06:07:49 +00003370 DEBUG(dbgs() << "Pick node " << "SU(" << SU->NodeNum << ") "
Andrew Trick44f750a2013-01-25 04:01:04 +00003371 << " ILP: " << DAG->getDFSResult()->getILP(SU)
3372 << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU) << " @"
3373 << DAG->getDFSResult()->getSubtreeLevel(
Andrew Trick1f0bb692013-04-13 06:07:49 +00003374 DAG->getDFSResult()->getSubtreeID(SU)) << '\n'
3375 << "Scheduling " << *SU->getInstr());
Andrew Trick90f711d2012-10-15 18:02:27 +00003376 return SU;
3377 }
3378
Andrew Trick44f750a2013-01-25 04:01:04 +00003379 /// \brief Scheduler callback to notify that a new subtree is scheduled.
Craig Topper4584cd52014-03-07 09:26:03 +00003380 void scheduleTree(unsigned SubtreeID) override {
Andrew Trick44f750a2013-01-25 04:01:04 +00003381 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3382 }
3383
Andrew Trick48d392e2012-11-28 05:13:28 +00003384 /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
3385 /// DFSResults, and resort the priority Q.
Craig Topper4584cd52014-03-07 09:26:03 +00003386 void schedNode(SUnit *SU, bool IsTopNode) override {
Andrew Trick48d392e2012-11-28 05:13:28 +00003387 assert(!IsTopNode && "SchedDFSResult needs bottom-up");
Andrew Trick48d392e2012-11-28 05:13:28 +00003388 }
Andrew Trick90f711d2012-10-15 18:02:27 +00003389
Craig Topper4584cd52014-03-07 09:26:03 +00003390 void releaseTopNode(SUnit *) override { /*only called for top roots*/ }
Andrew Trick90f711d2012-10-15 18:02:27 +00003391
Craig Topper4584cd52014-03-07 09:26:03 +00003392 void releaseBottomNode(SUnit *SU) override {
Andrew Trick90f711d2012-10-15 18:02:27 +00003393 ReadyQ.push_back(SU);
3394 std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3395 }
3396};
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003397
3398} // end anonymous namespace
Andrew Trick90f711d2012-10-15 18:02:27 +00003399
3400static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003401 return new ScheduleDAGMILive(C, llvm::make_unique<ILPScheduler>(true));
Andrew Trick90f711d2012-10-15 18:02:27 +00003402}
3403static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003404 return new ScheduleDAGMILive(C, llvm::make_unique<ILPScheduler>(false));
Andrew Trick90f711d2012-10-15 18:02:27 +00003405}
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003406
Andrew Trick90f711d2012-10-15 18:02:27 +00003407static MachineSchedRegistry ILPMaxRegistry(
3408 "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
3409static MachineSchedRegistry ILPMinRegistry(
3410 "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
3411
3412//===----------------------------------------------------------------------===//
Andrew Trick63440872012-01-14 02:17:06 +00003413// Machine Instruction Shuffler for Correctness Testing
3414//===----------------------------------------------------------------------===//
3415
Andrew Tricke77e84e2012-01-13 06:30:30 +00003416#ifndef NDEBUG
3417namespace {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003418
Andrew Trick8823dec2012-03-14 04:00:41 +00003419/// Apply a less-than relation on the node order, which corresponds to the
3420/// instruction order prior to scheduling. IsReverse implements greater-than.
3421template<bool IsReverse>
3422struct SUnitOrder {
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003423 bool operator()(SUnit *A, SUnit *B) const {
Andrew Trick8823dec2012-03-14 04:00:41 +00003424 if (IsReverse)
3425 return A->NodeNum > B->NodeNum;
3426 else
3427 return A->NodeNum < B->NodeNum;
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003428 }
3429};
3430
Andrew Tricke77e84e2012-01-13 06:30:30 +00003431/// Reorder instructions as much as possible.
Andrew Trick8823dec2012-03-14 04:00:41 +00003432class InstructionShuffler : public MachineSchedStrategy {
3433 bool IsAlternating;
3434 bool IsTopDown;
3435
3436 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
3437 // gives nodes with a higher number higher priority causing the latest
3438 // instructions to be scheduled first.
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003439 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false>>
Andrew Trick8823dec2012-03-14 04:00:41 +00003440 TopQ;
3441 // When scheduling bottom-up, use greater-than as the queue priority.
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003442 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true>>
Andrew Trick8823dec2012-03-14 04:00:41 +00003443 BottomQ;
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003444
Andrew Tricke77e84e2012-01-13 06:30:30 +00003445public:
Andrew Trick8823dec2012-03-14 04:00:41 +00003446 InstructionShuffler(bool alternate, bool topdown)
3447 : IsAlternating(alternate), IsTopDown(topdown) {}
Andrew Tricke77e84e2012-01-13 06:30:30 +00003448
Craig Topper9d74a5a2014-04-29 07:58:41 +00003449 void initialize(ScheduleDAGMI*) override {
Andrew Trick8823dec2012-03-14 04:00:41 +00003450 TopQ.clear();
3451 BottomQ.clear();
3452 }
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003453
Andrew Trick8823dec2012-03-14 04:00:41 +00003454 /// Implement MachineSchedStrategy interface.
3455 /// -----------------------------------------
3456
Craig Topper9d74a5a2014-04-29 07:58:41 +00003457 SUnit *pickNode(bool &IsTopNode) override {
Andrew Trick8823dec2012-03-14 04:00:41 +00003458 SUnit *SU;
3459 if (IsTopDown) {
3460 do {
Craig Topperc0196b12014-04-14 00:51:57 +00003461 if (TopQ.empty()) return nullptr;
Andrew Trick8823dec2012-03-14 04:00:41 +00003462 SU = TopQ.top();
3463 TopQ.pop();
3464 } while (SU->isScheduled);
3465 IsTopNode = true;
Matthias Braunb550b762016-04-21 01:54:13 +00003466 } else {
Andrew Trick8823dec2012-03-14 04:00:41 +00003467 do {
Craig Topperc0196b12014-04-14 00:51:57 +00003468 if (BottomQ.empty()) return nullptr;
Andrew Trick8823dec2012-03-14 04:00:41 +00003469 SU = BottomQ.top();
3470 BottomQ.pop();
3471 } while (SU->isScheduled);
3472 IsTopNode = false;
3473 }
3474 if (IsAlternating)
3475 IsTopDown = !IsTopDown;
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003476 return SU;
3477 }
3478
Craig Topper9d74a5a2014-04-29 07:58:41 +00003479 void schedNode(SUnit *SU, bool IsTopNode) override {}
Andrew Trick61f1a272012-05-24 22:11:09 +00003480
Craig Topper9d74a5a2014-04-29 07:58:41 +00003481 void releaseTopNode(SUnit *SU) override {
Andrew Trick8823dec2012-03-14 04:00:41 +00003482 TopQ.push(SU);
3483 }
Craig Topper9d74a5a2014-04-29 07:58:41 +00003484 void releaseBottomNode(SUnit *SU) override {
Andrew Trick8823dec2012-03-14 04:00:41 +00003485 BottomQ.push(SU);
Andrew Tricke77e84e2012-01-13 06:30:30 +00003486 }
3487};
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003488
3489} // end anonymous namespace
Andrew Tricke77e84e2012-01-13 06:30:30 +00003490
Andrew Trick02a80da2012-03-08 01:41:12 +00003491static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
Andrew Trick8823dec2012-03-14 04:00:41 +00003492 bool Alternate = !ForceTopDown && !ForceBottomUp;
3493 bool TopDown = !ForceBottomUp;
Benjamin Kramer05e7a842012-03-14 11:26:37 +00003494 assert((TopDown || !ForceTopDown) &&
Andrew Trick8823dec2012-03-14 04:00:41 +00003495 "-misched-topdown incompatible with -misched-bottomup");
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003496 return new ScheduleDAGMILive(
3497 C, llvm::make_unique<InstructionShuffler>(Alternate, TopDown));
Andrew Tricke77e84e2012-01-13 06:30:30 +00003498}
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003499
Andrew Trick8823dec2012-03-14 04:00:41 +00003500static MachineSchedRegistry ShufflerRegistry(
3501 "shuffle", "Shuffle machine instructions alternating directions",
3502 createInstructionShuffler);
Andrew Tricke77e84e2012-01-13 06:30:30 +00003503#endif // !NDEBUG
Andrew Trickea9fd952013-01-25 07:45:29 +00003504
3505//===----------------------------------------------------------------------===//
Andrew Trickd7f890e2013-12-28 21:56:47 +00003506// GraphWriter support for ScheduleDAGMILive.
Andrew Trickea9fd952013-01-25 07:45:29 +00003507//===----------------------------------------------------------------------===//
3508
3509#ifndef NDEBUG
3510namespace llvm {
3511
3512template<> struct GraphTraits<
3513 ScheduleDAGMI*> : public GraphTraits<ScheduleDAG*> {};
3514
3515template<>
3516struct DOTGraphTraits<ScheduleDAGMI*> : public DefaultDOTGraphTraits {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003517 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
Andrew Trickea9fd952013-01-25 07:45:29 +00003518
3519 static std::string getGraphName(const ScheduleDAG *G) {
3520 return G->MF.getName();
3521 }
3522
3523 static bool renderGraphFromBottomUp() {
3524 return true;
3525 }
3526
3527 static bool isNodeHidden(const SUnit *Node) {
Matthias Braund78ee542015-09-17 21:09:59 +00003528 if (ViewMISchedCutoff == 0)
3529 return false;
3530 return (Node->Preds.size() > ViewMISchedCutoff
3531 || Node->Succs.size() > ViewMISchedCutoff);
Andrew Trickea9fd952013-01-25 07:45:29 +00003532 }
3533
Andrew Trickea9fd952013-01-25 07:45:29 +00003534 /// If you want to override the dot attributes printed for a particular
3535 /// edge, override this method.
3536 static std::string getEdgeAttributes(const SUnit *Node,
3537 SUnitIterator EI,
3538 const ScheduleDAG *Graph) {
3539 if (EI.isArtificialDep())
3540 return "color=cyan,style=dashed";
3541 if (EI.isCtrlDep())
3542 return "color=blue,style=dashed";
3543 return "";
3544 }
3545
3546 static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) {
Alp Tokere69170a2014-06-26 22:52:05 +00003547 std::string Str;
3548 raw_string_ostream SS(Str);
Andrew Trickd7f890e2013-12-28 21:56:47 +00003549 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3550 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
Craig Topperc0196b12014-04-14 00:51:57 +00003551 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
Andrew Trick7609b7d2013-09-06 17:32:42 +00003552 SS << "SU:" << SU->NodeNum;
3553 if (DFS)
3554 SS << " I:" << DFS->getNumInstrs(SU);
Andrew Trickea9fd952013-01-25 07:45:29 +00003555 return SS.str();
3556 }
3557 static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G) {
3558 return G->getGraphNodeLabel(SU);
3559 }
3560
Andrew Trickd7f890e2013-12-28 21:56:47 +00003561 static std::string getNodeAttributes(const SUnit *N, const ScheduleDAG *G) {
Andrew Trickea9fd952013-01-25 07:45:29 +00003562 std::string Str("shape=Mrecord");
Andrew Trickd7f890e2013-12-28 21:56:47 +00003563 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3564 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
Craig Topperc0196b12014-04-14 00:51:57 +00003565 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
Andrew Trickea9fd952013-01-25 07:45:29 +00003566 if (DFS) {
3567 Str += ",style=filled,fillcolor=\"#";
3568 Str += DOT::getColorString(DFS->getSubtreeID(N));
3569 Str += '"';
3570 }
3571 return Str;
3572 }
3573};
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003574
3575} // end namespace llvm
Andrew Trickea9fd952013-01-25 07:45:29 +00003576#endif // NDEBUG
3577
3578/// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
3579/// rendered using 'dot'.
3580///
3581void ScheduleDAGMI::viewGraph(const Twine &Name, const Twine &Title) {
3582#ifndef NDEBUG
3583 ViewGraph(this, Name, false, Title);
3584#else
3585 errs() << "ScheduleDAGMI::viewGraph is only available in debug builds on "
3586 << "systems with Graphviz or gv!\n";
3587#endif // NDEBUG
3588}
3589
3590/// Out-of-line implementation with no arguments is handy for gdb.
3591void ScheduleDAGMI::viewGraph() {
3592 viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName());
3593}