blob: 79b02c7de8c9fe079cad48fca1d1a6754c1ce61e [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
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000015#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/BitVector.h"
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/iterator_range.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/SmallVector.h"
21#include "llvm/ADT/STLExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/Analysis/AliasAnalysis.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000023#include "llvm/CodeGen/LiveInterval.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000025#include "llvm/CodeGen/MachineBasicBlock.h"
Jakub Staszakdf17ddd2013-03-10 13:11:23 +000026#include "llvm/CodeGen/MachineDominators.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000027#include "llvm/CodeGen/MachineFunction.h"
28#include "llvm/CodeGen/MachineFunctionPass.h"
29#include "llvm/CodeGen/MachineInstr.h"
Jakub Staszakdf17ddd2013-03-10 13:11:23 +000030#include "llvm/CodeGen/MachineLoopInfo.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000031#include "llvm/CodeGen/MachineOperand.h"
32#include "llvm/CodeGen/MachinePassRegistry.h"
33#include "llvm/CodeGen/RegisterPressure.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/MachineScheduler.h"
36#include "llvm/CodeGen/MachineValueType.h"
Andrew Tricke77e84e2012-01-13 06:30:30 +000037#include "llvm/CodeGen/Passes.h"
Andrew Trick05ff4662012-06-06 20:29:31 +000038#include "llvm/CodeGen/RegisterClassInfo.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
Chandler Carruth1b9dde02014-04-22 02:02:50 +000072#define DEBUG_TYPE "misched"
73
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
Akira Hatanaka7ba78302014-12-13 04:52:04 +0000194INITIALIZE_PASS_BEGIN(MachineScheduler, "machine-scheduler",
Andrew Tricke77e84e2012-01-13 06:30:30 +0000195 "Machine Instruction Scheduler", false, false)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000196INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Andrew Tricke77e84e2012-01-13 06:30:30 +0000197INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
198INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
Akira Hatanaka7ba78302014-12-13 04:52:04 +0000199INITIALIZE_PASS_END(MachineScheduler, "machine-scheduler",
Andrew Tricke77e84e2012-01-13 06:30:30 +0000200 "Machine Instruction Scheduler", false, false)
201
Andrew Tricke1c034f2012-01-17 06:55:03 +0000202MachineScheduler::MachineScheduler()
Andrew Trickd7f890e2013-12-28 21:56:47 +0000203: MachineSchedulerBase(ID) {
Andrew Tricke1c034f2012-01-17 06:55:03 +0000204 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Andrew Tricke77e84e2012-01-13 06:30:30 +0000205}
206
Andrew Tricke1c034f2012-01-17 06:55:03 +0000207void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
Andrew Tricke77e84e2012-01-13 06:30:30 +0000208 AU.setPreservesCFG();
209 AU.addRequiredID(MachineDominatorsID);
210 AU.addRequired<MachineLoopInfo>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000211 AU.addRequired<AAResultsWrapperPass>();
Andrew Trick45300682012-03-09 00:52:20 +0000212 AU.addRequired<TargetPassConfig>();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000213 AU.addRequired<SlotIndexes>();
214 AU.addPreserved<SlotIndexes>();
215 AU.addRequired<LiveIntervals>();
216 AU.addPreserved<LiveIntervals>();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000217 MachineFunctionPass::getAnalysisUsage(AU);
218}
219
Andrew Trick17080b92013-12-28 21:56:51 +0000220char PostMachineScheduler::ID = 0;
221
222char &llvm::PostMachineSchedulerID = PostMachineScheduler::ID;
223
224INITIALIZE_PASS(PostMachineScheduler, "postmisched",
Saleem Abdulrasool7230b372013-12-28 22:47:55 +0000225 "PostRA Machine Instruction Scheduler", false, false)
Andrew Trick17080b92013-12-28 21:56:51 +0000226
227PostMachineScheduler::PostMachineScheduler()
228: MachineSchedulerBase(ID) {
229 initializePostMachineSchedulerPass(*PassRegistry::getPassRegistry());
230}
231
232void PostMachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
233 AU.setPreservesCFG();
234 AU.addRequiredID(MachineDominatorsID);
235 AU.addRequired<MachineLoopInfo>();
236 AU.addRequired<TargetPassConfig>();
237 MachineFunctionPass::getAnalysisUsage(AU);
238}
239
Andrew Tricke77e84e2012-01-13 06:30:30 +0000240MachinePassRegistry MachineSchedRegistry::Registry;
241
Andrew Trick45300682012-03-09 00:52:20 +0000242/// A dummy default scheduler factory indicates whether the scheduler
243/// is overridden on the command line.
244static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
Craig Topperc0196b12014-04-14 00:51:57 +0000245 return nullptr;
Andrew Trick45300682012-03-09 00:52:20 +0000246}
Andrew Tricke77e84e2012-01-13 06:30:30 +0000247
248/// MachineSchedOpt allows command line selection of the scheduler.
249static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +0000250 RegisterPassParser<MachineSchedRegistry>>
Andrew Tricke77e84e2012-01-13 06:30:30 +0000251MachineSchedOpt("misched",
Andrew Trick45300682012-03-09 00:52:20 +0000252 cl::init(&useDefaultMachineSched), cl::Hidden,
Andrew Tricke77e84e2012-01-13 06:30:30 +0000253 cl::desc("Machine instruction scheduler to use"));
254
Andrew Trick45300682012-03-09 00:52:20 +0000255static MachineSchedRegistry
Andrew Trick8823dec2012-03-14 04:00:41 +0000256DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
Andrew Trick45300682012-03-09 00:52:20 +0000257 useDefaultMachineSched);
258
Eric Christopher5f141b02015-03-11 22:56:10 +0000259static cl::opt<bool> EnableMachineSched(
260 "enable-misched",
261 cl::desc("Enable the machine instruction scheduling pass."), cl::init(true),
262 cl::Hidden);
263
Chad Rosier816a1ab2016-01-20 23:08:32 +0000264static cl::opt<bool> EnablePostRAMachineSched(
265 "enable-post-misched",
266 cl::desc("Enable the post-ra machine instruction scheduling pass."),
267 cl::init(true), cl::Hidden);
268
Andrew Trickcc45a282012-04-24 18:04:34 +0000269/// Decrement this iterator until reaching the top or a non-debug instr.
Andrew Trick2bc74c22013-08-30 04:36:57 +0000270static MachineBasicBlock::const_iterator
271priorNonDebug(MachineBasicBlock::const_iterator I,
272 MachineBasicBlock::const_iterator Beg) {
Andrew Trickcc45a282012-04-24 18:04:34 +0000273 assert(I != Beg && "reached the top of the region, cannot decrement");
274 while (--I != Beg) {
275 if (!I->isDebugValue())
276 break;
277 }
278 return I;
279}
280
Andrew Trick2bc74c22013-08-30 04:36:57 +0000281/// Non-const version.
282static MachineBasicBlock::iterator
283priorNonDebug(MachineBasicBlock::iterator I,
284 MachineBasicBlock::const_iterator Beg) {
Duncan P. N. Exon Smithdcbce9c2016-08-16 23:34:07 +0000285 return priorNonDebug(MachineBasicBlock::const_iterator(I), Beg)
286 .getNonConstIterator();
Andrew Trick2bc74c22013-08-30 04:36:57 +0000287}
288
Andrew Trickcc45a282012-04-24 18:04:34 +0000289/// If this iterator is a debug value, increment until reaching the End or a
290/// non-debug instruction.
Andrew Trick2c4f8b72013-08-31 05:17:58 +0000291static MachineBasicBlock::const_iterator
292nextIfDebug(MachineBasicBlock::const_iterator I,
293 MachineBasicBlock::const_iterator End) {
Andrew Trick463b2f12012-05-17 18:35:03 +0000294 for(; I != End; ++I) {
Andrew Trickcc45a282012-04-24 18:04:34 +0000295 if (!I->isDebugValue())
296 break;
297 }
298 return I;
299}
300
Andrew Trick2c4f8b72013-08-31 05:17:58 +0000301/// Non-const version.
302static MachineBasicBlock::iterator
303nextIfDebug(MachineBasicBlock::iterator I,
304 MachineBasicBlock::const_iterator End) {
Duncan P. N. Exon Smithdcbce9c2016-08-16 23:34:07 +0000305 return nextIfDebug(MachineBasicBlock::const_iterator(I), End)
306 .getNonConstIterator();
Andrew Trick2c4f8b72013-08-31 05:17:58 +0000307}
308
Andrew Trickdc4c1ad2013-09-24 17:11:19 +0000309/// Instantiate a ScheduleDAGInstrs that will be owned by the caller.
Andrew Trick978674b2013-09-20 05:14:41 +0000310ScheduleDAGInstrs *MachineScheduler::createMachineScheduler() {
311 // Select the scheduler, or set the default.
312 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
313 if (Ctor != useDefaultMachineSched)
314 return Ctor(this);
315
316 // Get the default scheduler set by the target for this function.
317 ScheduleDAGInstrs *Scheduler = PassConfig->createMachineScheduler(this);
318 if (Scheduler)
319 return Scheduler;
320
321 // Default to GenericScheduler.
Andrew Trickd14d7c22013-12-28 21:56:57 +0000322 return createGenericSchedLive(this);
Andrew Trick978674b2013-09-20 05:14:41 +0000323}
324
Andrew Trick17080b92013-12-28 21:56:51 +0000325/// Instantiate a ScheduleDAGInstrs for PostRA scheduling that will be owned by
326/// the caller. We don't have a command line option to override the postRA
327/// scheduler. The Target must configure it.
328ScheduleDAGInstrs *PostMachineScheduler::createPostMachineScheduler() {
329 // Get the postRA scheduler set by the target for this function.
330 ScheduleDAGInstrs *Scheduler = PassConfig->createPostMachineScheduler(this);
331 if (Scheduler)
332 return Scheduler;
333
334 // Default to GenericScheduler.
Andrew Trickd14d7c22013-12-28 21:56:57 +0000335 return createGenericSchedPostRA(this);
Andrew Trick17080b92013-12-28 21:56:51 +0000336}
337
Andrew Trick72515be2012-03-14 04:00:38 +0000338/// Top-level MachineScheduler pass driver.
339///
340/// Visit blocks in function order. Divide each block into scheduling regions
Andrew Trick8823dec2012-03-14 04:00:41 +0000341/// and visit them bottom-up. Visiting regions bottom-up is not required, but is
342/// consistent with the DAG builder, which traverses the interior of the
343/// scheduling regions bottom-up.
Andrew Trick72515be2012-03-14 04:00:38 +0000344///
345/// This design avoids exposing scheduling boundaries to the DAG builder,
Andrew Trick8823dec2012-03-14 04:00:41 +0000346/// simplifying the DAG builder's support for "special" target instructions.
347/// At the same time the design allows target schedulers to operate across
Andrew Trick72515be2012-03-14 04:00:38 +0000348/// scheduling boundaries, for example to bundle the boudary instructions
349/// without reordering them. This creates complexity, because the target
350/// scheduler must update the RegionBegin and RegionEnd positions cached by
351/// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
352/// design would be to split blocks at scheduling boundaries, but LLVM has a
353/// general bias against block splitting purely for implementation simplicity.
Andrew Tricke1c034f2012-01-17 06:55:03 +0000354bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000355 if (skipFunction(*mf.getFunction()))
Chad Rosier6338d7c2016-01-20 22:38:25 +0000356 return false;
357
Eric Christopher5f141b02015-03-11 22:56:10 +0000358 if (EnableMachineSched.getNumOccurrences()) {
359 if (!EnableMachineSched)
360 return false;
361 } else if (!mf.getSubtarget().enableMachineScheduler())
362 return false;
363
Matthias Braundc7580a2015-10-29 03:57:28 +0000364 DEBUG(dbgs() << "Before MISched:\n"; mf.print(dbgs()));
Andrew Trickc5d70082012-05-10 21:06:21 +0000365
Andrew Tricke77e84e2012-01-13 06:30:30 +0000366 // Initialize the context of the pass.
367 MF = &mf;
368 MLI = &getAnalysis<MachineLoopInfo>();
369 MDT = &getAnalysis<MachineDominatorTree>();
Andrew Trick45300682012-03-09 00:52:20 +0000370 PassConfig = &getAnalysis<TargetPassConfig>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000371 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Andrew Trick02a80da2012-03-08 01:41:12 +0000372
Lang Hamesad33d5a2012-01-27 22:36:19 +0000373 LIS = &getAnalysis<LiveIntervals>();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000374
Andrew Trick48f2a722013-03-08 05:40:34 +0000375 if (VerifyScheduling) {
Andrew Trick97064962013-07-25 07:26:26 +0000376 DEBUG(LIS->dump());
Andrew Trick48f2a722013-03-08 05:40:34 +0000377 MF->verify(this, "Before machine scheduling.");
378 }
Andrew Trick4d4b5462012-04-24 20:36:19 +0000379 RegClassInfo->runOnMachineFunction(*MF);
Andrew Trick88639922012-04-24 17:56:43 +0000380
Andrew Trick978674b2013-09-20 05:14:41 +0000381 // Instantiate the selected scheduler for this target, function, and
382 // optimization level.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000383 std::unique_ptr<ScheduleDAGInstrs> Scheduler(createMachineScheduler());
Matthias Braun93563e72015-11-03 01:53:29 +0000384 scheduleRegions(*Scheduler, false);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000385
386 DEBUG(LIS->dump());
387 if (VerifyScheduling)
388 MF->verify(this, "After machine scheduling.");
389 return true;
390}
391
Andrew Trick17080b92013-12-28 21:56:51 +0000392bool PostMachineScheduler::runOnMachineFunction(MachineFunction &mf) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000393 if (skipFunction(*mf.getFunction()))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000394 return false;
395
Chad Rosier816a1ab2016-01-20 23:08:32 +0000396 if (EnablePostRAMachineSched.getNumOccurrences()) {
397 if (!EnablePostRAMachineSched)
398 return false;
399 } else if (!mf.getSubtarget().enablePostRAScheduler()) {
Andrew Trick8d2ee372014-06-04 07:06:27 +0000400 DEBUG(dbgs() << "Subtarget disables post-MI-sched.\n");
401 return false;
402 }
Andrew Trick17080b92013-12-28 21:56:51 +0000403 DEBUG(dbgs() << "Before post-MI-sched:\n"; mf.print(dbgs()));
404
405 // Initialize the context of the pass.
406 MF = &mf;
407 PassConfig = &getAnalysis<TargetPassConfig>();
408
409 if (VerifyScheduling)
410 MF->verify(this, "Before post machine scheduling.");
411
412 // Instantiate the selected scheduler for this target, function, and
413 // optimization level.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000414 std::unique_ptr<ScheduleDAGInstrs> Scheduler(createPostMachineScheduler());
Matthias Braun93563e72015-11-03 01:53:29 +0000415 scheduleRegions(*Scheduler, true);
Andrew Trick17080b92013-12-28 21:56:51 +0000416
417 if (VerifyScheduling)
418 MF->verify(this, "After post machine scheduling.");
419 return true;
420}
421
Andrew Trickd14d7c22013-12-28 21:56:57 +0000422/// Return true of the given instruction should not be included in a scheduling
423/// region.
424///
425/// MachineScheduler does not currently support scheduling across calls. To
426/// handle calls, the DAG builder needs to be modified to create register
427/// anti/output dependencies on the registers clobbered by the call's regmask
428/// operand. In PreRA scheduling, the stack pointer adjustment already prevents
429/// scheduling across calls. In PostRA scheduling, we need the isCall to enforce
430/// the boundary, but there would be no benefit to postRA scheduling across
431/// calls this late anyway.
432static bool isSchedBoundary(MachineBasicBlock::iterator MI,
433 MachineBasicBlock *MBB,
434 MachineFunction *MF,
Matthias Braun93563e72015-11-03 01:53:29 +0000435 const TargetInstrInfo *TII) {
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000436 return MI->isCall() || TII->isSchedulingBoundary(*MI, MBB, *MF);
Andrew Trickd14d7c22013-12-28 21:56:57 +0000437}
438
Andrew Trickd7f890e2013-12-28 21:56:47 +0000439/// Main driver for both MachineScheduler and PostMachineScheduler.
Matthias Braun93563e72015-11-03 01:53:29 +0000440void MachineSchedulerBase::scheduleRegions(ScheduleDAGInstrs &Scheduler,
441 bool FixKillFlags) {
Eric Christopherfc6de422014-08-05 02:39:49 +0000442 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000443
444 // Visit all machine basic blocks.
Andrew Trick88639922012-04-24 17:56:43 +0000445 //
446 // TODO: Visit blocks in global postorder or postorder within the bottom-up
447 // loop tree. Then we can optionally compute global RegPressure.
Andrew Tricke77e84e2012-01-13 06:30:30 +0000448 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
449 MBB != MBBEnd; ++MBB) {
450
Duncan P. N. Exon Smith5ec15682015-10-09 19:40:45 +0000451 Scheduler.startBlock(&*MBB);
Andrew Trickedfe2ec2012-03-09 08:02:51 +0000452
Andrew Trick33e05d72013-12-28 21:57:02 +0000453#ifndef NDEBUG
454 if (SchedOnlyFunc.getNumOccurrences() && SchedOnlyFunc != MF->getName())
455 continue;
456 if (SchedOnlyBlock.getNumOccurrences()
457 && (int)SchedOnlyBlock != MBB->getNumber())
458 continue;
459#endif
460
Andrew Trick7e120f42012-01-14 02:17:09 +0000461 // Break the block into scheduling regions [I, RegionEnd), and schedule each
Sylvestre Ledru35521e22012-07-23 08:51:15 +0000462 // region as soon as it is discovered. RegionEnd points the scheduling
Andrew Trickaf1bee72012-03-09 22:34:56 +0000463 // boundary at the bottom of the region. The DAG does not include RegionEnd,
464 // but the region does (i.e. the next RegionEnd is above the previous
465 // RegionBegin). If the current block has no terminator then RegionEnd ==
466 // MBB->end() for the bottom region.
467 //
468 // The Scheduler may insert instructions during either schedule() or
469 // exitRegion(), even for empty regions. So the local iterators 'I' and
470 // 'RegionEnd' are invalid across these calls.
Andrew Trickd14d7c22013-12-28 21:56:57 +0000471 //
472 // MBB::size() uses instr_iterator to count. Here we need a bundle to count
473 // as a single instruction.
Andrew Tricka21daf72012-03-09 03:46:39 +0000474 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
Andrew Trickd7f890e2013-12-28 21:56:47 +0000475 RegionEnd != MBB->begin(); RegionEnd = Scheduler.begin()) {
Andrew Trick88639922012-04-24 17:56:43 +0000476
Andrew Trickedfe2ec2012-03-09 08:02:51 +0000477 // Avoid decrementing RegionEnd for blocks with no terminator.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000478 if (RegionEnd != MBB->end() ||
Matthias Braun93563e72015-11-03 01:53:29 +0000479 isSchedBoundary(&*std::prev(RegionEnd), &*MBB, MF, TII)) {
Andrew Trickedfe2ec2012-03-09 08:02:51 +0000480 --RegionEnd;
Andrew Trickedfe2ec2012-03-09 08:02:51 +0000481 }
482
Andrew Trick7e120f42012-01-14 02:17:09 +0000483 // The next region starts above the previous region. Look backward in the
484 // instruction stream until we find the nearest boundary.
Andrew Tricka53e1012013-08-23 17:48:33 +0000485 unsigned NumRegionInstrs = 0;
Andrew Trick7e120f42012-01-14 02:17:09 +0000486 MachineBasicBlock::iterator I = RegionEnd;
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +0000487 for (; I != MBB->begin(); --I) {
Duncan P. N. Exon Smith38eea4a2016-08-11 20:03:09 +0000488 MachineInstr &MI = *std::prev(I);
489 if (isSchedBoundary(&MI, &*MBB, MF, TII))
Andrew Trick7e120f42012-01-14 02:17:09 +0000490 break;
Duncan P. N. Exon Smith38eea4a2016-08-11 20:03:09 +0000491 if (!MI.isDebugValue())
Andrea Di Biagiod65fd9f2014-12-12 15:09:58 +0000492 ++NumRegionInstrs;
Andrew Trick7e120f42012-01-14 02:17:09 +0000493 }
Andrew Trick60cf03e2012-03-07 05:21:52 +0000494 // Notify the scheduler of the region, even if we may skip scheduling
495 // it. Perhaps it still needs to be bundled.
Duncan P. N. Exon Smith5ec15682015-10-09 19:40:45 +0000496 Scheduler.enterRegion(&*MBB, I, RegionEnd, NumRegionInstrs);
Andrew Trick60cf03e2012-03-07 05:21:52 +0000497
498 // Skip empty scheduling regions (0 or 1 schedulable instructions).
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000499 if (I == RegionEnd || I == std::prev(RegionEnd)) {
Andrew Trick60cf03e2012-03-07 05:21:52 +0000500 // Close the current region. Bundle the terminator if needed.
Andrew Trickaf1bee72012-03-09 22:34:56 +0000501 // This invalidates 'RegionEnd' and 'I'.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000502 Scheduler.exitRegion();
Andrew Trick7ccdc5c2012-01-17 06:55:07 +0000503 continue;
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000504 }
Matthias Braun93563e72015-11-03 01:53:29 +0000505 DEBUG(dbgs() << "********** MI Scheduling **********\n");
Craig Toppera538d832012-08-22 06:07:19 +0000506 DEBUG(dbgs() << MF->getName()
Andrew Trick54b2ce32013-01-25 07:45:31 +0000507 << ":BB#" << MBB->getNumber() << " " << MBB->getName()
508 << "\n From: " << *I << " To: ";
Andrew Tricke57583a2012-02-08 02:17:21 +0000509 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
510 else dbgs() << "End";
Matthias Braun858d1df2016-05-20 19:46:13 +0000511 dbgs() << " RegionInstrs: " << NumRegionInstrs << '\n');
Gerolf Hoflehnerb5220dc2014-08-07 21:49:44 +0000512 if (DumpCriticalPathLength) {
513 errs() << MF->getName();
514 errs() << ":BB# " << MBB->getNumber();
515 errs() << " " << MBB->getName() << " \n";
516 }
Andrew Trick7ccdc5c2012-01-17 06:55:07 +0000517
Andrew Trick1c0ec452012-03-09 03:46:42 +0000518 // Schedule a region: possibly reorder instructions.
Andrew Trickaf1bee72012-03-09 22:34:56 +0000519 // This invalidates 'RegionEnd' and 'I'.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000520 Scheduler.schedule();
Andrew Trick1c0ec452012-03-09 03:46:42 +0000521
522 // Close the current region.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000523 Scheduler.exitRegion();
Andrew Trick60cf03e2012-03-07 05:21:52 +0000524
525 // Scheduling has invalidated the current iterator 'I'. Ask the
526 // scheduler for the top of it's scheduled region.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000527 RegionEnd = Scheduler.begin();
Andrew Trick7e120f42012-01-14 02:17:09 +0000528 }
Andrew Trickd7f890e2013-12-28 21:56:47 +0000529 Scheduler.finishBlock();
Matthias Braun93563e72015-11-03 01:53:29 +0000530 // FIXME: Ideally, no further passes should rely on kill flags. However,
531 // thumb2 size reduction is currently an exception, so the PostMIScheduler
532 // needs to do this.
533 if (FixKillFlags)
534 Scheduler.fixupKills(&*MBB);
Andrew Tricke77e84e2012-01-13 06:30:30 +0000535 }
Andrew Trickd7f890e2013-12-28 21:56:47 +0000536 Scheduler.finalizeSchedule();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000537}
538
Andrew Trickd7f890e2013-12-28 21:56:47 +0000539void MachineSchedulerBase::print(raw_ostream &O, const Module* m) const {
Andrew Tricke77e84e2012-01-13 06:30:30 +0000540 // unimplemented
541}
542
Matthias Braun8c209aa2017-01-28 02:02:38 +0000543#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
544LLVM_DUMP_METHOD void ReadyQueue::dump() {
James Y Knighte72b0db2015-09-18 18:52:20 +0000545 dbgs() << "Queue " << Name << ": ";
Andrew Trick7a8e1002012-09-11 00:39:15 +0000546 for (unsigned i = 0, e = Queue.size(); i < e; ++i)
547 dbgs() << Queue[i]->NodeNum << " ";
548 dbgs() << "\n";
549}
Matthias Braun8c209aa2017-01-28 02:02:38 +0000550#endif
Andrew Trick8823dec2012-03-14 04:00:41 +0000551
552//===----------------------------------------------------------------------===//
Andrew Trickd7f890e2013-12-28 21:56:47 +0000553// ScheduleDAGMI - Basic machine instruction scheduling. This is
554// independent of PreRA/PostRA scheduling and involves no extra book-keeping for
555// virtual registers.
556// ===----------------------------------------------------------------------===/
Andrew Trick8823dec2012-03-14 04:00:41 +0000557
David Blaikie422b93d2014-04-21 20:32:32 +0000558// Provide a vtable anchor.
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +0000559ScheduleDAGMI::~ScheduleDAGMI() = default;
Andrew Trick44f750a2013-01-25 04:01:04 +0000560
Andrew Trick85a1d4c2013-04-24 15:54:43 +0000561bool ScheduleDAGMI::canAddEdge(SUnit *SuccSU, SUnit *PredSU) {
562 return SuccSU == &ExitSU || !Topo.IsReachable(PredSU, SuccSU);
563}
564
Andrew Tricka7714a02012-11-12 19:40:10 +0000565bool ScheduleDAGMI::addEdge(SUnit *SuccSU, const SDep &PredDep) {
Andrew Trick263280242012-11-12 19:52:20 +0000566 if (SuccSU != &ExitSU) {
567 // Do not use WillCreateCycle, it assumes SD scheduling.
568 // If Pred is reachable from Succ, then the edge creates a cycle.
569 if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
570 return false;
571 Topo.AddPred(SuccSU, PredDep.getSUnit());
572 }
Andrew Tricka7714a02012-11-12 19:40:10 +0000573 SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
574 // Return true regardless of whether a new edge needed to be inserted.
575 return true;
576}
577
Andrew Trick02a80da2012-03-08 01:41:12 +0000578/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
579/// NumPredsLeft reaches zero, release the successor node.
Andrew Trick61f1a272012-05-24 22:11:09 +0000580///
581/// FIXME: Adjust SuccSU height based on MinLatency.
Andrew Trick8823dec2012-03-14 04:00:41 +0000582void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
Andrew Trick02a80da2012-03-08 01:41:12 +0000583 SUnit *SuccSU = SuccEdge->getSUnit();
584
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000585 if (SuccEdge->isWeak()) {
586 --SuccSU->WeakPredsLeft;
Andrew Tricka7714a02012-11-12 19:40:10 +0000587 if (SuccEdge->isCluster())
588 NextClusterSucc = SuccSU;
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000589 return;
590 }
Andrew Trick02a80da2012-03-08 01:41:12 +0000591#ifndef NDEBUG
592 if (SuccSU->NumPredsLeft == 0) {
593 dbgs() << "*** Scheduling failed! ***\n";
594 SuccSU->dump(this);
595 dbgs() << " has been released too many times!\n";
Craig Topperc0196b12014-04-14 00:51:57 +0000596 llvm_unreachable(nullptr);
Andrew Trick02a80da2012-03-08 01:41:12 +0000597 }
598#endif
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000599 // SU->TopReadyCycle was set to CurrCycle when it was scheduled. However,
600 // CurrCycle may have advanced since then.
601 if (SuccSU->TopReadyCycle < SU->TopReadyCycle + SuccEdge->getLatency())
602 SuccSU->TopReadyCycle = SU->TopReadyCycle + SuccEdge->getLatency();
603
Andrew Trick02a80da2012-03-08 01:41:12 +0000604 --SuccSU->NumPredsLeft;
605 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
Andrew Trick8823dec2012-03-14 04:00:41 +0000606 SchedImpl->releaseTopNode(SuccSU);
Andrew Trick02a80da2012-03-08 01:41:12 +0000607}
608
609/// releaseSuccessors - Call releaseSucc on each of SU's successors.
Andrew Trick8823dec2012-03-14 04:00:41 +0000610void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
Andrew Trick02a80da2012-03-08 01:41:12 +0000611 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
612 I != E; ++I) {
613 releaseSucc(SU, &*I);
614 }
615}
616
Andrew Trick8823dec2012-03-14 04:00:41 +0000617/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
618/// NumSuccsLeft reaches zero, release the predecessor node.
Andrew Trick61f1a272012-05-24 22:11:09 +0000619///
620/// FIXME: Adjust PredSU height based on MinLatency.
Andrew Trick8823dec2012-03-14 04:00:41 +0000621void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
622 SUnit *PredSU = PredEdge->getSUnit();
623
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000624 if (PredEdge->isWeak()) {
625 --PredSU->WeakSuccsLeft;
Andrew Tricka7714a02012-11-12 19:40:10 +0000626 if (PredEdge->isCluster())
627 NextClusterPred = PredSU;
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000628 return;
629 }
Andrew Trick8823dec2012-03-14 04:00:41 +0000630#ifndef NDEBUG
631 if (PredSU->NumSuccsLeft == 0) {
632 dbgs() << "*** Scheduling failed! ***\n";
633 PredSU->dump(this);
634 dbgs() << " has been released too many times!\n";
Craig Topperc0196b12014-04-14 00:51:57 +0000635 llvm_unreachable(nullptr);
Andrew Trick8823dec2012-03-14 04:00:41 +0000636 }
637#endif
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000638 // SU->BotReadyCycle was set to CurrCycle when it was scheduled. However,
639 // CurrCycle may have advanced since then.
640 if (PredSU->BotReadyCycle < SU->BotReadyCycle + PredEdge->getLatency())
641 PredSU->BotReadyCycle = SU->BotReadyCycle + PredEdge->getLatency();
642
Andrew Trick8823dec2012-03-14 04:00:41 +0000643 --PredSU->NumSuccsLeft;
644 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
645 SchedImpl->releaseBottomNode(PredSU);
646}
647
648/// releasePredecessors - Call releasePred on each of SU's predecessors.
649void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
650 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
651 I != E; ++I) {
652 releasePred(SU, &*I);
653 }
654}
655
Andrew Trickd7f890e2013-12-28 21:56:47 +0000656/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
657/// crossing a scheduling boundary. [begin, end) includes all instructions in
658/// the region, including the boundary itself and single-instruction regions
659/// that don't get scheduled.
660void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
661 MachineBasicBlock::iterator begin,
662 MachineBasicBlock::iterator end,
663 unsigned regioninstrs)
664{
665 ScheduleDAGInstrs::enterRegion(bb, begin, end, regioninstrs);
666
667 SchedImpl->initPolicy(begin, end, regioninstrs);
668}
669
Andrew Tricke833e1c2013-04-13 06:07:40 +0000670/// This is normally called from the main scheduler loop but may also be invoked
671/// by the scheduling strategy to perform additional code motion.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000672void ScheduleDAGMI::moveInstruction(
673 MachineInstr *MI, MachineBasicBlock::iterator InsertPos) {
Andrew Trick463b2f12012-05-17 18:35:03 +0000674 // Advance RegionBegin if the first instruction moves down.
Andrew Trick54f7def2012-03-21 04:12:10 +0000675 if (&*RegionBegin == MI)
Andrew Trick463b2f12012-05-17 18:35:03 +0000676 ++RegionBegin;
677
678 // Update the instruction stream.
Andrew Trick8823dec2012-03-14 04:00:41 +0000679 BB->splice(InsertPos, BB, MI);
Andrew Trick463b2f12012-05-17 18:35:03 +0000680
681 // Update LiveIntervals
Andrew Trickd7f890e2013-12-28 21:56:47 +0000682 if (LIS)
Duncan P. N. Exon Smithbe8f8c42016-02-27 20:14:29 +0000683 LIS->handleMove(*MI, /*UpdateFlags=*/true);
Andrew Trick463b2f12012-05-17 18:35:03 +0000684
685 // Recede RegionBegin if an instruction moves above the first.
Andrew Trick8823dec2012-03-14 04:00:41 +0000686 if (RegionBegin == InsertPos)
687 RegionBegin = MI;
688}
689
Andrew Trickde670c02012-03-21 04:12:07 +0000690bool ScheduleDAGMI::checkSchedLimit() {
691#ifndef NDEBUG
692 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
693 CurrentTop = CurrentBottom;
694 return false;
695 }
696 ++NumInstrsScheduled;
697#endif
698 return true;
699}
700
Andrew Trickd7f890e2013-12-28 21:56:47 +0000701/// Per-region scheduling driver, called back from
702/// MachineScheduler::runOnMachineFunction. This is a simplified driver that
703/// does not consider liveness or register pressure. It is useful for PostRA
704/// scheduling and potentially other custom schedulers.
705void ScheduleDAGMI::schedule() {
James Y Knighte72b0db2015-09-18 18:52:20 +0000706 DEBUG(dbgs() << "ScheduleDAGMI::schedule starting\n");
707 DEBUG(SchedImpl->dumpPolicy());
708
Andrew Trickd7f890e2013-12-28 21:56:47 +0000709 // Build the DAG.
710 buildSchedGraph(AA);
711
712 Topo.InitDAGTopologicalSorting();
713
714 postprocessDAG();
715
716 SmallVector<SUnit*, 8> TopRoots, BotRoots;
717 findRootsAndBiasEdges(TopRoots, BotRoots);
718
719 // Initialize the strategy before modifying the DAG.
720 // This may initialize a DFSResult to be used for queue priority.
721 SchedImpl->initialize(this);
722
Matthias Braun69f1d122016-11-11 22:37:28 +0000723 DEBUG(
724 if (EntrySU.getInstr() != nullptr)
725 EntrySU.dumpAll(this);
726 for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
727 SUnits[su].dumpAll(this);
728 if (ExitSU.getInstr() != nullptr)
729 ExitSU.dumpAll(this);
730 );
Andrew Trickd7f890e2013-12-28 21:56:47 +0000731 if (ViewMISchedDAGs) viewGraph();
732
733 // Initialize ready queues now that the DAG and priority data are finalized.
734 initQueues(TopRoots, BotRoots);
735
736 bool IsTopNode = false;
James Y Knighte72b0db2015-09-18 18:52:20 +0000737 while (true) {
738 DEBUG(dbgs() << "** ScheduleDAGMI::schedule picking next node\n");
739 SUnit *SU = SchedImpl->pickNode(IsTopNode);
740 if (!SU) break;
741
Andrew Trickd7f890e2013-12-28 21:56:47 +0000742 assert(!SU->isScheduled && "Node already scheduled");
743 if (!checkSchedLimit())
744 break;
745
746 MachineInstr *MI = SU->getInstr();
747 if (IsTopNode) {
748 assert(SU->isTopReady() && "node still has unscheduled dependencies");
749 if (&*CurrentTop == MI)
750 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
751 else
752 moveInstruction(MI, CurrentTop);
Matthias Braunb550b762016-04-21 01:54:13 +0000753 } else {
Andrew Trickd7f890e2013-12-28 21:56:47 +0000754 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
755 MachineBasicBlock::iterator priorII =
756 priorNonDebug(CurrentBottom, CurrentTop);
757 if (&*priorII == MI)
758 CurrentBottom = priorII;
759 else {
760 if (&*CurrentTop == MI)
761 CurrentTop = nextIfDebug(++CurrentTop, priorII);
762 moveInstruction(MI, CurrentBottom);
763 CurrentBottom = MI;
764 }
765 }
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000766 // Notify the scheduling strategy before updating the DAG.
Andrew Trick491e34a2014-06-12 22:36:28 +0000767 // This sets the scheduled node's ReadyCycle to CurrCycle. When updateQueues
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000768 // runs, it can then use the accurate ReadyCycle time to determine whether
769 // newly released nodes can move to the readyQ.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000770 SchedImpl->schedNode(SU, IsTopNode);
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000771
772 updateQueues(SU, IsTopNode);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000773 }
774 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
775
776 placeDebugValues();
777
778 DEBUG({
779 unsigned BBNum = begin()->getParent()->getNumber();
780 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
781 dumpSchedule();
782 dbgs() << '\n';
783 });
784}
785
786/// Apply each ScheduleDAGMutation step in order.
787void ScheduleDAGMI::postprocessDAG() {
788 for (unsigned i = 0, e = Mutations.size(); i < e; ++i) {
789 Mutations[i]->apply(this);
790 }
791}
792
793void ScheduleDAGMI::
794findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
795 SmallVectorImpl<SUnit*> &BotRoots) {
796 for (std::vector<SUnit>::iterator
797 I = SUnits.begin(), E = SUnits.end(); I != E; ++I) {
798 SUnit *SU = &(*I);
799 assert(!SU->isBoundaryNode() && "Boundary node should not be in SUnits");
800
801 // Order predecessors so DFSResult follows the critical path.
802 SU->biasCriticalPath();
803
804 // A SUnit is ready to top schedule if it has no predecessors.
805 if (!I->NumPredsLeft)
806 TopRoots.push_back(SU);
807 // A SUnit is ready to bottom schedule if it has no successors.
808 if (!I->NumSuccsLeft)
809 BotRoots.push_back(SU);
810 }
811 ExitSU.biasCriticalPath();
812}
813
814/// Identify DAG roots and setup scheduler queues.
815void ScheduleDAGMI::initQueues(ArrayRef<SUnit*> TopRoots,
816 ArrayRef<SUnit*> BotRoots) {
Craig Topperc0196b12014-04-14 00:51:57 +0000817 NextClusterSucc = nullptr;
818 NextClusterPred = nullptr;
Andrew Trickd7f890e2013-12-28 21:56:47 +0000819
820 // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
821 //
822 // Nodes with unreleased weak edges can still be roots.
823 // Release top roots in forward order.
824 for (SmallVectorImpl<SUnit*>::const_iterator
825 I = TopRoots.begin(), E = TopRoots.end(); I != E; ++I) {
826 SchedImpl->releaseTopNode(*I);
827 }
828 // Release bottom roots in reverse order so the higher priority nodes appear
829 // first. This is more natural and slightly more efficient.
830 for (SmallVectorImpl<SUnit*>::const_reverse_iterator
831 I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I) {
832 SchedImpl->releaseBottomNode(*I);
833 }
834
835 releaseSuccessors(&EntrySU);
836 releasePredecessors(&ExitSU);
837
838 SchedImpl->registerRoots();
839
840 // Advance past initial DebugValues.
841 CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
842 CurrentBottom = RegionEnd;
843}
844
845/// Update scheduler queues after scheduling an instruction.
846void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
847 // Release dependent instructions for scheduling.
848 if (IsTopNode)
849 releaseSuccessors(SU);
850 else
851 releasePredecessors(SU);
852
853 SU->isScheduled = true;
854}
855
856/// Reinsert any remaining debug_values, just like the PostRA scheduler.
857void ScheduleDAGMI::placeDebugValues() {
858 // If first instruction was a DBG_VALUE then put it back.
859 if (FirstDbgValue) {
860 BB->splice(RegionBegin, BB, FirstDbgValue);
861 RegionBegin = FirstDbgValue;
862 }
863
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +0000864 for (std::vector<std::pair<MachineInstr *, MachineInstr *>>::iterator
Andrew Trickd7f890e2013-12-28 21:56:47 +0000865 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000866 std::pair<MachineInstr *, MachineInstr *> P = *std::prev(DI);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000867 MachineInstr *DbgValue = P.first;
868 MachineBasicBlock::iterator OrigPrevMI = P.second;
869 if (&*RegionBegin == DbgValue)
870 ++RegionBegin;
871 BB->splice(++OrigPrevMI, BB, DbgValue);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000872 if (OrigPrevMI == std::prev(RegionEnd))
Andrew Trickd7f890e2013-12-28 21:56:47 +0000873 RegionEnd = DbgValue;
874 }
875 DbgValues.clear();
Craig Topperc0196b12014-04-14 00:51:57 +0000876 FirstDbgValue = nullptr;
Andrew Trickd7f890e2013-12-28 21:56:47 +0000877}
878
879#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Matthias Braun8c209aa2017-01-28 02:02:38 +0000880LLVM_DUMP_METHOD void ScheduleDAGMI::dumpSchedule() const {
Andrew Trickd7f890e2013-12-28 21:56:47 +0000881 for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
882 if (SUnit *SU = getSUnit(&(*MI)))
883 SU->dump(this);
884 else
885 dbgs() << "Missing SUnit\n";
886 }
887}
888#endif
889
890//===----------------------------------------------------------------------===//
891// ScheduleDAGMILive - Base class for MachineInstr scheduling with LiveIntervals
892// preservation.
893//===----------------------------------------------------------------------===//
894
895ScheduleDAGMILive::~ScheduleDAGMILive() {
896 delete DFSResult;
897}
898
Matthias Braun40639882016-11-11 22:37:31 +0000899void ScheduleDAGMILive::collectVRegUses(SUnit &SU) {
900 const MachineInstr &MI = *SU.getInstr();
901 for (const MachineOperand &MO : MI.operands()) {
902 if (!MO.isReg())
903 continue;
904 if (!MO.readsReg())
905 continue;
906 if (TrackLaneMasks && !MO.isUse())
907 continue;
908
909 unsigned Reg = MO.getReg();
910 if (!TargetRegisterInfo::isVirtualRegister(Reg))
911 continue;
912
913 // Ignore re-defs.
914 if (TrackLaneMasks) {
915 bool FoundDef = false;
916 for (const MachineOperand &MO2 : MI.operands()) {
917 if (MO2.isReg() && MO2.isDef() && MO2.getReg() == Reg && !MO2.isDead()) {
918 FoundDef = true;
919 break;
920 }
921 }
922 if (FoundDef)
923 continue;
924 }
925
926 // Record this local VReg use.
927 VReg2SUnitMultiMap::iterator UI = VRegUses.find(Reg);
928 for (; UI != VRegUses.end(); ++UI) {
929 if (UI->SU == &SU)
930 break;
931 }
932 if (UI == VRegUses.end())
Krzysztof Parzyszek91b5cf82016-12-15 14:36:06 +0000933 VRegUses.insert(VReg2SUnit(Reg, LaneBitmask::getNone(), &SU));
Matthias Braun40639882016-11-11 22:37:31 +0000934 }
935}
936
Andrew Trick88639922012-04-24 17:56:43 +0000937/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
938/// crossing a scheduling boundary. [begin, end) includes all instructions in
939/// the region, including the boundary itself and single-instruction regions
940/// that don't get scheduled.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000941void ScheduleDAGMILive::enterRegion(MachineBasicBlock *bb,
Andrew Trick88639922012-04-24 17:56:43 +0000942 MachineBasicBlock::iterator begin,
943 MachineBasicBlock::iterator end,
Andrew Tricka53e1012013-08-23 17:48:33 +0000944 unsigned regioninstrs)
Andrew Trick88639922012-04-24 17:56:43 +0000945{
Andrew Trickd7f890e2013-12-28 21:56:47 +0000946 // ScheduleDAGMI initializes SchedImpl's per-region policy.
947 ScheduleDAGMI::enterRegion(bb, begin, end, regioninstrs);
Andrew Trick4add42f2012-05-10 21:06:10 +0000948
949 // For convenience remember the end of the liveness region.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000950 LiveRegionEnd = (RegionEnd == bb->end()) ? RegionEnd : std::next(RegionEnd);
Andrew Trick75e411c2013-09-06 17:32:34 +0000951
Andrew Trickb248b4a2013-09-06 17:32:47 +0000952 SUPressureDiffs.clear();
953
Andrew Trick75e411c2013-09-06 17:32:34 +0000954 ShouldTrackPressure = SchedImpl->shouldTrackPressure();
Matthias Braund4f64092016-01-20 00:23:32 +0000955 ShouldTrackLaneMasks = SchedImpl->shouldTrackLaneMasks();
956
Matthias Braunf9acaca2016-05-31 22:38:06 +0000957 assert((!ShouldTrackLaneMasks || ShouldTrackPressure) &&
958 "ShouldTrackLaneMasks requires ShouldTrackPressure");
Andrew Trick4add42f2012-05-10 21:06:10 +0000959}
960
961// Setup the register pressure trackers for the top scheduled top and bottom
962// scheduled regions.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000963void ScheduleDAGMILive::initRegPressure() {
Matthias Braun40639882016-11-11 22:37:31 +0000964 VRegUses.clear();
965 VRegUses.setUniverse(MRI.getNumVirtRegs());
966 for (SUnit &SU : SUnits)
967 collectVRegUses(SU);
968
Matthias Braund4f64092016-01-20 00:23:32 +0000969 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin,
970 ShouldTrackLaneMasks, false);
971 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
972 ShouldTrackLaneMasks, false);
Andrew Trick4add42f2012-05-10 21:06:10 +0000973
974 // Close the RPTracker to finalize live ins.
975 RPTracker.closeRegion();
976
Andrew Trick9c17eab2013-07-30 19:59:12 +0000977 DEBUG(RPTracker.dump());
Andrew Trick79d3eec2012-05-24 22:11:14 +0000978
Andrew Trick4add42f2012-05-10 21:06:10 +0000979 // Initialize the live ins and live outs.
Matthias Braun3e86de12015-09-17 21:12:24 +0000980 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
981 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
Andrew Trick4add42f2012-05-10 21:06:10 +0000982
983 // Close one end of the tracker so we can call
984 // getMaxUpward/DownwardPressureDelta before advancing across any
985 // instructions. This converts currently live regs into live ins/outs.
986 TopRPTracker.closeTop();
987 BotRPTracker.closeBottom();
988
Andrew Trick9c17eab2013-07-30 19:59:12 +0000989 BotRPTracker.initLiveThru(RPTracker);
990 if (!BotRPTracker.getLiveThru().empty()) {
991 TopRPTracker.initLiveThru(BotRPTracker.getLiveThru());
992 DEBUG(dbgs() << "Live Thru: ";
993 dumpRegSetPressure(BotRPTracker.getLiveThru(), TRI));
994 };
995
Andrew Trick2bc74c22013-08-30 04:36:57 +0000996 // For each live out vreg reduce the pressure change associated with other
997 // uses of the same vreg below the live-out reaching def.
Matthias Braun3e86de12015-09-17 21:12:24 +0000998 updatePressureDiffs(RPTracker.getPressure().LiveOutRegs);
Andrew Trick2bc74c22013-08-30 04:36:57 +0000999
Andrew Trick4add42f2012-05-10 21:06:10 +00001000 // Account for liveness generated by the region boundary.
Andrew Trick2bc74c22013-08-30 04:36:57 +00001001 if (LiveRegionEnd != RegionEnd) {
Matthias Braun5d458612016-01-20 00:23:26 +00001002 SmallVector<RegisterMaskPair, 8> LiveUses;
Andrew Trick2bc74c22013-08-30 04:36:57 +00001003 BotRPTracker.recede(&LiveUses);
1004 updatePressureDiffs(LiveUses);
1005 }
Andrew Trick4add42f2012-05-10 21:06:10 +00001006
Matthias Braune6edd482015-11-13 22:30:31 +00001007 DEBUG(
1008 dbgs() << "Top Pressure:\n";
1009 dumpRegSetPressure(TopRPTracker.getRegSetPressureAtPos(), TRI);
1010 dbgs() << "Bottom Pressure:\n";
1011 dumpRegSetPressure(BotRPTracker.getRegSetPressureAtPos(), TRI);
1012 );
1013
Andrew Trick4add42f2012-05-10 21:06:10 +00001014 assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
Andrew Trick22025772012-05-17 18:35:10 +00001015
1016 // Cache the list of excess pressure sets in this region. This will also track
1017 // the max pressure in the scheduled code for these sets.
1018 RegionCriticalPSets.clear();
Jakub Staszakc641ada2013-01-25 21:44:27 +00001019 const std::vector<unsigned> &RegionPressure =
1020 RPTracker.getPressure().MaxSetPressure;
Andrew Trick22025772012-05-17 18:35:10 +00001021 for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
Andrew Trick736dd9a2013-06-21 18:32:58 +00001022 unsigned Limit = RegClassInfo->getRegPressureSetLimit(i);
Andrew Trickb55db582013-06-21 18:33:01 +00001023 if (RegionPressure[i] > Limit) {
1024 DEBUG(dbgs() << TRI->getRegPressureSetName(i)
1025 << " Limit " << Limit
1026 << " Actual " << RegionPressure[i] << "\n");
Andrew Trick1a831342013-08-30 03:49:48 +00001027 RegionCriticalPSets.push_back(PressureChange(i));
Andrew Trickb55db582013-06-21 18:33:01 +00001028 }
Andrew Trick22025772012-05-17 18:35:10 +00001029 }
1030 DEBUG(dbgs() << "Excess PSets: ";
1031 for (unsigned i = 0, e = RegionCriticalPSets.size(); i != e; ++i)
1032 dbgs() << TRI->getRegPressureSetName(
Andrew Trick1a831342013-08-30 03:49:48 +00001033 RegionCriticalPSets[i].getPSet()) << " ";
Andrew Trick22025772012-05-17 18:35:10 +00001034 dbgs() << "\n");
1035}
1036
Andrew Trickd7f890e2013-12-28 21:56:47 +00001037void ScheduleDAGMILive::
Andrew Trickb248b4a2013-09-06 17:32:47 +00001038updateScheduledPressure(const SUnit *SU,
1039 const std::vector<unsigned> &NewMaxPressure) {
1040 const PressureDiff &PDiff = getPressureDiff(SU);
1041 unsigned CritIdx = 0, CritEnd = RegionCriticalPSets.size();
1042 for (PressureDiff::const_iterator I = PDiff.begin(), E = PDiff.end();
1043 I != E; ++I) {
1044 if (!I->isValid())
1045 break;
1046 unsigned ID = I->getPSet();
1047 while (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() < ID)
1048 ++CritIdx;
1049 if (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() == ID) {
1050 if ((int)NewMaxPressure[ID] > RegionCriticalPSets[CritIdx].getUnitInc()
Simon Pilgrim858d8e62017-02-23 12:00:34 +00001051 && NewMaxPressure[ID] <= (unsigned)std::numeric_limits<int16_t>::max())
Andrew Trickb248b4a2013-09-06 17:32:47 +00001052 RegionCriticalPSets[CritIdx].setUnitInc(NewMaxPressure[ID]);
1053 }
1054 unsigned Limit = RegClassInfo->getRegPressureSetLimit(ID);
1055 if (NewMaxPressure[ID] >= Limit - 2) {
1056 DEBUG(dbgs() << " " << TRI->getRegPressureSetName(ID) << ": "
Andrew Trick569dc65a2015-05-17 23:40:31 +00001057 << NewMaxPressure[ID]
1058 << ((NewMaxPressure[ID] > Limit) ? " > " : " <= ") << Limit
1059 << "(+ " << BotRPTracker.getLiveThru()[ID] << " livethru)\n");
Andrew Trickb248b4a2013-09-06 17:32:47 +00001060 }
Andrew Trick22025772012-05-17 18:35:10 +00001061 }
Andrew Trick88639922012-04-24 17:56:43 +00001062}
1063
Andrew Trick2bc74c22013-08-30 04:36:57 +00001064/// Update the PressureDiff array for liveness after scheduling this
1065/// instruction.
Matthias Braun5d458612016-01-20 00:23:26 +00001066void ScheduleDAGMILive::updatePressureDiffs(
1067 ArrayRef<RegisterMaskPair> LiveUses) {
1068 for (const RegisterMaskPair &P : LiveUses) {
Matthias Braun5d458612016-01-20 00:23:26 +00001069 unsigned Reg = P.RegUnit;
Matthias Braund4f64092016-01-20 00:23:32 +00001070 /// FIXME: Currently assuming single-use physregs.
Andrew Trick2bc74c22013-08-30 04:36:57 +00001071 if (!TRI->isVirtualRegister(Reg))
1072 continue;
Andrew Trickffdbefb2013-09-06 17:32:39 +00001073
Matthias Braund4f64092016-01-20 00:23:32 +00001074 if (ShouldTrackLaneMasks) {
1075 // If the register has just become live then other uses won't change
1076 // this fact anymore => decrement pressure.
1077 // If the register has just become dead then other uses make it come
1078 // back to life => increment pressure.
Krzysztof Parzyszekea9f8ce2016-12-16 19:11:56 +00001079 bool Decrement = P.LaneMask.any();
Matthias Braund4f64092016-01-20 00:23:32 +00001080
1081 for (const VReg2SUnit &V2SU
1082 : make_range(VRegUses.find(Reg), VRegUses.end())) {
1083 SUnit &SU = *V2SU.SU;
1084 if (SU.isScheduled || &SU == &ExitSU)
1085 continue;
1086
1087 PressureDiff &PDiff = getPressureDiff(&SU);
1088 PDiff.addPressureChange(Reg, Decrement, &MRI);
1089 DEBUG(
1090 dbgs() << " UpdateRegP: SU(" << SU.NodeNum << ") "
1091 << PrintReg(Reg, TRI) << ':' << PrintLaneMask(P.LaneMask)
1092 << ' ' << *SU.getInstr();
1093 dbgs() << " to ";
1094 PDiff.dump(*TRI);
1095 );
1096 }
1097 } else {
Krzysztof Parzyszekea9f8ce2016-12-16 19:11:56 +00001098 assert(P.LaneMask.any());
Matthias Braund4f64092016-01-20 00:23:32 +00001099 DEBUG(dbgs() << " LiveReg: " << PrintVRegOrUnit(Reg, TRI) << "\n");
1100 // This may be called before CurrentBottom has been initialized. However,
1101 // BotRPTracker must have a valid position. We want the value live into the
1102 // instruction or live out of the block, so ask for the previous
1103 // instruction's live-out.
1104 const LiveInterval &LI = LIS->getInterval(Reg);
1105 VNInfo *VNI;
1106 MachineBasicBlock::const_iterator I =
1107 nextIfDebug(BotRPTracker.getPos(), BB->end());
1108 if (I == BB->end())
1109 VNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
1110 else {
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001111 LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(*I));
Matthias Braund4f64092016-01-20 00:23:32 +00001112 VNI = LRQ.valueIn();
1113 }
1114 // RegisterPressureTracker guarantees that readsReg is true for LiveUses.
1115 assert(VNI && "No live value at use.");
1116 for (const VReg2SUnit &V2SU
1117 : make_range(VRegUses.find(Reg), VRegUses.end())) {
1118 SUnit *SU = V2SU.SU;
1119 // If this use comes before the reaching def, it cannot be a last use,
1120 // so decrease its pressure change.
1121 if (!SU->isScheduled && SU != &ExitSU) {
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001122 LiveQueryResult LRQ =
1123 LI.Query(LIS->getInstructionIndex(*SU->getInstr()));
Matthias Braund4f64092016-01-20 00:23:32 +00001124 if (LRQ.valueIn() == VNI) {
1125 PressureDiff &PDiff = getPressureDiff(SU);
1126 PDiff.addPressureChange(Reg, true, &MRI);
1127 DEBUG(
1128 dbgs() << " UpdateRegP: SU(" << SU->NodeNum << ") "
1129 << *SU->getInstr();
1130 dbgs() << " to ";
1131 PDiff.dump(*TRI);
1132 );
1133 }
Matthias Braun9198c672015-11-06 20:59:02 +00001134 }
Andrew Trick2bc74c22013-08-30 04:36:57 +00001135 }
1136 }
1137 }
1138}
1139
Andrew Trick8823dec2012-03-14 04:00:41 +00001140/// schedule - Called back from MachineScheduler::runOnMachineFunction
Andrew Trick88639922012-04-24 17:56:43 +00001141/// after setting up the current scheduling region. [RegionBegin, RegionEnd)
1142/// only includes instructions that have DAG nodes, not scheduling boundaries.
Andrew Trick7a8e1002012-09-11 00:39:15 +00001143///
1144/// This is a skeletal driver, with all the functionality pushed into helpers,
Nick Lewycky06b0ea22015-08-18 22:41:58 +00001145/// so that it can be easily extended by experimental schedulers. Generally,
Andrew Trick7a8e1002012-09-11 00:39:15 +00001146/// implementing MachineSchedStrategy should be sufficient to implement a new
1147/// scheduling algorithm. However, if a scheduler further subclasses
Andrew Trickd7f890e2013-12-28 21:56:47 +00001148/// ScheduleDAGMILive then it will want to override this virtual method in order
1149/// to update any specialized state.
1150void ScheduleDAGMILive::schedule() {
James Y Knighte72b0db2015-09-18 18:52:20 +00001151 DEBUG(dbgs() << "ScheduleDAGMILive::schedule starting\n");
1152 DEBUG(SchedImpl->dumpPolicy());
Andrew Trick7a8e1002012-09-11 00:39:15 +00001153 buildDAGWithRegPressure();
1154
Andrew Tricka7714a02012-11-12 19:40:10 +00001155 Topo.InitDAGTopologicalSorting();
1156
Andrew Tricka2733e92012-09-14 17:22:42 +00001157 postprocessDAG();
1158
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001159 SmallVector<SUnit*, 8> TopRoots, BotRoots;
1160 findRootsAndBiasEdges(TopRoots, BotRoots);
1161
1162 // Initialize the strategy before modifying the DAG.
1163 // This may initialize a DFSResult to be used for queue priority.
1164 SchedImpl->initialize(this);
1165
Matthias Braun9198c672015-11-06 20:59:02 +00001166 DEBUG(
Matthias Braun69f1d122016-11-11 22:37:28 +00001167 if (EntrySU.getInstr() != nullptr)
1168 EntrySU.dumpAll(this);
Matthias Braun9198c672015-11-06 20:59:02 +00001169 for (const SUnit &SU : SUnits) {
1170 SU.dumpAll(this);
1171 if (ShouldTrackPressure) {
1172 dbgs() << " Pressure Diff : ";
1173 getPressureDiff(&SU).dump(*TRI);
1174 }
1175 dbgs() << '\n';
1176 }
Matthias Braun69f1d122016-11-11 22:37:28 +00001177 if (ExitSU.getInstr() != nullptr)
1178 ExitSU.dumpAll(this);
Matthias Braun9198c672015-11-06 20:59:02 +00001179 );
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001180 if (ViewMISchedDAGs) viewGraph();
Andrew Trick7a8e1002012-09-11 00:39:15 +00001181
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001182 // Initialize ready queues now that the DAG and priority data are finalized.
1183 initQueues(TopRoots, BotRoots);
Andrew Trick7a8e1002012-09-11 00:39:15 +00001184
1185 bool IsTopNode = false;
James Y Knighte72b0db2015-09-18 18:52:20 +00001186 while (true) {
1187 DEBUG(dbgs() << "** ScheduleDAGMILive::schedule picking next node\n");
1188 SUnit *SU = SchedImpl->pickNode(IsTopNode);
1189 if (!SU) break;
1190
Andrew Trick984d98b2012-10-08 18:53:53 +00001191 assert(!SU->isScheduled && "Node already scheduled");
Andrew Trick7a8e1002012-09-11 00:39:15 +00001192 if (!checkSchedLimit())
1193 break;
1194
1195 scheduleMI(SU, IsTopNode);
1196
Andrew Trickd7f890e2013-12-28 21:56:47 +00001197 if (DFSResult) {
1198 unsigned SubtreeID = DFSResult->getSubtreeID(SU);
1199 if (!ScheduledTrees.test(SubtreeID)) {
1200 ScheduledTrees.set(SubtreeID);
1201 DFSResult->scheduleTree(SubtreeID);
1202 SchedImpl->scheduleTree(SubtreeID);
1203 }
1204 }
1205
1206 // Notify the scheduling strategy after updating the DAG.
1207 SchedImpl->schedNode(SU, IsTopNode);
Andrew Trick43adfb32015-03-27 06:10:13 +00001208
1209 updateQueues(SU, IsTopNode);
Andrew Trick7a8e1002012-09-11 00:39:15 +00001210 }
1211 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
1212
1213 placeDebugValues();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001214
1215 DEBUG({
Andrew Trickcf7e6972012-11-28 03:42:47 +00001216 unsigned BBNum = begin()->getParent()->getNumber();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001217 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
1218 dumpSchedule();
1219 dbgs() << '\n';
1220 });
Andrew Trick7a8e1002012-09-11 00:39:15 +00001221}
1222
1223/// Build the DAG and setup three register pressure trackers.
Andrew Trickd7f890e2013-12-28 21:56:47 +00001224void ScheduleDAGMILive::buildDAGWithRegPressure() {
Andrew Trickb6e74712013-09-04 20:59:59 +00001225 if (!ShouldTrackPressure) {
1226 RPTracker.reset();
1227 RegionCriticalPSets.clear();
1228 buildSchedGraph(AA);
1229 return;
1230 }
1231
Andrew Trick4add42f2012-05-10 21:06:10 +00001232 // Initialize the register pressure tracker used by buildSchedGraph.
Andrew Trick9c17eab2013-07-30 19:59:12 +00001233 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
Matthias Braund4f64092016-01-20 00:23:32 +00001234 ShouldTrackLaneMasks, /*TrackUntiedDefs=*/true);
Andrew Trick88639922012-04-24 17:56:43 +00001235
Andrew Trick4add42f2012-05-10 21:06:10 +00001236 // Account for liveness generate by the region boundary.
1237 if (LiveRegionEnd != RegionEnd)
1238 RPTracker.recede();
1239
1240 // Build the DAG, and compute current register pressure.
Matthias Braund4f64092016-01-20 00:23:32 +00001241 buildSchedGraph(AA, &RPTracker, &SUPressureDiffs, LIS, ShouldTrackLaneMasks);
Andrew Trick02a80da2012-03-08 01:41:12 +00001242
Andrew Trick4add42f2012-05-10 21:06:10 +00001243 // Initialize top/bottom trackers after computing region pressure.
1244 initRegPressure();
Andrew Trick7a8e1002012-09-11 00:39:15 +00001245}
Andrew Trick4add42f2012-05-10 21:06:10 +00001246
Andrew Trickd7f890e2013-12-28 21:56:47 +00001247void ScheduleDAGMILive::computeDFSResult() {
Andrew Trick44f750a2013-01-25 04:01:04 +00001248 if (!DFSResult)
1249 DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize);
1250 DFSResult->clear();
Andrew Trick44f750a2013-01-25 04:01:04 +00001251 ScheduledTrees.clear();
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001252 DFSResult->resize(SUnits.size());
1253 DFSResult->compute(SUnits);
Andrew Trick44f750a2013-01-25 04:01:04 +00001254 ScheduledTrees.resize(DFSResult->getNumSubtrees());
1255}
1256
Andrew Trick483f4192013-08-29 18:04:49 +00001257/// Compute the max cyclic critical path through the DAG. The scheduling DAG
1258/// only provides the critical path for single block loops. To handle loops that
1259/// span blocks, we could use the vreg path latencies provided by
1260/// MachineTraceMetrics instead. However, MachineTraceMetrics is not currently
1261/// available for use in the scheduler.
1262///
1263/// The cyclic path estimation identifies a def-use pair that crosses the back
Andrew Trickef80f502013-08-30 02:02:12 +00001264/// edge and considers the depth and height of the nodes. For example, consider
Andrew Trick483f4192013-08-29 18:04:49 +00001265/// the following instruction sequence where each instruction has unit latency
1266/// and defines an epomymous virtual register:
1267///
1268/// a->b(a,c)->c(b)->d(c)->exit
1269///
1270/// The cyclic critical path is a two cycles: b->c->b
1271/// The acyclic critical path is four cycles: a->b->c->d->exit
1272/// LiveOutHeight = height(c) = len(c->d->exit) = 2
1273/// LiveOutDepth = depth(c) + 1 = len(a->b->c) + 1 = 3
1274/// LiveInHeight = height(b) + 1 = len(b->c->d->exit) + 1 = 4
1275/// LiveInDepth = depth(b) = len(a->b) = 1
1276///
1277/// LiveOutDepth - LiveInDepth = 3 - 1 = 2
1278/// LiveInHeight - LiveOutHeight = 4 - 2 = 2
1279/// CyclicCriticalPath = min(2, 2) = 2
Andrew Trickd7f890e2013-12-28 21:56:47 +00001280///
1281/// This could be relevant to PostRA scheduling, but is currently implemented
1282/// assuming LiveIntervals.
1283unsigned ScheduleDAGMILive::computeCyclicCriticalPath() {
Andrew Trick483f4192013-08-29 18:04:49 +00001284 // This only applies to single block loop.
1285 if (!BB->isSuccessor(BB))
1286 return 0;
1287
1288 unsigned MaxCyclicLatency = 0;
1289 // Visit each live out vreg def to find def/use pairs that cross iterations.
Matthias Braun5d458612016-01-20 00:23:26 +00001290 for (const RegisterMaskPair &P : RPTracker.getPressure().LiveOutRegs) {
1291 unsigned Reg = P.RegUnit;
Andrew Trick483f4192013-08-29 18:04:49 +00001292 if (!TRI->isVirtualRegister(Reg))
1293 continue;
1294 const LiveInterval &LI = LIS->getInterval(Reg);
1295 const VNInfo *DefVNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
1296 if (!DefVNI)
1297 continue;
1298
1299 MachineInstr *DefMI = LIS->getInstructionFromIndex(DefVNI->def);
1300 const SUnit *DefSU = getSUnit(DefMI);
1301 if (!DefSU)
1302 continue;
1303
1304 unsigned LiveOutHeight = DefSU->getHeight();
1305 unsigned LiveOutDepth = DefSU->getDepth() + DefSU->Latency;
1306 // Visit all local users of the vreg def.
Matthias Braunb0c437b2015-10-29 03:57:17 +00001307 for (const VReg2SUnit &V2SU
1308 : make_range(VRegUses.find(Reg), VRegUses.end())) {
1309 SUnit *SU = V2SU.SU;
1310 if (SU == &ExitSU)
Andrew Trick483f4192013-08-29 18:04:49 +00001311 continue;
1312
1313 // Only consider uses of the phi.
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001314 LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(*SU->getInstr()));
Andrew Trick483f4192013-08-29 18:04:49 +00001315 if (!LRQ.valueIn()->isPHIDef())
1316 continue;
1317
1318 // Assume that a path spanning two iterations is a cycle, which could
1319 // overestimate in strange cases. This allows cyclic latency to be
1320 // estimated as the minimum slack of the vreg's depth or height.
1321 unsigned CyclicLatency = 0;
Matthias Braunb0c437b2015-10-29 03:57:17 +00001322 if (LiveOutDepth > SU->getDepth())
1323 CyclicLatency = LiveOutDepth - SU->getDepth();
Andrew Trick483f4192013-08-29 18:04:49 +00001324
Matthias Braunb0c437b2015-10-29 03:57:17 +00001325 unsigned LiveInHeight = SU->getHeight() + DefSU->Latency;
Andrew Trick483f4192013-08-29 18:04:49 +00001326 if (LiveInHeight > LiveOutHeight) {
1327 if (LiveInHeight - LiveOutHeight < CyclicLatency)
1328 CyclicLatency = LiveInHeight - LiveOutHeight;
Matthias Braunb550b762016-04-21 01:54:13 +00001329 } else
Andrew Trick483f4192013-08-29 18:04:49 +00001330 CyclicLatency = 0;
1331
1332 DEBUG(dbgs() << "Cyclic Path: SU(" << DefSU->NodeNum << ") -> SU("
Matthias Braunb0c437b2015-10-29 03:57:17 +00001333 << SU->NodeNum << ") = " << CyclicLatency << "c\n");
Andrew Trick483f4192013-08-29 18:04:49 +00001334 if (CyclicLatency > MaxCyclicLatency)
1335 MaxCyclicLatency = CyclicLatency;
1336 }
1337 }
1338 DEBUG(dbgs() << "Cyclic Critical Path: " << MaxCyclicLatency << "c\n");
1339 return MaxCyclicLatency;
1340}
1341
Krzysztof Parzyszek7ea9a522016-04-28 19:17:44 +00001342/// Release ExitSU predecessors and setup scheduler queues. Re-position
1343/// the Top RP tracker in case the region beginning has changed.
1344void ScheduleDAGMILive::initQueues(ArrayRef<SUnit*> TopRoots,
1345 ArrayRef<SUnit*> BotRoots) {
1346 ScheduleDAGMI::initQueues(TopRoots, BotRoots);
1347 if (ShouldTrackPressure) {
1348 assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
1349 TopRPTracker.setPos(CurrentTop);
1350 }
1351}
1352
Andrew Trick7a8e1002012-09-11 00:39:15 +00001353/// Move an instruction and update register pressure.
Andrew Trickd7f890e2013-12-28 21:56:47 +00001354void ScheduleDAGMILive::scheduleMI(SUnit *SU, bool IsTopNode) {
Andrew Trick7a8e1002012-09-11 00:39:15 +00001355 // Move the instruction to its new location in the instruction stream.
1356 MachineInstr *MI = SU->getInstr();
Andrew Trick02a80da2012-03-08 01:41:12 +00001357
Andrew Trick7a8e1002012-09-11 00:39:15 +00001358 if (IsTopNode) {
1359 assert(SU->isTopReady() && "node still has unscheduled dependencies");
1360 if (&*CurrentTop == MI)
1361 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
Andrew Trick8823dec2012-03-14 04:00:41 +00001362 else {
Andrew Trick7a8e1002012-09-11 00:39:15 +00001363 moveInstruction(MI, CurrentTop);
1364 TopRPTracker.setPos(MI);
Andrew Trick8823dec2012-03-14 04:00:41 +00001365 }
Andrew Trickc3ea0052012-04-24 18:04:37 +00001366
Andrew Trickb6e74712013-09-04 20:59:59 +00001367 if (ShouldTrackPressure) {
1368 // Update top scheduled pressure.
Matthias Braund4f64092016-01-20 00:23:32 +00001369 RegisterOperands RegOpers;
1370 RegOpers.collect(*MI, *TRI, MRI, ShouldTrackLaneMasks, false);
1371 if (ShouldTrackLaneMasks) {
1372 // Adjust liveness and add missing dead+read-undef flags.
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001373 SlotIndex SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot();
Matthias Braund4f64092016-01-20 00:23:32 +00001374 RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx, MI);
1375 } else {
1376 // Adjust for missing dead-def flags.
1377 RegOpers.detectDeadDefs(*MI, *LIS);
1378 }
1379
1380 TopRPTracker.advance(RegOpers);
Andrew Trickb6e74712013-09-04 20:59:59 +00001381 assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
Matthias Braun9198c672015-11-06 20:59:02 +00001382 DEBUG(
1383 dbgs() << "Top Pressure:\n";
1384 dumpRegSetPressure(TopRPTracker.getRegSetPressureAtPos(), TRI);
1385 );
1386
Andrew Trickb248b4a2013-09-06 17:32:47 +00001387 updateScheduledPressure(SU, TopRPTracker.getPressure().MaxSetPressure);
Andrew Trickb6e74712013-09-04 20:59:59 +00001388 }
Matthias Braunb550b762016-04-21 01:54:13 +00001389 } else {
Andrew Trick7a8e1002012-09-11 00:39:15 +00001390 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
1391 MachineBasicBlock::iterator priorII =
1392 priorNonDebug(CurrentBottom, CurrentTop);
1393 if (&*priorII == MI)
1394 CurrentBottom = priorII;
1395 else {
1396 if (&*CurrentTop == MI) {
1397 CurrentTop = nextIfDebug(++CurrentTop, priorII);
1398 TopRPTracker.setPos(CurrentTop);
1399 }
1400 moveInstruction(MI, CurrentBottom);
1401 CurrentBottom = MI;
1402 }
Andrew Trickb6e74712013-09-04 20:59:59 +00001403 if (ShouldTrackPressure) {
Matthias Braund4f64092016-01-20 00:23:32 +00001404 RegisterOperands RegOpers;
1405 RegOpers.collect(*MI, *TRI, MRI, ShouldTrackLaneMasks, false);
1406 if (ShouldTrackLaneMasks) {
1407 // Adjust liveness and add missing dead+read-undef flags.
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001408 SlotIndex SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot();
Matthias Braund4f64092016-01-20 00:23:32 +00001409 RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx, MI);
1410 } else {
1411 // Adjust for missing dead-def flags.
1412 RegOpers.detectDeadDefs(*MI, *LIS);
1413 }
1414
1415 BotRPTracker.recedeSkipDebugValues();
Matthias Braun5d458612016-01-20 00:23:26 +00001416 SmallVector<RegisterMaskPair, 8> LiveUses;
Matthias Braund4f64092016-01-20 00:23:32 +00001417 BotRPTracker.recede(RegOpers, &LiveUses);
Andrew Trickb6e74712013-09-04 20:59:59 +00001418 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
Matthias Braun9198c672015-11-06 20:59:02 +00001419 DEBUG(
1420 dbgs() << "Bottom Pressure:\n";
1421 dumpRegSetPressure(BotRPTracker.getRegSetPressureAtPos(), TRI);
1422 );
1423
Andrew Trickb248b4a2013-09-06 17:32:47 +00001424 updateScheduledPressure(SU, BotRPTracker.getPressure().MaxSetPressure);
Andrew Trickb6e74712013-09-04 20:59:59 +00001425 updatePressureDiffs(LiveUses);
Andrew Trickb6e74712013-09-04 20:59:59 +00001426 }
Andrew Trick7a8e1002012-09-11 00:39:15 +00001427 }
1428}
1429
Andrew Trick263280242012-11-12 19:52:20 +00001430//===----------------------------------------------------------------------===//
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001431// BaseMemOpClusterMutation - DAG post-processing to cluster loads or stores.
Andrew Trick263280242012-11-12 19:52:20 +00001432//===----------------------------------------------------------------------===//
1433
Andrew Tricka7714a02012-11-12 19:40:10 +00001434namespace {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001435
Andrew Tricka7714a02012-11-12 19:40:10 +00001436/// \brief Post-process the DAG to create cluster edges between neighboring
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001437/// loads or between neighboring stores.
1438class BaseMemOpClusterMutation : public ScheduleDAGMutation {
1439 struct MemOpInfo {
Andrew Tricka7714a02012-11-12 19:40:10 +00001440 SUnit *SU;
1441 unsigned BaseReg;
Chad Rosierc27a18f2016-03-09 16:00:35 +00001442 int64_t Offset;
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001443
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001444 MemOpInfo(SUnit *su, unsigned reg, int64_t ofs)
1445 : SU(su), BaseReg(reg), Offset(ofs) {}
Benjamin Kramerb0f74b22014-03-07 21:35:39 +00001446
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001447 bool operator<(const MemOpInfo&RHS) const {
Mandeep Singh Grange82678a2016-10-18 00:11:19 +00001448 return std::tie(BaseReg, Offset, SU->NodeNum) <
1449 std::tie(RHS.BaseReg, RHS.Offset, RHS.SU->NodeNum);
Benjamin Kramerb0f74b22014-03-07 21:35:39 +00001450 }
Andrew Tricka7714a02012-11-12 19:40:10 +00001451 };
Andrew Tricka7714a02012-11-12 19:40:10 +00001452
1453 const TargetInstrInfo *TII;
1454 const TargetRegisterInfo *TRI;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001455 bool IsLoad;
1456
Andrew Tricka7714a02012-11-12 19:40:10 +00001457public:
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001458 BaseMemOpClusterMutation(const TargetInstrInfo *tii,
1459 const TargetRegisterInfo *tri, bool IsLoad)
1460 : TII(tii), TRI(tri), IsLoad(IsLoad) {}
Andrew Tricka7714a02012-11-12 19:40:10 +00001461
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001462 void apply(ScheduleDAGInstrs *DAGInstrs) override;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001463
Andrew Tricka7714a02012-11-12 19:40:10 +00001464protected:
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001465 void clusterNeighboringMemOps(ArrayRef<SUnit *> MemOps, ScheduleDAGMI *DAG);
1466};
1467
1468class StoreClusterMutation : public BaseMemOpClusterMutation {
1469public:
1470 StoreClusterMutation(const TargetInstrInfo *tii,
1471 const TargetRegisterInfo *tri)
1472 : BaseMemOpClusterMutation(tii, tri, false) {}
1473};
1474
1475class LoadClusterMutation : public BaseMemOpClusterMutation {
1476public:
1477 LoadClusterMutation(const TargetInstrInfo *tii, const TargetRegisterInfo *tri)
1478 : BaseMemOpClusterMutation(tii, tri, true) {}
Andrew Tricka7714a02012-11-12 19:40:10 +00001479};
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001480
1481} // end anonymous namespace
Andrew Tricka7714a02012-11-12 19:40:10 +00001482
Tom Stellard68726a52016-08-19 19:59:18 +00001483namespace llvm {
1484
1485std::unique_ptr<ScheduleDAGMutation>
1486createLoadClusterDAGMutation(const TargetInstrInfo *TII,
1487 const TargetRegisterInfo *TRI) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001488 return EnableMemOpCluster ? llvm::make_unique<LoadClusterMutation>(TII, TRI)
Matthias Braun115efcd2016-11-28 20:11:54 +00001489 : nullptr;
Tom Stellard68726a52016-08-19 19:59:18 +00001490}
1491
1492std::unique_ptr<ScheduleDAGMutation>
1493createStoreClusterDAGMutation(const TargetInstrInfo *TII,
1494 const TargetRegisterInfo *TRI) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001495 return EnableMemOpCluster ? llvm::make_unique<StoreClusterMutation>(TII, TRI)
Matthias Braun115efcd2016-11-28 20:11:54 +00001496 : nullptr;
Tom Stellard68726a52016-08-19 19:59:18 +00001497}
1498
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001499} // end namespace llvm
Tom Stellard68726a52016-08-19 19:59:18 +00001500
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001501void BaseMemOpClusterMutation::clusterNeighboringMemOps(
1502 ArrayRef<SUnit *> MemOps, ScheduleDAGMI *DAG) {
1503 SmallVector<MemOpInfo, 32> MemOpRecords;
1504 for (unsigned Idx = 0, End = MemOps.size(); Idx != End; ++Idx) {
1505 SUnit *SU = MemOps[Idx];
Andrew Tricka7714a02012-11-12 19:40:10 +00001506 unsigned BaseReg;
Chad Rosierc27a18f2016-03-09 16:00:35 +00001507 int64_t Offset;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001508 if (TII->getMemOpBaseRegImmOfs(*SU->getInstr(), BaseReg, Offset, TRI))
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001509 MemOpRecords.push_back(MemOpInfo(SU, BaseReg, Offset));
Andrew Tricka7714a02012-11-12 19:40:10 +00001510 }
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001511 if (MemOpRecords.size() < 2)
Andrew Tricka7714a02012-11-12 19:40:10 +00001512 return;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001513
1514 std::sort(MemOpRecords.begin(), MemOpRecords.end());
Andrew Tricka7714a02012-11-12 19:40:10 +00001515 unsigned ClusterLength = 1;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001516 for (unsigned Idx = 0, End = MemOpRecords.size(); Idx < (End - 1); ++Idx) {
1517 if (MemOpRecords[Idx].BaseReg != MemOpRecords[Idx+1].BaseReg) {
Andrew Tricka7714a02012-11-12 19:40:10 +00001518 ClusterLength = 1;
1519 continue;
1520 }
1521
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001522 SUnit *SUa = MemOpRecords[Idx].SU;
1523 SUnit *SUb = MemOpRecords[Idx+1].SU;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001524 if (TII->shouldClusterMemOps(*SUa->getInstr(), *SUb->getInstr(),
1525 ClusterLength) &&
1526 DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001527 DEBUG(dbgs() << "Cluster ld/st SU(" << SUa->NodeNum << ") - SU("
Andrew Tricka7714a02012-11-12 19:40:10 +00001528 << SUb->NodeNum << ")\n");
1529 // Copy successor edges from SUa to SUb. Interleaving computation
1530 // dependent on SUa can prevent load combining due to register reuse.
1531 // Predecessor edges do not need to be copied from SUb to SUa since nearby
1532 // loads should have effectively the same inputs.
1533 for (SUnit::const_succ_iterator
1534 SI = SUa->Succs.begin(), SE = SUa->Succs.end(); SI != SE; ++SI) {
1535 if (SI->getSUnit() == SUb)
1536 continue;
1537 DEBUG(dbgs() << " Copy Succ SU(" << SI->getSUnit()->NodeNum << ")\n");
1538 DAG->addEdge(SI->getSUnit(), SDep(SUb, SDep::Artificial));
1539 }
1540 ++ClusterLength;
Matthias Braunb550b762016-04-21 01:54:13 +00001541 } else
Andrew Tricka7714a02012-11-12 19:40:10 +00001542 ClusterLength = 1;
1543 }
1544}
1545
1546/// \brief Callback from DAG postProcessing to create cluster edges for loads.
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001547void BaseMemOpClusterMutation::apply(ScheduleDAGInstrs *DAGInstrs) {
1548
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001549 ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs);
1550
Andrew Tricka7714a02012-11-12 19:40:10 +00001551 // Map DAG NodeNum to store chain ID.
1552 DenseMap<unsigned, unsigned> StoreChainIDs;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001553 // Map each store chain to a set of dependent MemOps.
Andrew Tricka7714a02012-11-12 19:40:10 +00001554 SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
1555 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
1556 SUnit *SU = &DAG->SUnits[Idx];
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001557 if ((IsLoad && !SU->getInstr()->mayLoad()) ||
1558 (!IsLoad && !SU->getInstr()->mayStore()))
Andrew Tricka7714a02012-11-12 19:40:10 +00001559 continue;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001560
Andrew Tricka7714a02012-11-12 19:40:10 +00001561 unsigned ChainPredID = DAG->SUnits.size();
1562 for (SUnit::const_pred_iterator
1563 PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
1564 if (PI->isCtrl()) {
1565 ChainPredID = PI->getSUnit()->NodeNum;
1566 break;
1567 }
1568 }
1569 // Check if this chain-like pred has been seen
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001570 // before. ChainPredID==MaxNodeID at the top of the schedule.
Andrew Tricka7714a02012-11-12 19:40:10 +00001571 unsigned NumChains = StoreChainDependents.size();
1572 std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
1573 StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
1574 if (Result.second)
1575 StoreChainDependents.resize(NumChains + 1);
1576 StoreChainDependents[Result.first->second].push_back(SU);
1577 }
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001578
Andrew Tricka7714a02012-11-12 19:40:10 +00001579 // Iterate over the store chains.
1580 for (unsigned Idx = 0, End = StoreChainDependents.size(); Idx != End; ++Idx)
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001581 clusterNeighboringMemOps(StoreChainDependents[Idx], DAG);
Andrew Tricka7714a02012-11-12 19:40:10 +00001582}
1583
Andrew Trick02a80da2012-03-08 01:41:12 +00001584//===----------------------------------------------------------------------===//
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001585// CopyConstrain - DAG post-processing to encourage copy elimination.
1586//===----------------------------------------------------------------------===//
1587
1588namespace {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001589
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001590/// \brief Post-process the DAG to create weak edges from all uses of a copy to
1591/// the one use that defines the copy's source vreg, most likely an induction
1592/// variable increment.
1593class CopyConstrain : public ScheduleDAGMutation {
1594 // Transient state.
1595 SlotIndex RegionBeginIdx;
Andrew Trick2e875172013-04-24 23:19:56 +00001596 // RegionEndIdx is the slot index of the last non-debug instruction in the
1597 // scheduling region. So we may have RegionBeginIdx == RegionEndIdx.
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001598 SlotIndex RegionEndIdx;
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001599
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001600public:
1601 CopyConstrain(const TargetInstrInfo *, const TargetRegisterInfo *) {}
1602
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001603 void apply(ScheduleDAGInstrs *DAGInstrs) override;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001604
1605protected:
Andrew Trickd7f890e2013-12-28 21:56:47 +00001606 void constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG);
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001607};
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001608
1609} // end anonymous namespace
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001610
Tom Stellard68726a52016-08-19 19:59:18 +00001611namespace llvm {
1612
1613std::unique_ptr<ScheduleDAGMutation>
1614createCopyConstrainDAGMutation(const TargetInstrInfo *TII,
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001615 const TargetRegisterInfo *TRI) {
1616 return llvm::make_unique<CopyConstrain>(TII, TRI);
Tom Stellard68726a52016-08-19 19:59:18 +00001617}
1618
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001619} // end namespace llvm
Tom Stellard68726a52016-08-19 19:59:18 +00001620
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001621/// constrainLocalCopy handles two possibilities:
1622/// 1) Local src:
1623/// I0: = dst
1624/// I1: src = ...
1625/// I2: = dst
1626/// I3: dst = src (copy)
1627/// (create pred->succ edges I0->I1, I2->I1)
1628///
1629/// 2) Local copy:
1630/// I0: dst = src (copy)
1631/// I1: = dst
1632/// I2: src = ...
1633/// I3: = dst
1634/// (create pred->succ edges I1->I2, I3->I2)
1635///
1636/// Although the MachineScheduler is currently constrained to single blocks,
1637/// this algorithm should handle extended blocks. An EBB is a set of
1638/// contiguously numbered blocks such that the previous block in the EBB is
1639/// always the single predecessor.
Andrew Trickd7f890e2013-12-28 21:56:47 +00001640void CopyConstrain::constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG) {
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001641 LiveIntervals *LIS = DAG->getLIS();
1642 MachineInstr *Copy = CopySU->getInstr();
1643
1644 // Check for pure vreg copies.
Matthias Braun7511abd2016-04-04 21:23:46 +00001645 const MachineOperand &SrcOp = Copy->getOperand(1);
1646 unsigned SrcReg = SrcOp.getReg();
1647 if (!TargetRegisterInfo::isVirtualRegister(SrcReg) || !SrcOp.readsReg())
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001648 return;
1649
Matthias Braun7511abd2016-04-04 21:23:46 +00001650 const MachineOperand &DstOp = Copy->getOperand(0);
1651 unsigned DstReg = DstOp.getReg();
1652 if (!TargetRegisterInfo::isVirtualRegister(DstReg) || DstOp.isDead())
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001653 return;
1654
1655 // Check if either the dest or source is local. If it's live across a back
1656 // edge, it's not local. Note that if both vregs are live across the back
1657 // edge, we cannot successfully contrain the copy without cyclic scheduling.
Michael Kuperstein54c61ed2015-01-19 07:30:47 +00001658 // If both the copy's source and dest are local live intervals, then we
1659 // should treat the dest as the global for the purpose of adding
1660 // constraints. This adds edges from source's other uses to the copy.
1661 unsigned LocalReg = SrcReg;
1662 unsigned GlobalReg = DstReg;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001663 LiveInterval *LocalLI = &LIS->getInterval(LocalReg);
1664 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx)) {
Michael Kuperstein54c61ed2015-01-19 07:30:47 +00001665 LocalReg = DstReg;
1666 GlobalReg = SrcReg;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001667 LocalLI = &LIS->getInterval(LocalReg);
1668 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx))
1669 return;
1670 }
1671 LiveInterval *GlobalLI = &LIS->getInterval(GlobalReg);
1672
1673 // Find the global segment after the start of the local LI.
1674 LiveInterval::iterator GlobalSegment = GlobalLI->find(LocalLI->beginIndex());
1675 // If GlobalLI does not overlap LocalLI->start, then a copy directly feeds a
1676 // local live range. We could create edges from other global uses to the local
1677 // start, but the coalescer should have already eliminated these cases, so
1678 // don't bother dealing with it.
1679 if (GlobalSegment == GlobalLI->end())
1680 return;
1681
1682 // If GlobalSegment is killed at the LocalLI->start, the call to find()
1683 // returned the next global segment. But if GlobalSegment overlaps with
1684 // LocalLI->start, then advance to the next segement. If a hole in GlobalLI
1685 // exists in LocalLI's vicinity, GlobalSegment will be the end of the hole.
1686 if (GlobalSegment->contains(LocalLI->beginIndex()))
1687 ++GlobalSegment;
1688
1689 if (GlobalSegment == GlobalLI->end())
1690 return;
1691
1692 // Check if GlobalLI contains a hole in the vicinity of LocalLI.
1693 if (GlobalSegment != GlobalLI->begin()) {
1694 // Two address defs have no hole.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001695 if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->end,
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001696 GlobalSegment->start)) {
1697 return;
1698 }
Andrew Trickd9761772013-07-30 19:59:08 +00001699 // If the prior global segment may be defined by the same two-address
1700 // instruction that also defines LocalLI, then can't make a hole here.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001701 if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->start,
Andrew Trickd9761772013-07-30 19:59:08 +00001702 LocalLI->beginIndex())) {
1703 return;
1704 }
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001705 // If GlobalLI has a prior segment, it must be live into the EBB. Otherwise
1706 // it would be a disconnected component in the live range.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001707 assert(std::prev(GlobalSegment)->start < LocalLI->beginIndex() &&
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001708 "Disconnected LRG within the scheduling region.");
1709 }
1710 MachineInstr *GlobalDef = LIS->getInstructionFromIndex(GlobalSegment->start);
1711 if (!GlobalDef)
1712 return;
1713
1714 SUnit *GlobalSU = DAG->getSUnit(GlobalDef);
1715 if (!GlobalSU)
1716 return;
1717
1718 // GlobalDef is the bottom of the GlobalLI hole. Open the hole by
1719 // constraining the uses of the last local def to precede GlobalDef.
1720 SmallVector<SUnit*,8> LocalUses;
1721 const VNInfo *LastLocalVN = LocalLI->getVNInfoBefore(LocalLI->endIndex());
1722 MachineInstr *LastLocalDef = LIS->getInstructionFromIndex(LastLocalVN->def);
1723 SUnit *LastLocalSU = DAG->getSUnit(LastLocalDef);
1724 for (SUnit::const_succ_iterator
1725 I = LastLocalSU->Succs.begin(), E = LastLocalSU->Succs.end();
1726 I != E; ++I) {
1727 if (I->getKind() != SDep::Data || I->getReg() != LocalReg)
1728 continue;
1729 if (I->getSUnit() == GlobalSU)
1730 continue;
1731 if (!DAG->canAddEdge(GlobalSU, I->getSUnit()))
1732 return;
1733 LocalUses.push_back(I->getSUnit());
1734 }
1735 // Open the top of the GlobalLI hole by constraining any earlier global uses
1736 // to precede the start of LocalLI.
1737 SmallVector<SUnit*,8> GlobalUses;
1738 MachineInstr *FirstLocalDef =
1739 LIS->getInstructionFromIndex(LocalLI->beginIndex());
1740 SUnit *FirstLocalSU = DAG->getSUnit(FirstLocalDef);
1741 for (SUnit::const_pred_iterator
1742 I = GlobalSU->Preds.begin(), E = GlobalSU->Preds.end(); I != E; ++I) {
1743 if (I->getKind() != SDep::Anti || I->getReg() != GlobalReg)
1744 continue;
1745 if (I->getSUnit() == FirstLocalSU)
1746 continue;
1747 if (!DAG->canAddEdge(FirstLocalSU, I->getSUnit()))
1748 return;
1749 GlobalUses.push_back(I->getSUnit());
1750 }
1751 DEBUG(dbgs() << "Constraining copy SU(" << CopySU->NodeNum << ")\n");
1752 // Add the weak edges.
1753 for (SmallVectorImpl<SUnit*>::const_iterator
1754 I = LocalUses.begin(), E = LocalUses.end(); I != E; ++I) {
1755 DEBUG(dbgs() << " Local use SU(" << (*I)->NodeNum << ") -> SU("
1756 << GlobalSU->NodeNum << ")\n");
1757 DAG->addEdge(GlobalSU, SDep(*I, SDep::Weak));
1758 }
1759 for (SmallVectorImpl<SUnit*>::const_iterator
1760 I = GlobalUses.begin(), E = GlobalUses.end(); I != E; ++I) {
1761 DEBUG(dbgs() << " Global use SU(" << (*I)->NodeNum << ") -> SU("
1762 << FirstLocalSU->NodeNum << ")\n");
1763 DAG->addEdge(FirstLocalSU, SDep(*I, SDep::Weak));
1764 }
1765}
1766
1767/// \brief Callback from DAG postProcessing to create weak edges to encourage
1768/// copy elimination.
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001769void CopyConstrain::apply(ScheduleDAGInstrs *DAGInstrs) {
1770 ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs);
Andrew Trickd7f890e2013-12-28 21:56:47 +00001771 assert(DAG->hasVRegLiveness() && "Expect VRegs with LiveIntervals");
1772
Andrew Trick2e875172013-04-24 23:19:56 +00001773 MachineBasicBlock::iterator FirstPos = nextIfDebug(DAG->begin(), DAG->end());
1774 if (FirstPos == DAG->end())
1775 return;
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001776 RegionBeginIdx = DAG->getLIS()->getInstructionIndex(*FirstPos);
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001777 RegionEndIdx = DAG->getLIS()->getInstructionIndex(
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001778 *priorNonDebug(DAG->end(), DAG->begin()));
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001779
1780 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
1781 SUnit *SU = &DAG->SUnits[Idx];
1782 if (!SU->getInstr()->isCopy())
1783 continue;
1784
Andrew Trickd7f890e2013-12-28 21:56:47 +00001785 constrainLocalCopy(SU, static_cast<ScheduleDAGMILive*>(DAG));
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001786 }
1787}
1788
1789//===----------------------------------------------------------------------===//
Andrew Trickfc127d12013-12-07 05:59:44 +00001790// MachineSchedStrategy helpers used by GenericScheduler, GenericPostScheduler
1791// and possibly other custom schedulers.
Andrew Trickd14d7c22013-12-28 21:56:57 +00001792//===----------------------------------------------------------------------===//
Andrew Tricke1c034f2012-01-17 06:55:03 +00001793
Andrew Trick5a22df42013-12-05 17:56:02 +00001794static const unsigned InvalidCycle = ~0U;
1795
Andrew Trickfc127d12013-12-07 05:59:44 +00001796SchedBoundary::~SchedBoundary() { delete HazardRec; }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001797
Andrew Trickfc127d12013-12-07 05:59:44 +00001798void SchedBoundary::reset() {
1799 // A new HazardRec is created for each DAG and owned by SchedBoundary.
1800 // Destroying and reconstructing it is very expensive though. So keep
1801 // invalid, placeholder HazardRecs.
1802 if (HazardRec && HazardRec->isEnabled()) {
1803 delete HazardRec;
Craig Topperc0196b12014-04-14 00:51:57 +00001804 HazardRec = nullptr;
Andrew Trickfc127d12013-12-07 05:59:44 +00001805 }
1806 Available.clear();
1807 Pending.clear();
1808 CheckPending = false;
Andrew Trickfc127d12013-12-07 05:59:44 +00001809 CurrCycle = 0;
1810 CurrMOps = 0;
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001811 MinReadyCycle = std::numeric_limits<unsigned>::max();
Andrew Trickfc127d12013-12-07 05:59:44 +00001812 ExpectedLatency = 0;
1813 DependentLatency = 0;
1814 RetiredMOps = 0;
1815 MaxExecutedResCount = 0;
1816 ZoneCritResIdx = 0;
1817 IsResourceLimited = false;
1818 ReservedCycles.clear();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001819#ifndef NDEBUG
Andrew Trickd14d7c22013-12-28 21:56:57 +00001820 // Track the maximum number of stall cycles that could arise either from the
1821 // latency of a DAG edge or the number of cycles that a processor resource is
1822 // reserved (SchedBoundary::ReservedCycles).
Andrew Trick7f1ebbe2014-06-07 01:48:43 +00001823 MaxObservedStall = 0;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001824#endif
Andrew Trickfc127d12013-12-07 05:59:44 +00001825 // Reserve a zero-count for invalid CritResIdx.
1826 ExecutedResCounts.resize(1);
1827 assert(!ExecutedResCounts[0] && "nonzero count for bad resource");
1828}
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001829
Andrew Trickfc127d12013-12-07 05:59:44 +00001830void SchedRemainder::
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001831init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
1832 reset();
1833 if (!SchedModel->hasInstrSchedModel())
1834 return;
1835 RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
1836 for (std::vector<SUnit>::iterator
1837 I = DAG->SUnits.begin(), E = DAG->SUnits.end(); I != E; ++I) {
1838 const MCSchedClassDesc *SC = DAG->getSchedClass(&*I);
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001839 RemIssueCount += SchedModel->getNumMicroOps(I->getInstr(), SC)
1840 * SchedModel->getMicroOpFactor();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001841 for (TargetSchedModel::ProcResIter
1842 PI = SchedModel->getWriteProcResBegin(SC),
1843 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1844 unsigned PIdx = PI->ProcResourceIdx;
1845 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1846 RemainingCounts[PIdx] += (Factor * PI->Cycles);
1847 }
1848 }
1849}
1850
Andrew Trickfc127d12013-12-07 05:59:44 +00001851void SchedBoundary::
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001852init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
1853 reset();
1854 DAG = dag;
1855 SchedModel = smodel;
1856 Rem = rem;
Andrew Trick5a22df42013-12-05 17:56:02 +00001857 if (SchedModel->hasInstrSchedModel()) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001858 ExecutedResCounts.resize(SchedModel->getNumProcResourceKinds());
Andrew Trick5a22df42013-12-05 17:56:02 +00001859 ReservedCycles.resize(SchedModel->getNumProcResourceKinds(), InvalidCycle);
1860 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001861}
1862
Andrew Trick880e5732013-12-05 17:55:58 +00001863/// Compute the stall cycles based on this SUnit's ready time. Heuristics treat
1864/// these "soft stalls" differently than the hard stall cycles based on CPU
1865/// resources and computed by checkHazard(). A fully in-order model
1866/// (MicroOpBufferSize==0) will not make use of this since instructions are not
1867/// available for scheduling until they are ready. However, a weaker in-order
1868/// model may use this for heuristics. For example, if a processor has in-order
1869/// behavior when reading certain resources, this may come into play.
Andrew Trickfc127d12013-12-07 05:59:44 +00001870unsigned SchedBoundary::getLatencyStallCycles(SUnit *SU) {
Andrew Trick880e5732013-12-05 17:55:58 +00001871 if (!SU->isUnbuffered)
1872 return 0;
1873
1874 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
1875 if (ReadyCycle > CurrCycle)
1876 return ReadyCycle - CurrCycle;
1877 return 0;
1878}
1879
Andrew Trick5a22df42013-12-05 17:56:02 +00001880/// Compute the next cycle at which the given processor resource can be
1881/// scheduled.
Andrew Trickfc127d12013-12-07 05:59:44 +00001882unsigned SchedBoundary::
Andrew Trick5a22df42013-12-05 17:56:02 +00001883getNextResourceCycle(unsigned PIdx, unsigned Cycles) {
1884 unsigned NextUnreserved = ReservedCycles[PIdx];
1885 // If this resource has never been used, always return cycle zero.
1886 if (NextUnreserved == InvalidCycle)
1887 return 0;
1888 // For bottom-up scheduling add the cycles needed for the current operation.
1889 if (!isTop())
1890 NextUnreserved += Cycles;
1891 return NextUnreserved;
1892}
1893
Andrew Trick8c9e6722012-06-29 03:23:24 +00001894/// Does this SU have a hazard within the current instruction group.
1895///
1896/// The scheduler supports two modes of hazard recognition. The first is the
1897/// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
1898/// supports highly complicated in-order reservation tables
1899/// (ScoreboardHazardRecognizer) and arbitraty target-specific logic.
1900///
1901/// The second is a streamlined mechanism that checks for hazards based on
1902/// simple counters that the scheduler itself maintains. It explicitly checks
1903/// for instruction dispatch limitations, including the number of micro-ops that
1904/// can dispatch per cycle.
1905///
1906/// TODO: Also check whether the SU must start a new group.
Andrew Trickfc127d12013-12-07 05:59:44 +00001907bool SchedBoundary::checkHazard(SUnit *SU) {
Andrew Trickd14d7c22013-12-28 21:56:57 +00001908 if (HazardRec->isEnabled()
1909 && HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard) {
1910 return true;
1911 }
Andrew Trickdd79f0f2012-10-10 05:43:09 +00001912 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
Andrew Tricke2ff5752013-06-15 04:49:49 +00001913 if ((CurrMOps > 0) && (CurrMOps + uops > SchedModel->getIssueWidth())) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001914 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") uops="
1915 << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
Andrew Trick8c9e6722012-06-29 03:23:24 +00001916 return true;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001917 }
Andrew Trick5a22df42013-12-05 17:56:02 +00001918 if (SchedModel->hasInstrSchedModel() && SU->hasReservedResource) {
1919 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1920 for (TargetSchedModel::ProcResIter
1921 PI = SchedModel->getWriteProcResBegin(SC),
1922 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
Andrew Trick56327222014-06-27 04:57:05 +00001923 unsigned NRCycle = getNextResourceCycle(PI->ProcResourceIdx, PI->Cycles);
1924 if (NRCycle > CurrCycle) {
Andrew Trick040c0da2014-06-27 05:09:36 +00001925#ifndef NDEBUG
Chad Rosieraba845e2014-07-02 16:46:08 +00001926 MaxObservedStall = std::max(PI->Cycles, MaxObservedStall);
Andrew Trick040c0da2014-06-27 05:09:36 +00001927#endif
Andrew Trick56327222014-06-27 04:57:05 +00001928 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") "
1929 << SchedModel->getResourceName(PI->ProcResourceIdx)
1930 << "=" << NRCycle << "c\n");
Andrew Trick5a22df42013-12-05 17:56:02 +00001931 return true;
Andrew Trick56327222014-06-27 04:57:05 +00001932 }
Andrew Trick5a22df42013-12-05 17:56:02 +00001933 }
1934 }
Andrew Trick8c9e6722012-06-29 03:23:24 +00001935 return false;
1936}
1937
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001938// Find the unscheduled node in ReadySUs with the highest latency.
Andrew Trickfc127d12013-12-07 05:59:44 +00001939unsigned SchedBoundary::
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001940findMaxLatency(ArrayRef<SUnit*> ReadySUs) {
Craig Topperc0196b12014-04-14 00:51:57 +00001941 SUnit *LateSU = nullptr;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001942 unsigned RemLatency = 0;
1943 for (ArrayRef<SUnit*>::iterator I = ReadySUs.begin(), E = ReadySUs.end();
Andrew Trickd6d5ad32012-12-18 20:52:56 +00001944 I != E; ++I) {
1945 unsigned L = getUnscheduledLatency(*I);
Andrew Trickf5b8ef22013-06-15 04:49:44 +00001946 if (L > RemLatency) {
Andrew Trickd6d5ad32012-12-18 20:52:56 +00001947 RemLatency = L;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001948 LateSU = *I;
Andrew Trickf5b8ef22013-06-15 04:49:44 +00001949 }
Andrew Trickd6d5ad32012-12-18 20:52:56 +00001950 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001951 if (LateSU) {
1952 DEBUG(dbgs() << Available.getName() << " RemLatency SU("
1953 << LateSU->NodeNum << ") " << RemLatency << "c\n");
Andrew Trickd6d5ad32012-12-18 20:52:56 +00001954 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001955 return RemLatency;
1956}
Andrew Trickf5b8ef22013-06-15 04:49:44 +00001957
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001958// Count resources in this zone and the remaining unscheduled
1959// instruction. Return the max count, scaled. Set OtherCritIdx to the critical
1960// resource index, or zero if the zone is issue limited.
Andrew Trickfc127d12013-12-07 05:59:44 +00001961unsigned SchedBoundary::
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001962getOtherResourceCount(unsigned &OtherCritIdx) {
Alexey Samsonov64c391d2013-07-19 08:55:18 +00001963 OtherCritIdx = 0;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001964 if (!SchedModel->hasInstrSchedModel())
1965 return 0;
1966
1967 unsigned OtherCritCount = Rem->RemIssueCount
1968 + (RetiredMOps * SchedModel->getMicroOpFactor());
1969 DEBUG(dbgs() << " " << Available.getName() << " + Remain MOps: "
1970 << OtherCritCount / SchedModel->getMicroOpFactor() << '\n');
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001971 for (unsigned PIdx = 1, PEnd = SchedModel->getNumProcResourceKinds();
1972 PIdx != PEnd; ++PIdx) {
1973 unsigned OtherCount = getResourceCount(PIdx) + Rem->RemainingCounts[PIdx];
1974 if (OtherCount > OtherCritCount) {
1975 OtherCritCount = OtherCount;
1976 OtherCritIdx = PIdx;
1977 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001978 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001979 if (OtherCritIdx) {
1980 DEBUG(dbgs() << " " << Available.getName() << " + Remain CritRes: "
1981 << OtherCritCount / SchedModel->getResourceFactor(OtherCritIdx)
Andrew Trickfc127d12013-12-07 05:59:44 +00001982 << " " << SchedModel->getResourceName(OtherCritIdx) << "\n");
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001983 }
1984 return OtherCritCount;
1985}
1986
Andrew Trickfc127d12013-12-07 05:59:44 +00001987void SchedBoundary::releaseNode(SUnit *SU, unsigned ReadyCycle) {
Andrew Trick7f1ebbe2014-06-07 01:48:43 +00001988 assert(SU->getInstr() && "Scheduled SUnit must have instr");
1989
1990#ifndef NDEBUG
Andrew Trick491e34a2014-06-12 22:36:28 +00001991 // ReadyCycle was been bumped up to the CurrCycle when this node was
1992 // scheduled, but CurrCycle may have been eagerly advanced immediately after
1993 // scheduling, so may now be greater than ReadyCycle.
1994 if (ReadyCycle > CurrCycle)
1995 MaxObservedStall = std::max(ReadyCycle - CurrCycle, MaxObservedStall);
Andrew Trick7f1ebbe2014-06-07 01:48:43 +00001996#endif
1997
Andrew Trick61f1a272012-05-24 22:11:09 +00001998 if (ReadyCycle < MinReadyCycle)
1999 MinReadyCycle = ReadyCycle;
2000
2001 // Check for interlocks first. For the purpose of other heuristics, an
2002 // instruction that cannot issue appears as if it's not in the ReadyQueue.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002003 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
Matthias Braun6493bc22016-04-22 19:09:17 +00002004 if ((!IsBuffered && ReadyCycle > CurrCycle) || checkHazard(SU) ||
2005 Available.size() >= ReadyListLimit)
Andrew Trick61f1a272012-05-24 22:11:09 +00002006 Pending.push(SU);
2007 else
2008 Available.push(SU);
2009}
2010
2011/// Move the boundary of scheduled code by one cycle.
Andrew Trickfc127d12013-12-07 05:59:44 +00002012void SchedBoundary::bumpCycle(unsigned NextCycle) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002013 if (SchedModel->getMicroOpBufferSize() == 0) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00002014 assert(MinReadyCycle < std::numeric_limits<unsigned>::max() &&
2015 "MinReadyCycle uninitialized");
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002016 if (MinReadyCycle > NextCycle)
2017 NextCycle = MinReadyCycle;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002018 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002019 // Update the current micro-ops, which will issue in the next cycle.
2020 unsigned DecMOps = SchedModel->getIssueWidth() * (NextCycle - CurrCycle);
2021 CurrMOps = (CurrMOps <= DecMOps) ? 0 : CurrMOps - DecMOps;
2022
2023 // Decrement DependentLatency based on the next cycle.
Andrew Trickf5b8ef22013-06-15 04:49:44 +00002024 if ((NextCycle - CurrCycle) > DependentLatency)
2025 DependentLatency = 0;
2026 else
2027 DependentLatency -= (NextCycle - CurrCycle);
Andrew Trick61f1a272012-05-24 22:11:09 +00002028
2029 if (!HazardRec->isEnabled()) {
Andrew Trick45446062012-06-05 21:11:27 +00002030 // Bypass HazardRec virtual calls.
Andrew Trick61f1a272012-05-24 22:11:09 +00002031 CurrCycle = NextCycle;
Matthias Braunb550b762016-04-21 01:54:13 +00002032 } else {
Andrew Trick45446062012-06-05 21:11:27 +00002033 // Bypass getHazardType calls in case of long latency.
Andrew Trick61f1a272012-05-24 22:11:09 +00002034 for (; CurrCycle != NextCycle; ++CurrCycle) {
2035 if (isTop())
2036 HazardRec->AdvanceCycle();
2037 else
2038 HazardRec->RecedeCycle();
2039 }
2040 }
2041 CheckPending = true;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002042 unsigned LFactor = SchedModel->getLatencyFactor();
2043 IsResourceLimited =
2044 (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
2045 > (int)LFactor;
Andrew Trick61f1a272012-05-24 22:11:09 +00002046
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002047 DEBUG(dbgs() << "Cycle: " << CurrCycle << ' ' << Available.getName() << '\n');
2048}
2049
Andrew Trickfc127d12013-12-07 05:59:44 +00002050void SchedBoundary::incExecutedResources(unsigned PIdx, unsigned Count) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002051 ExecutedResCounts[PIdx] += Count;
2052 if (ExecutedResCounts[PIdx] > MaxExecutedResCount)
2053 MaxExecutedResCount = ExecutedResCounts[PIdx];
Andrew Trick61f1a272012-05-24 22:11:09 +00002054}
2055
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002056/// Add the given processor resource to this scheduled zone.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002057///
2058/// \param Cycles indicates the number of consecutive (non-pipelined) cycles
2059/// during which this resource is consumed.
2060///
2061/// \return the next cycle at which the instruction may execute without
2062/// oversubscribing resources.
Andrew Trickfc127d12013-12-07 05:59:44 +00002063unsigned SchedBoundary::
Andrew Trick5a22df42013-12-05 17:56:02 +00002064countResource(unsigned PIdx, unsigned Cycles, unsigned NextCycle) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002065 unsigned Factor = SchedModel->getResourceFactor(PIdx);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002066 unsigned Count = Factor * Cycles;
Andrew Trickfc127d12013-12-07 05:59:44 +00002067 DEBUG(dbgs() << " " << SchedModel->getResourceName(PIdx)
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002068 << " +" << Cycles << "x" << Factor << "u\n");
2069
2070 // Update Executed resources counts.
2071 incExecutedResources(PIdx, Count);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002072 assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
2073 Rem->RemainingCounts[PIdx] -= Count;
2074
Andrew Trickb13ef172013-07-19 00:20:07 +00002075 // Check if this resource exceeds the current critical resource. If so, it
2076 // becomes the critical resource.
2077 if (ZoneCritResIdx != PIdx && (getResourceCount(PIdx) > getCriticalCount())) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002078 ZoneCritResIdx = PIdx;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002079 DEBUG(dbgs() << " *** Critical resource "
Andrew Trickfc127d12013-12-07 05:59:44 +00002080 << SchedModel->getResourceName(PIdx) << ": "
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002081 << getResourceCount(PIdx) / SchedModel->getLatencyFactor() << "c\n");
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002082 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002083 // For reserved resources, record the highest cycle using the resource.
2084 unsigned NextAvailable = getNextResourceCycle(PIdx, Cycles);
2085 if (NextAvailable > CurrCycle) {
2086 DEBUG(dbgs() << " Resource conflict: "
2087 << SchedModel->getProcResource(PIdx)->Name << " reserved until @"
2088 << NextAvailable << "\n");
2089 }
2090 return NextAvailable;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002091}
2092
Andrew Trick45446062012-06-05 21:11:27 +00002093/// Move the boundary of scheduled code by one SUnit.
Andrew Trickfc127d12013-12-07 05:59:44 +00002094void SchedBoundary::bumpNode(SUnit *SU) {
Andrew Trick45446062012-06-05 21:11:27 +00002095 // Update the reservation table.
2096 if (HazardRec->isEnabled()) {
2097 if (!isTop() && SU->isCall) {
2098 // Calls are scheduled with their preceding instructions. For bottom-up
2099 // scheduling, clear the pipeline state before emitting.
2100 HazardRec->Reset();
2101 }
2102 HazardRec->EmitInstruction(SU);
2103 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002104 // checkHazard should prevent scheduling multiple instructions per cycle that
2105 // exceed the issue width.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002106 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
2107 unsigned IncMOps = SchedModel->getNumMicroOps(SU->getInstr());
Daniel Jasper0d92abd2013-12-06 08:58:22 +00002108 assert(
2109 (CurrMOps == 0 || (CurrMOps + IncMOps) <= SchedModel->getIssueWidth()) &&
Andrew Trickf7760a22013-12-06 17:19:20 +00002110 "Cannot schedule this instruction's MicroOps in the current cycle.");
Andrew Trick5a22df42013-12-05 17:56:02 +00002111
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002112 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
2113 DEBUG(dbgs() << " Ready @" << ReadyCycle << "c\n");
2114
Andrew Trick5a22df42013-12-05 17:56:02 +00002115 unsigned NextCycle = CurrCycle;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002116 switch (SchedModel->getMicroOpBufferSize()) {
2117 case 0:
2118 assert(ReadyCycle <= CurrCycle && "Broken PendingQueue");
2119 break;
2120 case 1:
2121 if (ReadyCycle > NextCycle) {
2122 NextCycle = ReadyCycle;
2123 DEBUG(dbgs() << " *** Stall until: " << ReadyCycle << "\n");
2124 }
2125 break;
2126 default:
2127 // We don't currently model the OOO reorder buffer, so consider all
Andrew Trick880e5732013-12-05 17:55:58 +00002128 // scheduled MOps to be "retired". We do loosely model in-order resource
2129 // latency. If this instruction uses an in-order resource, account for any
2130 // likely stall cycles.
2131 if (SU->isUnbuffered && ReadyCycle > NextCycle)
2132 NextCycle = ReadyCycle;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002133 break;
2134 }
2135 RetiredMOps += IncMOps;
2136
2137 // Update resource counts and critical resource.
2138 if (SchedModel->hasInstrSchedModel()) {
2139 unsigned DecRemIssue = IncMOps * SchedModel->getMicroOpFactor();
2140 assert(Rem->RemIssueCount >= DecRemIssue && "MOps double counted");
2141 Rem->RemIssueCount -= DecRemIssue;
2142 if (ZoneCritResIdx) {
2143 // Scale scheduled micro-ops for comparing with the critical resource.
2144 unsigned ScaledMOps =
2145 RetiredMOps * SchedModel->getMicroOpFactor();
2146
2147 // If scaled micro-ops are now more than the previous critical resource by
2148 // a full cycle, then micro-ops issue becomes critical.
2149 if ((int)(ScaledMOps - getResourceCount(ZoneCritResIdx))
2150 >= (int)SchedModel->getLatencyFactor()) {
2151 ZoneCritResIdx = 0;
2152 DEBUG(dbgs() << " *** Critical resource NumMicroOps: "
2153 << ScaledMOps / SchedModel->getLatencyFactor() << "c\n");
2154 }
2155 }
2156 for (TargetSchedModel::ProcResIter
2157 PI = SchedModel->getWriteProcResBegin(SC),
2158 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2159 unsigned RCycle =
Andrew Trick5a22df42013-12-05 17:56:02 +00002160 countResource(PI->ProcResourceIdx, PI->Cycles, NextCycle);
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002161 if (RCycle > NextCycle)
2162 NextCycle = RCycle;
2163 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002164 if (SU->hasReservedResource) {
2165 // For reserved resources, record the highest cycle using the resource.
2166 // For top-down scheduling, this is the cycle in which we schedule this
2167 // instruction plus the number of cycles the operations reserves the
2168 // resource. For bottom-up is it simply the instruction's cycle.
2169 for (TargetSchedModel::ProcResIter
2170 PI = SchedModel->getWriteProcResBegin(SC),
2171 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2172 unsigned PIdx = PI->ProcResourceIdx;
Andrew Trickd14d7c22013-12-28 21:56:57 +00002173 if (SchedModel->getProcResource(PIdx)->BufferSize == 0) {
Chad Rosieraba845e2014-07-02 16:46:08 +00002174 if (isTop()) {
2175 ReservedCycles[PIdx] =
2176 std::max(getNextResourceCycle(PIdx, 0), NextCycle + PI->Cycles);
2177 }
2178 else
2179 ReservedCycles[PIdx] = NextCycle;
Andrew Trickd14d7c22013-12-28 21:56:57 +00002180 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002181 }
2182 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002183 }
2184 // Update ExpectedLatency and DependentLatency.
2185 unsigned &TopLatency = isTop() ? ExpectedLatency : DependentLatency;
2186 unsigned &BotLatency = isTop() ? DependentLatency : ExpectedLatency;
2187 if (SU->getDepth() > TopLatency) {
2188 TopLatency = SU->getDepth();
2189 DEBUG(dbgs() << " " << Available.getName()
2190 << " TopLatency SU(" << SU->NodeNum << ") " << TopLatency << "c\n");
2191 }
2192 if (SU->getHeight() > BotLatency) {
2193 BotLatency = SU->getHeight();
2194 DEBUG(dbgs() << " " << Available.getName()
2195 << " BotLatency SU(" << SU->NodeNum << ") " << BotLatency << "c\n");
2196 }
2197 // If we stall for any reason, bump the cycle.
2198 if (NextCycle > CurrCycle) {
2199 bumpCycle(NextCycle);
Matthias Braunb550b762016-04-21 01:54:13 +00002200 } else {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002201 // After updating ZoneCritResIdx and ExpectedLatency, check if we're
Alp Tokercb402912014-01-24 17:20:08 +00002202 // resource limited. If a stall occurred, bumpCycle does this.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002203 unsigned LFactor = SchedModel->getLatencyFactor();
2204 IsResourceLimited =
2205 (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
2206 > (int)LFactor;
2207 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002208 // Update CurrMOps after calling bumpCycle to handle stalls, since bumpCycle
2209 // resets CurrMOps. Loop to handle instructions with more MOps than issue in
2210 // one cycle. Since we commonly reach the max MOps here, opportunistically
2211 // bump the cycle to avoid uselessly checking everything in the readyQ.
2212 CurrMOps += IncMOps;
2213 while (CurrMOps >= SchedModel->getIssueWidth()) {
Andrew Trick5a22df42013-12-05 17:56:02 +00002214 DEBUG(dbgs() << " *** Max MOps " << CurrMOps
2215 << " at cycle " << CurrCycle << '\n');
Andrew Trickd14d7c22013-12-28 21:56:57 +00002216 bumpCycle(++NextCycle);
Andrew Trick5a22df42013-12-05 17:56:02 +00002217 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002218 DEBUG(dumpScheduledState());
Andrew Trick45446062012-06-05 21:11:27 +00002219}
2220
Andrew Trick61f1a272012-05-24 22:11:09 +00002221/// Release pending ready nodes in to the available queue. This makes them
2222/// visible to heuristics.
Andrew Trickfc127d12013-12-07 05:59:44 +00002223void SchedBoundary::releasePending() {
Andrew Trick61f1a272012-05-24 22:11:09 +00002224 // If the available queue is empty, it is safe to reset MinReadyCycle.
2225 if (Available.empty())
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00002226 MinReadyCycle = std::numeric_limits<unsigned>::max();
Andrew Trick61f1a272012-05-24 22:11:09 +00002227
2228 // Check to see if any of the pending instructions are ready to issue. If
2229 // so, add them to the available queue.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002230 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
Andrew Trick61f1a272012-05-24 22:11:09 +00002231 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
2232 SUnit *SU = *(Pending.begin()+i);
Andrew Trick45446062012-06-05 21:11:27 +00002233 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
Andrew Trick61f1a272012-05-24 22:11:09 +00002234
2235 if (ReadyCycle < MinReadyCycle)
2236 MinReadyCycle = ReadyCycle;
2237
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002238 if (!IsBuffered && ReadyCycle > CurrCycle)
Andrew Trick61f1a272012-05-24 22:11:09 +00002239 continue;
2240
Andrew Trick8c9e6722012-06-29 03:23:24 +00002241 if (checkHazard(SU))
Andrew Trick61f1a272012-05-24 22:11:09 +00002242 continue;
2243
Matthias Braun6493bc22016-04-22 19:09:17 +00002244 if (Available.size() >= ReadyListLimit)
2245 break;
2246
Andrew Trick61f1a272012-05-24 22:11:09 +00002247 Available.push(SU);
2248 Pending.remove(Pending.begin()+i);
2249 --i; --e;
2250 }
2251 CheckPending = false;
2252}
2253
2254/// Remove SU from the ready set for this boundary.
Andrew Trickfc127d12013-12-07 05:59:44 +00002255void SchedBoundary::removeReady(SUnit *SU) {
Andrew Trick61f1a272012-05-24 22:11:09 +00002256 if (Available.isInQueue(SU))
2257 Available.remove(Available.find(SU));
2258 else {
2259 assert(Pending.isInQueue(SU) && "bad ready count");
2260 Pending.remove(Pending.find(SU));
2261 }
2262}
2263
2264/// If this queue only has one ready candidate, return it. As a side effect,
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002265/// defer any nodes that now hit a hazard, and advance the cycle until at least
2266/// one node is ready. If multiple instructions are ready, return NULL.
Andrew Trickfc127d12013-12-07 05:59:44 +00002267SUnit *SchedBoundary::pickOnlyChoice() {
Andrew Trick61f1a272012-05-24 22:11:09 +00002268 if (CheckPending)
2269 releasePending();
2270
Andrew Tricke2ff5752013-06-15 04:49:49 +00002271 if (CurrMOps > 0) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002272 // Defer any ready instrs that now have a hazard.
2273 for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
2274 if (checkHazard(*I)) {
2275 Pending.push(*I);
2276 I = Available.remove(I);
2277 continue;
2278 }
2279 ++I;
2280 }
2281 }
Andrew Trick61f1a272012-05-24 22:11:09 +00002282 for (unsigned i = 0; Available.empty(); ++i) {
Chad Rosieraba845e2014-07-02 16:46:08 +00002283// FIXME: Re-enable assert once PR20057 is resolved.
2284// assert(i <= (HazardRec->getMaxLookAhead() + MaxObservedStall) &&
2285// "permanent hazard");
2286 (void)i;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002287 bumpCycle(CurrCycle + 1);
Andrew Trick61f1a272012-05-24 22:11:09 +00002288 releasePending();
2289 }
Matthias Braund29d31e2016-06-23 21:27:38 +00002290
2291 DEBUG(Pending.dump());
2292 DEBUG(Available.dump());
2293
Andrew Trick61f1a272012-05-24 22:11:09 +00002294 if (Available.size() == 1)
2295 return *Available.begin();
Craig Topperc0196b12014-04-14 00:51:57 +00002296 return nullptr;
Andrew Trick61f1a272012-05-24 22:11:09 +00002297}
2298
Matthias Braun8c209aa2017-01-28 02:02:38 +00002299#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002300// This is useful information to dump after bumpNode.
2301// Note that the Queue contents are more useful before pickNodeFromQueue.
Matthias Braun8c209aa2017-01-28 02:02:38 +00002302LLVM_DUMP_METHOD void SchedBoundary::dumpScheduledState() {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002303 unsigned ResFactor;
2304 unsigned ResCount;
2305 if (ZoneCritResIdx) {
2306 ResFactor = SchedModel->getResourceFactor(ZoneCritResIdx);
2307 ResCount = getResourceCount(ZoneCritResIdx);
Matthias Braunb550b762016-04-21 01:54:13 +00002308 } else {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002309 ResFactor = SchedModel->getMicroOpFactor();
2310 ResCount = RetiredMOps * SchedModel->getMicroOpFactor();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002311 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002312 unsigned LFactor = SchedModel->getLatencyFactor();
2313 dbgs() << Available.getName() << " @" << CurrCycle << "c\n"
2314 << " Retired: " << RetiredMOps;
2315 dbgs() << "\n Executed: " << getExecutedCount() / LFactor << "c";
2316 dbgs() << "\n Critical: " << ResCount / LFactor << "c, "
Andrew Trickfc127d12013-12-07 05:59:44 +00002317 << ResCount / ResFactor << " "
2318 << SchedModel->getResourceName(ZoneCritResIdx)
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002319 << "\n ExpectedLatency: " << ExpectedLatency << "c\n"
2320 << (IsResourceLimited ? " - Resource" : " - Latency")
2321 << " limited.\n";
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002322}
Andrew Trick8e8415f2013-06-15 05:46:47 +00002323#endif
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002324
Andrew Trickfc127d12013-12-07 05:59:44 +00002325//===----------------------------------------------------------------------===//
Andrew Trickd14d7c22013-12-28 21:56:57 +00002326// GenericScheduler - Generic implementation of MachineSchedStrategy.
Andrew Trickfc127d12013-12-07 05:59:44 +00002327//===----------------------------------------------------------------------===//
2328
Andrew Trickd14d7c22013-12-28 21:56:57 +00002329void GenericSchedulerBase::SchedCandidate::
2330initResourceDelta(const ScheduleDAGMI *DAG,
2331 const TargetSchedModel *SchedModel) {
2332 if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
2333 return;
2334
2335 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
2336 for (TargetSchedModel::ProcResIter
2337 PI = SchedModel->getWriteProcResBegin(SC),
2338 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2339 if (PI->ProcResourceIdx == Policy.ReduceResIdx)
2340 ResDelta.CritResources += PI->Cycles;
2341 if (PI->ProcResourceIdx == Policy.DemandResIdx)
2342 ResDelta.DemandedResources += PI->Cycles;
2343 }
2344}
2345
2346/// Set the CandPolicy given a scheduling zone given the current resources and
2347/// latencies inside and outside the zone.
Matthias Braunb550b762016-04-21 01:54:13 +00002348void GenericSchedulerBase::setPolicy(CandPolicy &Policy, bool IsPostRA,
Andrew Trickd14d7c22013-12-28 21:56:57 +00002349 SchedBoundary &CurrZone,
2350 SchedBoundary *OtherZone) {
Eric Christopher572e03a2015-06-19 01:53:21 +00002351 // Apply preemptive heuristics based on the total latency and resources
Andrew Trickd14d7c22013-12-28 21:56:57 +00002352 // inside and outside this zone. Potential stalls should be considered before
2353 // following this policy.
2354
2355 // Compute remaining latency. We need this both to determine whether the
2356 // overall schedule has become latency-limited and whether the instructions
2357 // outside this zone are resource or latency limited.
2358 //
2359 // The "dependent" latency is updated incrementally during scheduling as the
2360 // max height/depth of scheduled nodes minus the cycles since it was
2361 // scheduled:
2362 // DLat = max (N.depth - (CurrCycle - N.ReadyCycle) for N in Zone
2363 //
2364 // The "independent" latency is the max ready queue depth:
2365 // ILat = max N.depth for N in Available|Pending
2366 //
2367 // RemainingLatency is the greater of independent and dependent latency.
2368 unsigned RemLatency = CurrZone.getDependentLatency();
2369 RemLatency = std::max(RemLatency,
2370 CurrZone.findMaxLatency(CurrZone.Available.elements()));
2371 RemLatency = std::max(RemLatency,
2372 CurrZone.findMaxLatency(CurrZone.Pending.elements()));
2373
2374 // Compute the critical resource outside the zone.
Andrew Trick7afe4812013-12-28 22:25:57 +00002375 unsigned OtherCritIdx = 0;
Andrew Trickd14d7c22013-12-28 21:56:57 +00002376 unsigned OtherCount =
2377 OtherZone ? OtherZone->getOtherResourceCount(OtherCritIdx) : 0;
2378
2379 bool OtherResLimited = false;
2380 if (SchedModel->hasInstrSchedModel()) {
2381 unsigned LFactor = SchedModel->getLatencyFactor();
2382 OtherResLimited = (int)(OtherCount - (RemLatency * LFactor)) > (int)LFactor;
2383 }
2384 // Schedule aggressively for latency in PostRA mode. We don't check for
2385 // acyclic latency during PostRA, and highly out-of-order processors will
2386 // skip PostRA scheduling.
2387 if (!OtherResLimited) {
2388 if (IsPostRA || (RemLatency + CurrZone.getCurrCycle() > Rem.CriticalPath)) {
2389 Policy.ReduceLatency |= true;
2390 DEBUG(dbgs() << " " << CurrZone.Available.getName()
2391 << " RemainingLatency " << RemLatency << " + "
2392 << CurrZone.getCurrCycle() << "c > CritPath "
2393 << Rem.CriticalPath << "\n");
2394 }
2395 }
2396 // If the same resource is limiting inside and outside the zone, do nothing.
2397 if (CurrZone.getZoneCritResIdx() == OtherCritIdx)
2398 return;
2399
2400 DEBUG(
2401 if (CurrZone.isResourceLimited()) {
2402 dbgs() << " " << CurrZone.Available.getName() << " ResourceLimited: "
2403 << SchedModel->getResourceName(CurrZone.getZoneCritResIdx())
2404 << "\n";
2405 }
2406 if (OtherResLimited)
2407 dbgs() << " RemainingLimit: "
2408 << SchedModel->getResourceName(OtherCritIdx) << "\n";
2409 if (!CurrZone.isResourceLimited() && !OtherResLimited)
2410 dbgs() << " Latency limited both directions.\n");
2411
2412 if (CurrZone.isResourceLimited() && !Policy.ReduceResIdx)
2413 Policy.ReduceResIdx = CurrZone.getZoneCritResIdx();
2414
2415 if (OtherResLimited)
2416 Policy.DemandResIdx = OtherCritIdx;
2417}
2418
2419#ifndef NDEBUG
2420const char *GenericSchedulerBase::getReasonStr(
2421 GenericSchedulerBase::CandReason Reason) {
2422 switch (Reason) {
2423 case NoCand: return "NOCAND ";
Matthias Braun49cb6e92016-05-27 22:14:26 +00002424 case Only1: return "ONLY1 ";
2425 case PhysRegCopy: return "PREG-COPY ";
Andrew Trickd14d7c22013-12-28 21:56:57 +00002426 case RegExcess: return "REG-EXCESS";
2427 case RegCritical: return "REG-CRIT ";
2428 case Stall: return "STALL ";
2429 case Cluster: return "CLUSTER ";
2430 case Weak: return "WEAK ";
2431 case RegMax: return "REG-MAX ";
2432 case ResourceReduce: return "RES-REDUCE";
2433 case ResourceDemand: return "RES-DEMAND";
2434 case TopDepthReduce: return "TOP-DEPTH ";
2435 case TopPathReduce: return "TOP-PATH ";
2436 case BotHeightReduce:return "BOT-HEIGHT";
2437 case BotPathReduce: return "BOT-PATH ";
2438 case NextDefUse: return "DEF-USE ";
2439 case NodeOrder: return "ORDER ";
2440 };
2441 llvm_unreachable("Unknown reason!");
2442}
2443
2444void GenericSchedulerBase::traceCandidate(const SchedCandidate &Cand) {
2445 PressureChange P;
2446 unsigned ResIdx = 0;
2447 unsigned Latency = 0;
2448 switch (Cand.Reason) {
2449 default:
2450 break;
2451 case RegExcess:
2452 P = Cand.RPDelta.Excess;
2453 break;
2454 case RegCritical:
2455 P = Cand.RPDelta.CriticalMax;
2456 break;
2457 case RegMax:
2458 P = Cand.RPDelta.CurrentMax;
2459 break;
2460 case ResourceReduce:
2461 ResIdx = Cand.Policy.ReduceResIdx;
2462 break;
2463 case ResourceDemand:
2464 ResIdx = Cand.Policy.DemandResIdx;
2465 break;
2466 case TopDepthReduce:
2467 Latency = Cand.SU->getDepth();
2468 break;
2469 case TopPathReduce:
2470 Latency = Cand.SU->getHeight();
2471 break;
2472 case BotHeightReduce:
2473 Latency = Cand.SU->getHeight();
2474 break;
2475 case BotPathReduce:
2476 Latency = Cand.SU->getDepth();
2477 break;
2478 }
James Y Knighte72b0db2015-09-18 18:52:20 +00002479 dbgs() << " Cand SU(" << Cand.SU->NodeNum << ") " << getReasonStr(Cand.Reason);
Andrew Trickd14d7c22013-12-28 21:56:57 +00002480 if (P.isValid())
2481 dbgs() << " " << TRI->getRegPressureSetName(P.getPSet())
2482 << ":" << P.getUnitInc() << " ";
2483 else
2484 dbgs() << " ";
2485 if (ResIdx)
2486 dbgs() << " " << SchedModel->getProcResource(ResIdx)->Name << " ";
2487 else
2488 dbgs() << " ";
2489 if (Latency)
2490 dbgs() << " " << Latency << " cycles ";
2491 else
2492 dbgs() << " ";
2493 dbgs() << '\n';
2494}
2495#endif
2496
2497/// Return true if this heuristic determines order.
2498static bool tryLess(int TryVal, int CandVal,
2499 GenericSchedulerBase::SchedCandidate &TryCand,
2500 GenericSchedulerBase::SchedCandidate &Cand,
2501 GenericSchedulerBase::CandReason Reason) {
2502 if (TryVal < CandVal) {
2503 TryCand.Reason = Reason;
2504 return true;
2505 }
2506 if (TryVal > CandVal) {
2507 if (Cand.Reason > Reason)
2508 Cand.Reason = Reason;
2509 return true;
2510 }
Andrew Trickd14d7c22013-12-28 21:56:57 +00002511 return false;
2512}
2513
2514static bool tryGreater(int TryVal, int CandVal,
2515 GenericSchedulerBase::SchedCandidate &TryCand,
2516 GenericSchedulerBase::SchedCandidate &Cand,
2517 GenericSchedulerBase::CandReason Reason) {
2518 if (TryVal > CandVal) {
2519 TryCand.Reason = Reason;
2520 return true;
2521 }
2522 if (TryVal < CandVal) {
2523 if (Cand.Reason > Reason)
2524 Cand.Reason = Reason;
2525 return true;
2526 }
Andrew Trickd14d7c22013-12-28 21:56:57 +00002527 return false;
2528}
2529
2530static bool tryLatency(GenericSchedulerBase::SchedCandidate &TryCand,
2531 GenericSchedulerBase::SchedCandidate &Cand,
2532 SchedBoundary &Zone) {
2533 if (Zone.isTop()) {
2534 if (Cand.SU->getDepth() > Zone.getScheduledLatency()) {
2535 if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2536 TryCand, Cand, GenericSchedulerBase::TopDepthReduce))
2537 return true;
2538 }
2539 if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2540 TryCand, Cand, GenericSchedulerBase::TopPathReduce))
2541 return true;
Matthias Braunb550b762016-04-21 01:54:13 +00002542 } else {
Andrew Trickd14d7c22013-12-28 21:56:57 +00002543 if (Cand.SU->getHeight() > Zone.getScheduledLatency()) {
2544 if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2545 TryCand, Cand, GenericSchedulerBase::BotHeightReduce))
2546 return true;
2547 }
2548 if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2549 TryCand, Cand, GenericSchedulerBase::BotPathReduce))
2550 return true;
2551 }
2552 return false;
2553}
2554
Matthias Braun49cb6e92016-05-27 22:14:26 +00002555static void tracePick(GenericSchedulerBase::CandReason Reason, bool IsTop) {
2556 DEBUG(dbgs() << "Pick " << (IsTop ? "Top " : "Bot ")
2557 << GenericSchedulerBase::getReasonStr(Reason) << '\n');
2558}
2559
Matthias Braun6ad3d052016-06-25 00:23:00 +00002560static void tracePick(const GenericSchedulerBase::SchedCandidate &Cand) {
2561 tracePick(Cand.Reason, Cand.AtTop);
Andrew Trickd14d7c22013-12-28 21:56:57 +00002562}
2563
Andrew Trickfc127d12013-12-07 05:59:44 +00002564void GenericScheduler::initialize(ScheduleDAGMI *dag) {
Andrew Trickd7f890e2013-12-28 21:56:47 +00002565 assert(dag->hasVRegLiveness() &&
2566 "(PreRA)GenericScheduler needs vreg liveness");
2567 DAG = static_cast<ScheduleDAGMILive*>(dag);
Andrew Trickfc127d12013-12-07 05:59:44 +00002568 SchedModel = DAG->getSchedModel();
2569 TRI = DAG->TRI;
2570
2571 Rem.init(DAG, SchedModel);
2572 Top.init(DAG, SchedModel, &Rem);
2573 Bot.init(DAG, SchedModel, &Rem);
2574
2575 // Initialize resource counts.
2576
2577 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
2578 // are disabled, then these HazardRecs will be disabled.
2579 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
Andrew Trickfc127d12013-12-07 05:59:44 +00002580 if (!Top.HazardRec) {
2581 Top.HazardRec =
Eric Christopher99556d72014-10-14 06:56:25 +00002582 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
Eric Christopherd9134482014-08-04 21:25:23 +00002583 Itin, DAG);
Andrew Trickfc127d12013-12-07 05:59:44 +00002584 }
2585 if (!Bot.HazardRec) {
2586 Bot.HazardRec =
Eric Christopher99556d72014-10-14 06:56:25 +00002587 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
Eric Christopherd9134482014-08-04 21:25:23 +00002588 Itin, DAG);
Andrew Trickfc127d12013-12-07 05:59:44 +00002589 }
Matthias Brauncc676c42016-06-25 02:03:36 +00002590 TopCand.SU = nullptr;
2591 BotCand.SU = nullptr;
Andrew Trickfc127d12013-12-07 05:59:44 +00002592}
2593
2594/// Initialize the per-region scheduling policy.
2595void GenericScheduler::initPolicy(MachineBasicBlock::iterator Begin,
2596 MachineBasicBlock::iterator End,
2597 unsigned NumRegionInstrs) {
Eric Christopher99556d72014-10-14 06:56:25 +00002598 const MachineFunction &MF = *Begin->getParent()->getParent();
2599 const TargetLowering *TLI = MF.getSubtarget().getTargetLowering();
Andrew Trickfc127d12013-12-07 05:59:44 +00002600
2601 // Avoid setting up the register pressure tracker for small regions to save
2602 // compile time. As a rough heuristic, only track pressure when the number of
2603 // schedulable instructions exceeds half the integer register file.
Andrew Trick350ff2c2014-01-21 21:27:37 +00002604 RegionPolicy.ShouldTrackPressure = true;
Andrew Trick46753512014-01-22 03:38:55 +00002605 for (unsigned VT = MVT::i32; VT > (unsigned)MVT::i1; --VT) {
2606 MVT::SimpleValueType LegalIntVT = (MVT::SimpleValueType)VT;
2607 if (TLI->isTypeLegal(LegalIntVT)) {
Andrew Trick350ff2c2014-01-21 21:27:37 +00002608 unsigned NIntRegs = Context->RegClassInfo->getNumAllocatableRegs(
Andrew Trick46753512014-01-22 03:38:55 +00002609 TLI->getRegClassFor(LegalIntVT));
Andrew Trick350ff2c2014-01-21 21:27:37 +00002610 RegionPolicy.ShouldTrackPressure = NumRegionInstrs > (NIntRegs / 2);
2611 }
2612 }
Andrew Trickfc127d12013-12-07 05:59:44 +00002613
2614 // For generic targets, we default to bottom-up, because it's simpler and more
2615 // compile-time optimizations have been implemented in that direction.
2616 RegionPolicy.OnlyBottomUp = true;
2617
2618 // Allow the subtarget to override default policy.
Duncan P. N. Exon Smith63298722016-07-01 00:23:27 +00002619 MF.getSubtarget().overrideSchedPolicy(RegionPolicy, NumRegionInstrs);
Andrew Trickfc127d12013-12-07 05:59:44 +00002620
2621 // After subtarget overrides, apply command line options.
2622 if (!EnableRegPressure)
2623 RegionPolicy.ShouldTrackPressure = false;
2624
2625 // Check -misched-topdown/bottomup can force or unforce scheduling direction.
2626 // e.g. -misched-bottomup=false allows scheduling in both directions.
2627 assert((!ForceTopDown || !ForceBottomUp) &&
2628 "-misched-topdown incompatible with -misched-bottomup");
2629 if (ForceBottomUp.getNumOccurrences() > 0) {
2630 RegionPolicy.OnlyBottomUp = ForceBottomUp;
2631 if (RegionPolicy.OnlyBottomUp)
2632 RegionPolicy.OnlyTopDown = false;
2633 }
2634 if (ForceTopDown.getNumOccurrences() > 0) {
2635 RegionPolicy.OnlyTopDown = ForceTopDown;
2636 if (RegionPolicy.OnlyTopDown)
2637 RegionPolicy.OnlyBottomUp = false;
2638 }
2639}
2640
James Y Knighte72b0db2015-09-18 18:52:20 +00002641void GenericScheduler::dumpPolicy() {
Matthias Braun8c209aa2017-01-28 02:02:38 +00002642 // Cannot completely remove virtual function even in release mode.
2643#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
James Y Knighte72b0db2015-09-18 18:52:20 +00002644 dbgs() << "GenericScheduler RegionPolicy: "
2645 << " ShouldTrackPressure=" << RegionPolicy.ShouldTrackPressure
2646 << " OnlyTopDown=" << RegionPolicy.OnlyTopDown
2647 << " OnlyBottomUp=" << RegionPolicy.OnlyBottomUp
2648 << "\n";
Matthias Braun8c209aa2017-01-28 02:02:38 +00002649#endif
James Y Knighte72b0db2015-09-18 18:52:20 +00002650}
2651
Andrew Trickfc127d12013-12-07 05:59:44 +00002652/// Set IsAcyclicLatencyLimited if the acyclic path is longer than the cyclic
2653/// critical path by more cycles than it takes to drain the instruction buffer.
2654/// We estimate an upper bounds on in-flight instructions as:
2655///
2656/// CyclesPerIteration = max( CyclicPath, Loop-Resource-Height )
2657/// InFlightIterations = AcyclicPath / CyclesPerIteration
2658/// InFlightResources = InFlightIterations * LoopResources
2659///
2660/// TODO: Check execution resources in addition to IssueCount.
2661void GenericScheduler::checkAcyclicLatency() {
2662 if (Rem.CyclicCritPath == 0 || Rem.CyclicCritPath >= Rem.CriticalPath)
2663 return;
2664
2665 // Scaled number of cycles per loop iteration.
2666 unsigned IterCount =
2667 std::max(Rem.CyclicCritPath * SchedModel->getLatencyFactor(),
2668 Rem.RemIssueCount);
2669 // Scaled acyclic critical path.
2670 unsigned AcyclicCount = Rem.CriticalPath * SchedModel->getLatencyFactor();
2671 // InFlightCount = (AcyclicPath / IterCycles) * InstrPerLoop
2672 unsigned InFlightCount =
2673 (AcyclicCount * Rem.RemIssueCount + IterCount-1) / IterCount;
2674 unsigned BufferLimit =
2675 SchedModel->getMicroOpBufferSize() * SchedModel->getMicroOpFactor();
2676
2677 Rem.IsAcyclicLatencyLimited = InFlightCount > BufferLimit;
2678
2679 DEBUG(dbgs() << "IssueCycles="
2680 << Rem.RemIssueCount / SchedModel->getLatencyFactor() << "c "
2681 << "IterCycles=" << IterCount / SchedModel->getLatencyFactor()
2682 << "c NumIters=" << (AcyclicCount + IterCount-1) / IterCount
2683 << " InFlight=" << InFlightCount / SchedModel->getMicroOpFactor()
2684 << "m BufferLim=" << SchedModel->getMicroOpBufferSize() << "m\n";
2685 if (Rem.IsAcyclicLatencyLimited)
2686 dbgs() << " ACYCLIC LATENCY LIMIT\n");
2687}
2688
2689void GenericScheduler::registerRoots() {
2690 Rem.CriticalPath = DAG->ExitSU.getDepth();
2691
2692 // Some roots may not feed into ExitSU. Check all of them in case.
2693 for (std::vector<SUnit*>::const_iterator
2694 I = Bot.Available.begin(), E = Bot.Available.end(); I != E; ++I) {
2695 if ((*I)->getDepth() > Rem.CriticalPath)
2696 Rem.CriticalPath = (*I)->getDepth();
2697 }
Gerolf Hoflehnerb5220dc2014-08-07 21:49:44 +00002698 DEBUG(dbgs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << '\n');
2699 if (DumpCriticalPathLength) {
2700 errs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << " \n";
2701 }
Andrew Trickfc127d12013-12-07 05:59:44 +00002702
2703 if (EnableCyclicPath) {
2704 Rem.CyclicCritPath = DAG->computeCyclicCriticalPath();
2705 checkAcyclicLatency();
2706 }
2707}
2708
Andrew Trick1a831342013-08-30 03:49:48 +00002709static bool tryPressure(const PressureChange &TryP,
2710 const PressureChange &CandP,
Andrew Trickd14d7c22013-12-28 21:56:57 +00002711 GenericSchedulerBase::SchedCandidate &TryCand,
2712 GenericSchedulerBase::SchedCandidate &Cand,
Tom Stellard5ce53062015-12-16 18:31:01 +00002713 GenericSchedulerBase::CandReason Reason,
2714 const TargetRegisterInfo *TRI,
2715 const MachineFunction &MF) {
Andrew Trickb1a45b62013-08-30 04:27:29 +00002716 // If one candidate decreases and the other increases, go with it.
2717 // Invalid candidates have UnitInc==0.
Hal Finkel7a87f8a2014-10-10 17:06:20 +00002718 if (tryGreater(TryP.getUnitInc() < 0, CandP.getUnitInc() < 0, TryCand, Cand,
2719 Reason)) {
Andrew Trickb1a45b62013-08-30 04:27:29 +00002720 return true;
2721 }
Matthias Braun6ad3d052016-06-25 00:23:00 +00002722 // Do not compare the magnitude of pressure changes between top and bottom
2723 // boundary.
2724 if (Cand.AtTop != TryCand.AtTop)
2725 return false;
2726
2727 // If both candidates affect the same set in the same boundary, go with the
2728 // smallest increase.
2729 unsigned TryPSet = TryP.getPSetOrMax();
2730 unsigned CandPSet = CandP.getPSetOrMax();
2731 if (TryPSet == CandPSet) {
2732 return tryLess(TryP.getUnitInc(), CandP.getUnitInc(), TryCand, Cand,
2733 Reason);
2734 }
Tom Stellard5ce53062015-12-16 18:31:01 +00002735
2736 int TryRank = TryP.isValid() ? TRI->getRegPressureSetScore(MF, TryPSet) :
2737 std::numeric_limits<int>::max();
2738
2739 int CandRank = CandP.isValid() ? TRI->getRegPressureSetScore(MF, CandPSet) :
2740 std::numeric_limits<int>::max();
2741
Andrew Trick401b6952013-07-25 07:26:35 +00002742 // If the candidates are decreasing pressure, reverse priority.
Andrew Trick1a831342013-08-30 03:49:48 +00002743 if (TryP.getUnitInc() < 0)
Andrew Trick401b6952013-07-25 07:26:35 +00002744 std::swap(TryRank, CandRank);
2745 return tryGreater(TryRank, CandRank, TryCand, Cand, Reason);
2746}
2747
Andrew Tricka7714a02012-11-12 19:40:10 +00002748static unsigned getWeakLeft(const SUnit *SU, bool isTop) {
2749 return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
2750}
2751
Andrew Tricke833e1c2013-04-13 06:07:40 +00002752/// Minimize physical register live ranges. Regalloc wants them adjacent to
2753/// their physreg def/use.
2754///
2755/// FIXME: This is an unnecessary check on the critical path. Most are root/leaf
2756/// copies which can be prescheduled. The rest (e.g. x86 MUL) could be bundled
2757/// with the operation that produces or consumes the physreg. We'll do this when
2758/// regalloc has support for parallel copies.
2759static int biasPhysRegCopy(const SUnit *SU, bool isTop) {
2760 const MachineInstr *MI = SU->getInstr();
2761 if (!MI->isCopy())
2762 return 0;
2763
2764 unsigned ScheduledOper = isTop ? 1 : 0;
2765 unsigned UnscheduledOper = isTop ? 0 : 1;
2766 // If we have already scheduled the physreg produce/consumer, immediately
2767 // schedule the copy.
2768 if (TargetRegisterInfo::isPhysicalRegister(
2769 MI->getOperand(ScheduledOper).getReg()))
2770 return 1;
2771 // If the physreg is at the boundary, defer it. Otherwise schedule it
2772 // immediately to free the dependent. We can hoist the copy later.
2773 bool AtBoundary = isTop ? !SU->NumSuccsLeft : !SU->NumPredsLeft;
2774 if (TargetRegisterInfo::isPhysicalRegister(
2775 MI->getOperand(UnscheduledOper).getReg()))
2776 return AtBoundary ? -1 : 1;
2777 return 0;
2778}
2779
Matthias Braun4f573772016-04-22 19:10:15 +00002780void GenericScheduler::initCandidate(SchedCandidate &Cand, SUnit *SU,
2781 bool AtTop,
2782 const RegPressureTracker &RPTracker,
2783 RegPressureTracker &TempTracker) {
2784 Cand.SU = SU;
Matthias Braun6ad3d052016-06-25 00:23:00 +00002785 Cand.AtTop = AtTop;
Matthias Braun4f573772016-04-22 19:10:15 +00002786 if (DAG->isTrackingPressure()) {
2787 if (AtTop) {
2788 TempTracker.getMaxDownwardPressureDelta(
2789 Cand.SU->getInstr(),
2790 Cand.RPDelta,
2791 DAG->getRegionCriticalPSets(),
2792 DAG->getRegPressure().MaxSetPressure);
2793 } else {
2794 if (VerifyScheduling) {
2795 TempTracker.getMaxUpwardPressureDelta(
2796 Cand.SU->getInstr(),
2797 &DAG->getPressureDiff(Cand.SU),
2798 Cand.RPDelta,
2799 DAG->getRegionCriticalPSets(),
2800 DAG->getRegPressure().MaxSetPressure);
2801 } else {
2802 RPTracker.getUpwardPressureDelta(
2803 Cand.SU->getInstr(),
2804 DAG->getPressureDiff(Cand.SU),
2805 Cand.RPDelta,
2806 DAG->getRegionCriticalPSets(),
2807 DAG->getRegPressure().MaxSetPressure);
2808 }
2809 }
2810 }
2811 DEBUG(if (Cand.RPDelta.Excess.isValid())
2812 dbgs() << " Try SU(" << Cand.SU->NodeNum << ") "
2813 << TRI->getRegPressureSetName(Cand.RPDelta.Excess.getPSet())
2814 << ":" << Cand.RPDelta.Excess.getUnitInc() << "\n");
2815}
2816
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002817/// Apply a set of heursitics to a new candidate. Heuristics are currently
2818/// hierarchical. This may be more efficient than a graduated cost model because
2819/// we don't need to evaluate all aspects of the model for each node in the
2820/// queue. But it's really done to make the heuristics easier to debug and
2821/// statistically analyze.
2822///
2823/// \param Cand provides the policy and current best candidate.
2824/// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
Matthias Braun6ad3d052016-06-25 00:23:00 +00002825/// \param Zone describes the scheduled zone that we are extending, or nullptr
2826// if Cand is from a different zone than TryCand.
Andrew Trick665d3ec2013-09-19 23:10:59 +00002827void GenericScheduler::tryCandidate(SchedCandidate &Cand,
Andrew Trickbb1247b2013-12-05 17:55:47 +00002828 SchedCandidate &TryCand,
Matthias Braun6ad3d052016-06-25 00:23:00 +00002829 SchedBoundary *Zone) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002830 // Initialize the candidate if needed.
2831 if (!Cand.isValid()) {
2832 TryCand.Reason = NodeOrder;
2833 return;
2834 }
Andrew Tricke833e1c2013-04-13 06:07:40 +00002835
Matthias Braun6ad3d052016-06-25 00:23:00 +00002836 if (tryGreater(biasPhysRegCopy(TryCand.SU, TryCand.AtTop),
2837 biasPhysRegCopy(Cand.SU, Cand.AtTop),
Andrew Tricke833e1c2013-04-13 06:07:40 +00002838 TryCand, Cand, PhysRegCopy))
2839 return;
2840
Andrew Tricke02d5da2015-05-17 23:40:27 +00002841 // Avoid exceeding the target's limit.
Andrew Trick66c3dfb2013-09-04 21:00:11 +00002842 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.Excess,
2843 Cand.RPDelta.Excess,
Tom Stellard5ce53062015-12-16 18:31:01 +00002844 TryCand, Cand, RegExcess, TRI,
2845 DAG->MF))
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002846 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002847
2848 // Avoid increasing the max critical pressure in the scheduled region.
Andrew Trick66c3dfb2013-09-04 21:00:11 +00002849 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CriticalMax,
2850 Cand.RPDelta.CriticalMax,
Tom Stellard5ce53062015-12-16 18:31:01 +00002851 TryCand, Cand, RegCritical, TRI,
2852 DAG->MF))
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002853 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002854
Matthias Braun6ad3d052016-06-25 00:23:00 +00002855 // We only compare a subset of features when comparing nodes between
2856 // Top and Bottom boundary. Some properties are simply incomparable, in many
2857 // other instances we should only override the other boundary if something
2858 // is a clear good pick on one boundary. Skip heuristics that are more
2859 // "tie-breaking" in nature.
2860 bool SameBoundary = Zone != nullptr;
2861 if (SameBoundary) {
2862 // For loops that are acyclic path limited, aggressively schedule for
Jonas Paulssonbaeb4022016-11-04 08:31:14 +00002863 // latency. Within an single cycle, whenever CurrMOps > 0, allow normal
2864 // heuristics to take precedence.
Matthias Braun6ad3d052016-06-25 00:23:00 +00002865 if (Rem.IsAcyclicLatencyLimited && !Zone->getCurrMOps() &&
2866 tryLatency(TryCand, Cand, *Zone))
2867 return;
Andrew Trickddffae92013-09-06 17:32:36 +00002868
Matthias Braun6ad3d052016-06-25 00:23:00 +00002869 // Prioritize instructions that read unbuffered resources by stall cycles.
2870 if (tryLess(Zone->getLatencyStallCycles(TryCand.SU),
2871 Zone->getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
2872 return;
2873 }
Andrew Trick880e5732013-12-05 17:55:58 +00002874
Andrew Tricka7714a02012-11-12 19:40:10 +00002875 // Keep clustered nodes together to encourage downstream peephole
2876 // optimizations which may reduce resource requirements.
2877 //
2878 // This is a best effort to set things up for a post-RA pass. Optimizations
2879 // like generating loads of multiple registers should ideally be done within
2880 // the scheduler pass by combining the loads during DAG postprocessing.
Matthias Braun6ad3d052016-06-25 00:23:00 +00002881 const SUnit *CandNextClusterSU =
2882 Cand.AtTop ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
2883 const SUnit *TryCandNextClusterSU =
2884 TryCand.AtTop ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
2885 if (tryGreater(TryCand.SU == TryCandNextClusterSU,
2886 Cand.SU == CandNextClusterSU,
Andrew Tricka7714a02012-11-12 19:40:10 +00002887 TryCand, Cand, Cluster))
2888 return;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00002889
Matthias Braun6ad3d052016-06-25 00:23:00 +00002890 if (SameBoundary) {
2891 // Weak edges are for clustering and other constraints.
2892 if (tryLess(getWeakLeft(TryCand.SU, TryCand.AtTop),
2893 getWeakLeft(Cand.SU, Cand.AtTop),
2894 TryCand, Cand, Weak))
2895 return;
Andrew Tricka7714a02012-11-12 19:40:10 +00002896 }
Matthias Braun6ad3d052016-06-25 00:23:00 +00002897
Andrew Trick71f08a32013-06-17 21:45:13 +00002898 // Avoid increasing the max pressure of the entire region.
Andrew Trick66c3dfb2013-09-04 21:00:11 +00002899 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CurrentMax,
2900 Cand.RPDelta.CurrentMax,
Tom Stellard5ce53062015-12-16 18:31:01 +00002901 TryCand, Cand, RegMax, TRI,
2902 DAG->MF))
Andrew Trick71f08a32013-06-17 21:45:13 +00002903 return;
2904
Matthias Braun6ad3d052016-06-25 00:23:00 +00002905 if (SameBoundary) {
2906 // Avoid critical resource consumption and balance the schedule.
2907 TryCand.initResourceDelta(DAG, SchedModel);
2908 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
2909 TryCand, Cand, ResourceReduce))
2910 return;
2911 if (tryGreater(TryCand.ResDelta.DemandedResources,
2912 Cand.ResDelta.DemandedResources,
2913 TryCand, Cand, ResourceDemand))
2914 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002915
Matthias Braun6ad3d052016-06-25 00:23:00 +00002916 // Avoid serializing long latency dependence chains.
2917 // For acyclic path limited loops, latency was already checked above.
2918 if (!RegionPolicy.DisableLatencyHeuristic && TryCand.Policy.ReduceLatency &&
2919 !Rem.IsAcyclicLatencyLimited && tryLatency(TryCand, Cand, *Zone))
2920 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002921
Matthias Braun6ad3d052016-06-25 00:23:00 +00002922 // Fall through to original instruction order.
2923 if ((Zone->isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
2924 || (!Zone->isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
2925 TryCand.Reason = NodeOrder;
2926 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002927 }
2928}
Andrew Trick419eae22012-05-10 21:06:19 +00002929
Andrew Trickc573cd92013-09-06 17:32:44 +00002930/// Pick the best candidate from the queue.
Andrew Trick7ee9de52012-05-10 21:06:16 +00002931///
2932/// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
2933/// DAG building. To adjust for the current scheduling location we need to
2934/// maintain the number of vreg uses remaining to be top-scheduled.
Andrew Trick665d3ec2013-09-19 23:10:59 +00002935void GenericScheduler::pickNodeFromQueue(SchedBoundary &Zone,
Matthias Braun6ad3d052016-06-25 00:23:00 +00002936 const CandPolicy &ZonePolicy,
Andrew Trickbb1247b2013-12-05 17:55:47 +00002937 const RegPressureTracker &RPTracker,
2938 SchedCandidate &Cand) {
Andrew Trick7ee9de52012-05-10 21:06:16 +00002939 // getMaxPressureDelta temporarily modifies the tracker.
2940 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
2941
Matthias Braund29d31e2016-06-23 21:27:38 +00002942 ReadyQueue &Q = Zone.Available;
Andrew Trickdd375dd2012-05-24 22:11:03 +00002943 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
Andrew Trick7ee9de52012-05-10 21:06:16 +00002944
Matthias Braun6ad3d052016-06-25 00:23:00 +00002945 SchedCandidate TryCand(ZonePolicy);
Matthias Braun4f573772016-04-22 19:10:15 +00002946 initCandidate(TryCand, *I, Zone.isTop(), RPTracker, TempTracker);
Matthias Braun6ad3d052016-06-25 00:23:00 +00002947 // Pass SchedBoundary only when comparing nodes from the same boundary.
2948 SchedBoundary *ZoneArg = Cand.AtTop == TryCand.AtTop ? &Zone : nullptr;
2949 tryCandidate(Cand, TryCand, ZoneArg);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002950 if (TryCand.Reason != NoCand) {
2951 // Initialize resource delta if needed in case future heuristics query it.
2952 if (TryCand.ResDelta == SchedResourceDelta())
2953 TryCand.initResourceDelta(DAG, SchedModel);
2954 Cand.setBest(TryCand);
Andrew Trick419d4912013-04-05 00:31:29 +00002955 DEBUG(traceCandidate(Cand));
Andrew Trick22025772012-05-17 18:35:10 +00002956 }
Andrew Trick7ee9de52012-05-10 21:06:16 +00002957 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002958}
2959
Andrew Trick22025772012-05-17 18:35:10 +00002960/// Pick the best candidate node from either the top or bottom queue.
Andrew Trick665d3ec2013-09-19 23:10:59 +00002961SUnit *GenericScheduler::pickNodeBidirectional(bool &IsTopNode) {
Andrew Trick22025772012-05-17 18:35:10 +00002962 // Schedule as far as possible in the direction of no choice. This is most
2963 // efficient, but also provides the best heuristics for CriticalPSets.
Andrew Trick61f1a272012-05-24 22:11:09 +00002964 if (SUnit *SU = Bot.pickOnlyChoice()) {
Andrew Trick22025772012-05-17 18:35:10 +00002965 IsTopNode = false;
Matthias Braun49cb6e92016-05-27 22:14:26 +00002966 tracePick(Only1, false);
Andrew Trick61f1a272012-05-24 22:11:09 +00002967 return SU;
Andrew Trick22025772012-05-17 18:35:10 +00002968 }
Andrew Trick61f1a272012-05-24 22:11:09 +00002969 if (SUnit *SU = Top.pickOnlyChoice()) {
Andrew Trick22025772012-05-17 18:35:10 +00002970 IsTopNode = true;
Matthias Braun49cb6e92016-05-27 22:14:26 +00002971 tracePick(Only1, true);
Andrew Trick61f1a272012-05-24 22:11:09 +00002972 return SU;
Andrew Trick22025772012-05-17 18:35:10 +00002973 }
Andrew Trickfc127d12013-12-07 05:59:44 +00002974 // Set the bottom-up policy based on the state of the current bottom zone and
2975 // the instructions outside the zone, including the top zone.
Matthias Braun6ad3d052016-06-25 00:23:00 +00002976 CandPolicy BotPolicy;
2977 setPolicy(BotPolicy, /*IsPostRA=*/false, Bot, &Top);
Andrew Trickfc127d12013-12-07 05:59:44 +00002978 // Set the top-down policy based on the state of the current top zone and
2979 // the instructions outside the zone, including the bottom zone.
Matthias Braun6ad3d052016-06-25 00:23:00 +00002980 CandPolicy TopPolicy;
2981 setPolicy(TopPolicy, /*IsPostRA=*/false, Top, &Bot);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002982
Matthias Brauncc676c42016-06-25 02:03:36 +00002983 // See if BotCand is still valid (because we previously scheduled from Top).
Matthias Braund29d31e2016-06-23 21:27:38 +00002984 DEBUG(dbgs() << "Picking from Bot:\n");
Matthias Brauncc676c42016-06-25 02:03:36 +00002985 if (!BotCand.isValid() || BotCand.SU->isScheduled ||
2986 BotCand.Policy != BotPolicy) {
2987 BotCand.reset(CandPolicy());
2988 pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), BotCand);
2989 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
2990 } else {
2991 DEBUG(traceCandidate(BotCand));
2992#ifndef NDEBUG
2993 if (VerifyScheduling) {
2994 SchedCandidate TCand;
2995 TCand.reset(CandPolicy());
2996 pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), TCand);
2997 assert(TCand.SU == BotCand.SU &&
2998 "Last pick result should correspond to re-picking right now");
2999 }
3000#endif
3001 }
Andrew Trick22025772012-05-17 18:35:10 +00003002
Andrew Trick22025772012-05-17 18:35:10 +00003003 // Check if the top Q has a better candidate.
Matthias Braund29d31e2016-06-23 21:27:38 +00003004 DEBUG(dbgs() << "Picking from Top:\n");
Matthias Brauncc676c42016-06-25 02:03:36 +00003005 if (!TopCand.isValid() || TopCand.SU->isScheduled ||
3006 TopCand.Policy != TopPolicy) {
3007 TopCand.reset(CandPolicy());
3008 pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TopCand);
3009 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
3010 } else {
3011 DEBUG(traceCandidate(TopCand));
3012#ifndef NDEBUG
3013 if (VerifyScheduling) {
3014 SchedCandidate TCand;
3015 TCand.reset(CandPolicy());
3016 pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TCand);
3017 assert(TCand.SU == TopCand.SU &&
3018 "Last pick result should correspond to re-picking right now");
3019 }
3020#endif
3021 }
3022
3023 // Pick best from BotCand and TopCand.
3024 assert(BotCand.isValid());
3025 assert(TopCand.isValid());
3026 SchedCandidate Cand = BotCand;
3027 TopCand.Reason = NoCand;
3028 tryCandidate(Cand, TopCand, nullptr);
3029 if (TopCand.Reason != NoCand) {
3030 Cand.setBest(TopCand);
3031 DEBUG(traceCandidate(Cand));
3032 }
Andrew Trick22025772012-05-17 18:35:10 +00003033
Matthias Braun6ad3d052016-06-25 00:23:00 +00003034 IsTopNode = Cand.AtTop;
3035 tracePick(Cand);
3036 return Cand.SU;
Andrew Trick22025772012-05-17 18:35:10 +00003037}
3038
3039/// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
Andrew Trick665d3ec2013-09-19 23:10:59 +00003040SUnit *GenericScheduler::pickNode(bool &IsTopNode) {
Andrew Trick7ee9de52012-05-10 21:06:16 +00003041 if (DAG->top() == DAG->bottom()) {
Andrew Trick61f1a272012-05-24 22:11:09 +00003042 assert(Top.Available.empty() && Top.Pending.empty() &&
3043 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
Craig Topperc0196b12014-04-14 00:51:57 +00003044 return nullptr;
Andrew Trick7ee9de52012-05-10 21:06:16 +00003045 }
Andrew Trick7ee9de52012-05-10 21:06:16 +00003046 SUnit *SU;
Andrew Trick984d98b2012-10-08 18:53:53 +00003047 do {
Andrew Trick75e411c2013-09-06 17:32:34 +00003048 if (RegionPolicy.OnlyTopDown) {
Andrew Trick984d98b2012-10-08 18:53:53 +00003049 SU = Top.pickOnlyChoice();
3050 if (!SU) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003051 CandPolicy NoPolicy;
Matthias Brauncc676c42016-06-25 02:03:36 +00003052 TopCand.reset(NoPolicy);
Matthias Braun6ad3d052016-06-25 00:23:00 +00003053 pickNodeFromQueue(Top, NoPolicy, DAG->getTopRPTracker(), TopCand);
Andrew Trick1ab16d92013-09-04 21:00:13 +00003054 assert(TopCand.Reason != NoCand && "failed to find a candidate");
Matthias Braun6ad3d052016-06-25 00:23:00 +00003055 tracePick(TopCand);
Andrew Trick984d98b2012-10-08 18:53:53 +00003056 SU = TopCand.SU;
3057 }
3058 IsTopNode = true;
Matthias Braunb550b762016-04-21 01:54:13 +00003059 } else if (RegionPolicy.OnlyBottomUp) {
Andrew Trick984d98b2012-10-08 18:53:53 +00003060 SU = Bot.pickOnlyChoice();
3061 if (!SU) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003062 CandPolicy NoPolicy;
Matthias Brauncc676c42016-06-25 02:03:36 +00003063 BotCand.reset(NoPolicy);
Matthias Braun6ad3d052016-06-25 00:23:00 +00003064 pickNodeFromQueue(Bot, NoPolicy, DAG->getBotRPTracker(), BotCand);
Andrew Trick1ab16d92013-09-04 21:00:13 +00003065 assert(BotCand.Reason != NoCand && "failed to find a candidate");
Matthias Braun6ad3d052016-06-25 00:23:00 +00003066 tracePick(BotCand);
Andrew Trick984d98b2012-10-08 18:53:53 +00003067 SU = BotCand.SU;
3068 }
3069 IsTopNode = false;
Matthias Braunb550b762016-04-21 01:54:13 +00003070 } else {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003071 SU = pickNodeBidirectional(IsTopNode);
Andrew Trick984d98b2012-10-08 18:53:53 +00003072 }
3073 } while (SU->isScheduled);
3074
Andrew Trick61f1a272012-05-24 22:11:09 +00003075 if (SU->isTopReady())
3076 Top.removeReady(SU);
3077 if (SU->isBottomReady())
3078 Bot.removeReady(SU);
Andrew Trick4e7f6a72012-05-25 02:02:39 +00003079
Andrew Trick1f0bb692013-04-13 06:07:49 +00003080 DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " << *SU->getInstr());
Andrew Trick7ee9de52012-05-10 21:06:16 +00003081 return SU;
3082}
3083
Andrew Trick665d3ec2013-09-19 23:10:59 +00003084void GenericScheduler::reschedulePhysRegCopies(SUnit *SU, bool isTop) {
Andrew Tricke833e1c2013-04-13 06:07:40 +00003085 MachineBasicBlock::iterator InsertPos = SU->getInstr();
3086 if (!isTop)
3087 ++InsertPos;
3088 SmallVectorImpl<SDep> &Deps = isTop ? SU->Preds : SU->Succs;
3089
3090 // Find already scheduled copies with a single physreg dependence and move
3091 // them just above the scheduled instruction.
3092 for (SmallVectorImpl<SDep>::iterator I = Deps.begin(), E = Deps.end();
3093 I != E; ++I) {
3094 if (I->getKind() != SDep::Data || !TRI->isPhysicalRegister(I->getReg()))
3095 continue;
3096 SUnit *DepSU = I->getSUnit();
3097 if (isTop ? DepSU->Succs.size() > 1 : DepSU->Preds.size() > 1)
3098 continue;
3099 MachineInstr *Copy = DepSU->getInstr();
3100 if (!Copy->isCopy())
3101 continue;
3102 DEBUG(dbgs() << " Rescheduling physreg copy ";
3103 I->getSUnit()->dump(DAG));
3104 DAG->moveInstruction(Copy, InsertPos);
3105 }
3106}
3107
Andrew Trick61f1a272012-05-24 22:11:09 +00003108/// Update the scheduler's state after scheduling a node. This is the same node
Andrew Trickd14d7c22013-12-28 21:56:57 +00003109/// that was just returned by pickNode(). However, ScheduleDAGMILive needs to
3110/// update it's state based on the current cycle before MachineSchedStrategy
3111/// does.
Andrew Tricke833e1c2013-04-13 06:07:40 +00003112///
3113/// FIXME: Eventually, we may bundle physreg copies rather than rescheduling
3114/// them here. See comments in biasPhysRegCopy.
Andrew Trick665d3ec2013-09-19 23:10:59 +00003115void GenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
Andrew Trick45446062012-06-05 21:11:27 +00003116 if (IsTopNode) {
Andrew Trickfc127d12013-12-07 05:59:44 +00003117 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
Andrew Trickce27bb92012-06-29 03:23:22 +00003118 Top.bumpNode(SU);
Andrew Tricke833e1c2013-04-13 06:07:40 +00003119 if (SU->hasPhysRegUses)
3120 reschedulePhysRegCopies(SU, true);
Matthias Braunb550b762016-04-21 01:54:13 +00003121 } else {
Andrew Trickfc127d12013-12-07 05:59:44 +00003122 SU->BotReadyCycle = std::max(SU->BotReadyCycle, Bot.getCurrCycle());
Andrew Trickce27bb92012-06-29 03:23:22 +00003123 Bot.bumpNode(SU);
Andrew Tricke833e1c2013-04-13 06:07:40 +00003124 if (SU->hasPhysRegDefs)
3125 reschedulePhysRegCopies(SU, false);
Andrew Trick61f1a272012-05-24 22:11:09 +00003126 }
3127}
3128
Andrew Trick8823dec2012-03-14 04:00:41 +00003129/// Create the standard converging machine scheduler. This will be used as the
3130/// default scheduler if the target does not set a default.
Matthias Braun115efcd2016-11-28 20:11:54 +00003131ScheduleDAGMILive *llvm::createGenericSchedLive(MachineSchedContext *C) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003132 ScheduleDAGMILive *DAG =
3133 new ScheduleDAGMILive(C, llvm::make_unique<GenericScheduler>(C));
Andrew Tricka7714a02012-11-12 19:40:10 +00003134 // Register DAG post-processors.
Andrew Trick85a1d4c2013-04-24 15:54:43 +00003135 //
3136 // FIXME: extend the mutation API to allow earlier mutations to instantiate
3137 // data and pass it to later mutations. Have a single mutation that gathers
3138 // the interesting nodes in one pass.
Tom Stellard68726a52016-08-19 19:59:18 +00003139 DAG->addMutation(createCopyConstrainDAGMutation(DAG->TII, DAG->TRI));
Andrew Tricka7714a02012-11-12 19:40:10 +00003140 return DAG;
Andrew Tricke1c034f2012-01-17 06:55:03 +00003141}
Andrew Trickd14d7c22013-12-28 21:56:57 +00003142
Matthias Braun115efcd2016-11-28 20:11:54 +00003143static ScheduleDAGInstrs *createConveringSched(MachineSchedContext *C) {
3144 return createGenericSchedLive(C);
3145}
3146
Andrew Tricke1c034f2012-01-17 06:55:03 +00003147static MachineSchedRegistry
Andrew Trick665d3ec2013-09-19 23:10:59 +00003148GenericSchedRegistry("converge", "Standard converging scheduler.",
Matthias Braun115efcd2016-11-28 20:11:54 +00003149 createConveringSched);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003150
3151//===----------------------------------------------------------------------===//
3152// PostGenericScheduler - Generic PostRA implementation of MachineSchedStrategy.
3153//===----------------------------------------------------------------------===//
3154
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003155void PostGenericScheduler::initialize(ScheduleDAGMI *Dag) {
3156 DAG = Dag;
3157 SchedModel = DAG->getSchedModel();
3158 TRI = DAG->TRI;
Andrew Trickd14d7c22013-12-28 21:56:57 +00003159
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003160 Rem.init(DAG, SchedModel);
3161 Top.init(DAG, SchedModel, &Rem);
3162 BotRoots.clear();
Andrew Trickd14d7c22013-12-28 21:56:57 +00003163
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003164 // Initialize the HazardRecognizers. If itineraries don't exist, are empty,
3165 // or are disabled, then these HazardRecs will be disabled.
3166 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003167 if (!Top.HazardRec) {
3168 Top.HazardRec =
Eric Christopher99556d72014-10-14 06:56:25 +00003169 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
Eric Christopherd9134482014-08-04 21:25:23 +00003170 Itin, DAG);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003171 }
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003172}
Andrew Trickd14d7c22013-12-28 21:56:57 +00003173
Andrew Trickd14d7c22013-12-28 21:56:57 +00003174void PostGenericScheduler::registerRoots() {
3175 Rem.CriticalPath = DAG->ExitSU.getDepth();
3176
3177 // Some roots may not feed into ExitSU. Check all of them in case.
3178 for (SmallVectorImpl<SUnit*>::const_iterator
3179 I = BotRoots.begin(), E = BotRoots.end(); I != E; ++I) {
3180 if ((*I)->getDepth() > Rem.CriticalPath)
3181 Rem.CriticalPath = (*I)->getDepth();
3182 }
Gerolf Hoflehnerb5220dc2014-08-07 21:49:44 +00003183 DEBUG(dbgs() << "Critical Path: (PGS-RR) " << Rem.CriticalPath << '\n');
3184 if (DumpCriticalPathLength) {
3185 errs() << "Critical Path(PGS-RR ): " << Rem.CriticalPath << " \n";
3186 }
Andrew Trickd14d7c22013-12-28 21:56:57 +00003187}
3188
3189/// Apply a set of heursitics to a new candidate for PostRA scheduling.
3190///
3191/// \param Cand provides the policy and current best candidate.
3192/// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
3193void PostGenericScheduler::tryCandidate(SchedCandidate &Cand,
3194 SchedCandidate &TryCand) {
3195
3196 // Initialize the candidate if needed.
3197 if (!Cand.isValid()) {
3198 TryCand.Reason = NodeOrder;
3199 return;
3200 }
3201
3202 // Prioritize instructions that read unbuffered resources by stall cycles.
3203 if (tryLess(Top.getLatencyStallCycles(TryCand.SU),
3204 Top.getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
3205 return;
3206
3207 // Avoid critical resource consumption and balance the schedule.
3208 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
3209 TryCand, Cand, ResourceReduce))
3210 return;
3211 if (tryGreater(TryCand.ResDelta.DemandedResources,
3212 Cand.ResDelta.DemandedResources,
3213 TryCand, Cand, ResourceDemand))
3214 return;
3215
3216 // Avoid serializing long latency dependence chains.
3217 if (Cand.Policy.ReduceLatency && tryLatency(TryCand, Cand, Top)) {
3218 return;
3219 }
3220
3221 // Fall through to original instruction order.
3222 if (TryCand.SU->NodeNum < Cand.SU->NodeNum)
3223 TryCand.Reason = NodeOrder;
3224}
3225
3226void PostGenericScheduler::pickNodeFromQueue(SchedCandidate &Cand) {
3227 ReadyQueue &Q = Top.Available;
Andrew Trickd14d7c22013-12-28 21:56:57 +00003228 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
3229 SchedCandidate TryCand(Cand.Policy);
3230 TryCand.SU = *I;
Matthias Braun6ad3d052016-06-25 00:23:00 +00003231 TryCand.AtTop = true;
Andrew Trickd14d7c22013-12-28 21:56:57 +00003232 TryCand.initResourceDelta(DAG, SchedModel);
3233 tryCandidate(Cand, TryCand);
3234 if (TryCand.Reason != NoCand) {
3235 Cand.setBest(TryCand);
3236 DEBUG(traceCandidate(Cand));
3237 }
3238 }
3239}
3240
3241/// Pick the next node to schedule.
3242SUnit *PostGenericScheduler::pickNode(bool &IsTopNode) {
3243 if (DAG->top() == DAG->bottom()) {
3244 assert(Top.Available.empty() && Top.Pending.empty() && "ReadyQ garbage");
Craig Topperc0196b12014-04-14 00:51:57 +00003245 return nullptr;
Andrew Trickd14d7c22013-12-28 21:56:57 +00003246 }
3247 SUnit *SU;
3248 do {
3249 SU = Top.pickOnlyChoice();
Matthias Braun49cb6e92016-05-27 22:14:26 +00003250 if (SU) {
3251 tracePick(Only1, true);
3252 } else {
Andrew Trickd14d7c22013-12-28 21:56:57 +00003253 CandPolicy NoPolicy;
3254 SchedCandidate TopCand(NoPolicy);
3255 // Set the top-down policy based on the state of the current top zone and
3256 // the instructions outside the zone, including the bottom zone.
Craig Topperc0196b12014-04-14 00:51:57 +00003257 setPolicy(TopCand.Policy, /*IsPostRA=*/true, Top, nullptr);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003258 pickNodeFromQueue(TopCand);
3259 assert(TopCand.Reason != NoCand && "failed to find a candidate");
Matthias Braun6ad3d052016-06-25 00:23:00 +00003260 tracePick(TopCand);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003261 SU = TopCand.SU;
3262 }
3263 } while (SU->isScheduled);
3264
3265 IsTopNode = true;
3266 Top.removeReady(SU);
3267
3268 DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " << *SU->getInstr());
3269 return SU;
3270}
3271
3272/// Called after ScheduleDAGMI has scheduled an instruction and updated
3273/// scheduled/remaining flags in the DAG nodes.
3274void PostGenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
3275 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
3276 Top.bumpNode(SU);
3277}
3278
Matthias Braun115efcd2016-11-28 20:11:54 +00003279ScheduleDAGMI *llvm::createGenericSchedPostRA(MachineSchedContext *C) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003280 return new ScheduleDAGMI(C, llvm::make_unique<PostGenericScheduler>(C),
Jonas Paulsson28f29482016-11-09 09:59:27 +00003281 /*RemoveKillFlags=*/true);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003282}
Andrew Tricke1c034f2012-01-17 06:55:03 +00003283
3284//===----------------------------------------------------------------------===//
Andrew Trick90f711d2012-10-15 18:02:27 +00003285// ILP Scheduler. Currently for experimental analysis of heuristics.
3286//===----------------------------------------------------------------------===//
3287
3288namespace {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003289
Andrew Trick90f711d2012-10-15 18:02:27 +00003290/// \brief Order nodes by the ILP metric.
3291struct ILPOrder {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003292 const SchedDFSResult *DFSResult = nullptr;
3293 const BitVector *ScheduledTrees = nullptr;
Andrew Trick90f711d2012-10-15 18:02:27 +00003294 bool MaximizeILP;
3295
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003296 ILPOrder(bool MaxILP) : MaximizeILP(MaxILP) {}
Andrew Trick90f711d2012-10-15 18:02:27 +00003297
3298 /// \brief Apply a less-than relation on node priority.
Andrew Trick48d392e2012-11-28 05:13:28 +00003299 ///
3300 /// (Return true if A comes after B in the Q.)
Andrew Trick90f711d2012-10-15 18:02:27 +00003301 bool operator()(const SUnit *A, const SUnit *B) const {
Andrew Trick48d392e2012-11-28 05:13:28 +00003302 unsigned SchedTreeA = DFSResult->getSubtreeID(A);
3303 unsigned SchedTreeB = DFSResult->getSubtreeID(B);
3304 if (SchedTreeA != SchedTreeB) {
3305 // Unscheduled trees have lower priority.
3306 if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
3307 return ScheduledTrees->test(SchedTreeB);
3308
3309 // Trees with shallower connections have have lower priority.
3310 if (DFSResult->getSubtreeLevel(SchedTreeA)
3311 != DFSResult->getSubtreeLevel(SchedTreeB)) {
3312 return DFSResult->getSubtreeLevel(SchedTreeA)
3313 < DFSResult->getSubtreeLevel(SchedTreeB);
3314 }
3315 }
Andrew Trick90f711d2012-10-15 18:02:27 +00003316 if (MaximizeILP)
Andrew Trick48d392e2012-11-28 05:13:28 +00003317 return DFSResult->getILP(A) < DFSResult->getILP(B);
Andrew Trick90f711d2012-10-15 18:02:27 +00003318 else
Andrew Trick48d392e2012-11-28 05:13:28 +00003319 return DFSResult->getILP(A) > DFSResult->getILP(B);
Andrew Trick90f711d2012-10-15 18:02:27 +00003320 }
3321};
3322
3323/// \brief Schedule based on the ILP metric.
3324class ILPScheduler : public MachineSchedStrategy {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003325 ScheduleDAGMILive *DAG = nullptr;
Andrew Trick90f711d2012-10-15 18:02:27 +00003326 ILPOrder Cmp;
3327
3328 std::vector<SUnit*> ReadyQ;
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003329
Andrew Trick90f711d2012-10-15 18:02:27 +00003330public:
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003331 ILPScheduler(bool MaximizeILP) : Cmp(MaximizeILP) {}
Andrew Trick90f711d2012-10-15 18:02:27 +00003332
Craig Topper4584cd52014-03-07 09:26:03 +00003333 void initialize(ScheduleDAGMI *dag) override {
Andrew Trickd7f890e2013-12-28 21:56:47 +00003334 assert(dag->hasVRegLiveness() && "ILPScheduler needs vreg liveness");
3335 DAG = static_cast<ScheduleDAGMILive*>(dag);
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00003336 DAG->computeDFSResult();
Andrew Trick44f750a2013-01-25 04:01:04 +00003337 Cmp.DFSResult = DAG->getDFSResult();
3338 Cmp.ScheduledTrees = &DAG->getScheduledTrees();
Andrew Trick90f711d2012-10-15 18:02:27 +00003339 ReadyQ.clear();
Andrew Trick90f711d2012-10-15 18:02:27 +00003340 }
3341
Craig Topper4584cd52014-03-07 09:26:03 +00003342 void registerRoots() override {
Benjamin Krameraa598b32012-11-29 14:36:26 +00003343 // Restore the heap in ReadyQ with the updated DFS results.
3344 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
Andrew Trick90f711d2012-10-15 18:02:27 +00003345 }
3346
3347 /// Implement MachineSchedStrategy interface.
3348 /// -----------------------------------------
3349
Andrew Trick48d392e2012-11-28 05:13:28 +00003350 /// Callback to select the highest priority node from the ready Q.
Craig Topper4584cd52014-03-07 09:26:03 +00003351 SUnit *pickNode(bool &IsTopNode) override {
Craig Topperc0196b12014-04-14 00:51:57 +00003352 if (ReadyQ.empty()) return nullptr;
Matt Arsenault4ab769f2013-03-21 00:57:21 +00003353 std::pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
Andrew Trick90f711d2012-10-15 18:02:27 +00003354 SUnit *SU = ReadyQ.back();
3355 ReadyQ.pop_back();
3356 IsTopNode = false;
Andrew Trick1f0bb692013-04-13 06:07:49 +00003357 DEBUG(dbgs() << "Pick node " << "SU(" << SU->NodeNum << ") "
Andrew Trick44f750a2013-01-25 04:01:04 +00003358 << " ILP: " << DAG->getDFSResult()->getILP(SU)
3359 << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU) << " @"
3360 << DAG->getDFSResult()->getSubtreeLevel(
Andrew Trick1f0bb692013-04-13 06:07:49 +00003361 DAG->getDFSResult()->getSubtreeID(SU)) << '\n'
3362 << "Scheduling " << *SU->getInstr());
Andrew Trick90f711d2012-10-15 18:02:27 +00003363 return SU;
3364 }
3365
Andrew Trick44f750a2013-01-25 04:01:04 +00003366 /// \brief Scheduler callback to notify that a new subtree is scheduled.
Craig Topper4584cd52014-03-07 09:26:03 +00003367 void scheduleTree(unsigned SubtreeID) override {
Andrew Trick44f750a2013-01-25 04:01:04 +00003368 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3369 }
3370
Andrew Trick48d392e2012-11-28 05:13:28 +00003371 /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
3372 /// DFSResults, and resort the priority Q.
Craig Topper4584cd52014-03-07 09:26:03 +00003373 void schedNode(SUnit *SU, bool IsTopNode) override {
Andrew Trick48d392e2012-11-28 05:13:28 +00003374 assert(!IsTopNode && "SchedDFSResult needs bottom-up");
Andrew Trick48d392e2012-11-28 05:13:28 +00003375 }
Andrew Trick90f711d2012-10-15 18:02:27 +00003376
Craig Topper4584cd52014-03-07 09:26:03 +00003377 void releaseTopNode(SUnit *) override { /*only called for top roots*/ }
Andrew Trick90f711d2012-10-15 18:02:27 +00003378
Craig Topper4584cd52014-03-07 09:26:03 +00003379 void releaseBottomNode(SUnit *SU) override {
Andrew Trick90f711d2012-10-15 18:02:27 +00003380 ReadyQ.push_back(SU);
3381 std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3382 }
3383};
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003384
3385} // end anonymous namespace
Andrew Trick90f711d2012-10-15 18:02:27 +00003386
3387static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003388 return new ScheduleDAGMILive(C, llvm::make_unique<ILPScheduler>(true));
Andrew Trick90f711d2012-10-15 18:02:27 +00003389}
3390static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003391 return new ScheduleDAGMILive(C, llvm::make_unique<ILPScheduler>(false));
Andrew Trick90f711d2012-10-15 18:02:27 +00003392}
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003393
Andrew Trick90f711d2012-10-15 18:02:27 +00003394static MachineSchedRegistry ILPMaxRegistry(
3395 "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
3396static MachineSchedRegistry ILPMinRegistry(
3397 "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
3398
3399//===----------------------------------------------------------------------===//
Andrew Trick63440872012-01-14 02:17:06 +00003400// Machine Instruction Shuffler for Correctness Testing
3401//===----------------------------------------------------------------------===//
3402
Andrew Tricke77e84e2012-01-13 06:30:30 +00003403#ifndef NDEBUG
3404namespace {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003405
Andrew Trick8823dec2012-03-14 04:00:41 +00003406/// Apply a less-than relation on the node order, which corresponds to the
3407/// instruction order prior to scheduling. IsReverse implements greater-than.
3408template<bool IsReverse>
3409struct SUnitOrder {
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003410 bool operator()(SUnit *A, SUnit *B) const {
Andrew Trick8823dec2012-03-14 04:00:41 +00003411 if (IsReverse)
3412 return A->NodeNum > B->NodeNum;
3413 else
3414 return A->NodeNum < B->NodeNum;
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003415 }
3416};
3417
Andrew Tricke77e84e2012-01-13 06:30:30 +00003418/// Reorder instructions as much as possible.
Andrew Trick8823dec2012-03-14 04:00:41 +00003419class InstructionShuffler : public MachineSchedStrategy {
3420 bool IsAlternating;
3421 bool IsTopDown;
3422
3423 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
3424 // gives nodes with a higher number higher priority causing the latest
3425 // instructions to be scheduled first.
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003426 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false>>
Andrew Trick8823dec2012-03-14 04:00:41 +00003427 TopQ;
3428 // When scheduling bottom-up, use greater-than as the queue priority.
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003429 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true>>
Andrew Trick8823dec2012-03-14 04:00:41 +00003430 BottomQ;
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003431
Andrew Tricke77e84e2012-01-13 06:30:30 +00003432public:
Andrew Trick8823dec2012-03-14 04:00:41 +00003433 InstructionShuffler(bool alternate, bool topdown)
3434 : IsAlternating(alternate), IsTopDown(topdown) {}
Andrew Tricke77e84e2012-01-13 06:30:30 +00003435
Craig Topper9d74a5a2014-04-29 07:58:41 +00003436 void initialize(ScheduleDAGMI*) override {
Andrew Trick8823dec2012-03-14 04:00:41 +00003437 TopQ.clear();
3438 BottomQ.clear();
3439 }
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003440
Andrew Trick8823dec2012-03-14 04:00:41 +00003441 /// Implement MachineSchedStrategy interface.
3442 /// -----------------------------------------
3443
Craig Topper9d74a5a2014-04-29 07:58:41 +00003444 SUnit *pickNode(bool &IsTopNode) override {
Andrew Trick8823dec2012-03-14 04:00:41 +00003445 SUnit *SU;
3446 if (IsTopDown) {
3447 do {
Craig Topperc0196b12014-04-14 00:51:57 +00003448 if (TopQ.empty()) return nullptr;
Andrew Trick8823dec2012-03-14 04:00:41 +00003449 SU = TopQ.top();
3450 TopQ.pop();
3451 } while (SU->isScheduled);
3452 IsTopNode = true;
Matthias Braunb550b762016-04-21 01:54:13 +00003453 } else {
Andrew Trick8823dec2012-03-14 04:00:41 +00003454 do {
Craig Topperc0196b12014-04-14 00:51:57 +00003455 if (BottomQ.empty()) return nullptr;
Andrew Trick8823dec2012-03-14 04:00:41 +00003456 SU = BottomQ.top();
3457 BottomQ.pop();
3458 } while (SU->isScheduled);
3459 IsTopNode = false;
3460 }
3461 if (IsAlternating)
3462 IsTopDown = !IsTopDown;
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003463 return SU;
3464 }
3465
Craig Topper9d74a5a2014-04-29 07:58:41 +00003466 void schedNode(SUnit *SU, bool IsTopNode) override {}
Andrew Trick61f1a272012-05-24 22:11:09 +00003467
Craig Topper9d74a5a2014-04-29 07:58:41 +00003468 void releaseTopNode(SUnit *SU) override {
Andrew Trick8823dec2012-03-14 04:00:41 +00003469 TopQ.push(SU);
3470 }
Craig Topper9d74a5a2014-04-29 07:58:41 +00003471 void releaseBottomNode(SUnit *SU) override {
Andrew Trick8823dec2012-03-14 04:00:41 +00003472 BottomQ.push(SU);
Andrew Tricke77e84e2012-01-13 06:30:30 +00003473 }
3474};
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003475
3476} // end anonymous namespace
Andrew Tricke77e84e2012-01-13 06:30:30 +00003477
Andrew Trick02a80da2012-03-08 01:41:12 +00003478static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
Andrew Trick8823dec2012-03-14 04:00:41 +00003479 bool Alternate = !ForceTopDown && !ForceBottomUp;
3480 bool TopDown = !ForceBottomUp;
Benjamin Kramer05e7a842012-03-14 11:26:37 +00003481 assert((TopDown || !ForceTopDown) &&
Andrew Trick8823dec2012-03-14 04:00:41 +00003482 "-misched-topdown incompatible with -misched-bottomup");
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003483 return new ScheduleDAGMILive(
3484 C, llvm::make_unique<InstructionShuffler>(Alternate, TopDown));
Andrew Tricke77e84e2012-01-13 06:30:30 +00003485}
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003486
Andrew Trick8823dec2012-03-14 04:00:41 +00003487static MachineSchedRegistry ShufflerRegistry(
3488 "shuffle", "Shuffle machine instructions alternating directions",
3489 createInstructionShuffler);
Andrew Tricke77e84e2012-01-13 06:30:30 +00003490#endif // !NDEBUG
Andrew Trickea9fd952013-01-25 07:45:29 +00003491
3492//===----------------------------------------------------------------------===//
Andrew Trickd7f890e2013-12-28 21:56:47 +00003493// GraphWriter support for ScheduleDAGMILive.
Andrew Trickea9fd952013-01-25 07:45:29 +00003494//===----------------------------------------------------------------------===//
3495
3496#ifndef NDEBUG
3497namespace llvm {
3498
3499template<> struct GraphTraits<
3500 ScheduleDAGMI*> : public GraphTraits<ScheduleDAG*> {};
3501
3502template<>
3503struct DOTGraphTraits<ScheduleDAGMI*> : public DefaultDOTGraphTraits {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003504 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
Andrew Trickea9fd952013-01-25 07:45:29 +00003505
3506 static std::string getGraphName(const ScheduleDAG *G) {
3507 return G->MF.getName();
3508 }
3509
3510 static bool renderGraphFromBottomUp() {
3511 return true;
3512 }
3513
3514 static bool isNodeHidden(const SUnit *Node) {
Matthias Braund78ee542015-09-17 21:09:59 +00003515 if (ViewMISchedCutoff == 0)
3516 return false;
3517 return (Node->Preds.size() > ViewMISchedCutoff
3518 || Node->Succs.size() > ViewMISchedCutoff);
Andrew Trickea9fd952013-01-25 07:45:29 +00003519 }
3520
Andrew Trickea9fd952013-01-25 07:45:29 +00003521 /// If you want to override the dot attributes printed for a particular
3522 /// edge, override this method.
3523 static std::string getEdgeAttributes(const SUnit *Node,
3524 SUnitIterator EI,
3525 const ScheduleDAG *Graph) {
3526 if (EI.isArtificialDep())
3527 return "color=cyan,style=dashed";
3528 if (EI.isCtrlDep())
3529 return "color=blue,style=dashed";
3530 return "";
3531 }
3532
3533 static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) {
Alp Tokere69170a2014-06-26 22:52:05 +00003534 std::string Str;
3535 raw_string_ostream SS(Str);
Andrew Trickd7f890e2013-12-28 21:56:47 +00003536 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3537 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
Craig Topperc0196b12014-04-14 00:51:57 +00003538 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
Andrew Trick7609b7d2013-09-06 17:32:42 +00003539 SS << "SU:" << SU->NodeNum;
3540 if (DFS)
3541 SS << " I:" << DFS->getNumInstrs(SU);
Andrew Trickea9fd952013-01-25 07:45:29 +00003542 return SS.str();
3543 }
3544 static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G) {
3545 return G->getGraphNodeLabel(SU);
3546 }
3547
Andrew Trickd7f890e2013-12-28 21:56:47 +00003548 static std::string getNodeAttributes(const SUnit *N, const ScheduleDAG *G) {
Andrew Trickea9fd952013-01-25 07:45:29 +00003549 std::string Str("shape=Mrecord");
Andrew Trickd7f890e2013-12-28 21:56:47 +00003550 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3551 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
Craig Topperc0196b12014-04-14 00:51:57 +00003552 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
Andrew Trickea9fd952013-01-25 07:45:29 +00003553 if (DFS) {
3554 Str += ",style=filled,fillcolor=\"#";
3555 Str += DOT::getColorString(DFS->getSubtreeID(N));
3556 Str += '"';
3557 }
3558 return Str;
3559 }
3560};
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003561
3562} // end namespace llvm
Andrew Trickea9fd952013-01-25 07:45:29 +00003563#endif // NDEBUG
3564
3565/// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
3566/// rendered using 'dot'.
3567///
3568void ScheduleDAGMI::viewGraph(const Twine &Name, const Twine &Title) {
3569#ifndef NDEBUG
3570 ViewGraph(this, Name, false, Title);
3571#else
3572 errs() << "ScheduleDAGMI::viewGraph is only available in debug builds on "
3573 << "systems with Graphviz or gv!\n";
3574#endif // NDEBUG
3575}
3576
3577/// Out-of-line implementation with no arguments is handy for gdb.
3578void ScheduleDAGMI::viewGraph() {
3579 viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName());
3580}