blob: 90dad9d399fecc97196ad7a8070e40506a546325 [file] [log] [blame]
Andrew Trick5429a6b2012-05-17 22:37:09 +00001//===- MachineScheduler.cpp - Machine Instruction Scheduler ---------------===//
Andrew Trick96f678f2012-01-13 06:30:30 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// MachineScheduler schedules machine instructions after phi elimination. It
11// preserves LiveIntervals so it can be invoked before register allocation.
12//
13//===----------------------------------------------------------------------===//
14
Chandler Carruthe3e43d92017-06-06 11:49:48 +000015#include "llvm/CodeGen/MachineScheduler.h"
Eugene Zelenko096e40d2017-02-22 22:32:51 +000016#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/BitVector.h"
18#include "llvm/ADT/DenseMap.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000019#include "llvm/ADT/PriorityQueue.h"
Eugene Zelenko096e40d2017-02-22 22:32:51 +000020#include "llvm/ADT/STLExtras.h"
Chandler Carruthe3e43d92017-06-06 11:49:48 +000021#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/iterator_range.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000023#include "llvm/Analysis/AliasAnalysis.h"
Eugene Zelenko096e40d2017-02-22 22:32:51 +000024#include "llvm/CodeGen/LiveInterval.h"
Matthias Braunfa621d22017-12-13 02:51:04 +000025#include "llvm/CodeGen/LiveIntervals.h"
Eugene Zelenko096e40d2017-02-22 22:32:51 +000026#include "llvm/CodeGen/MachineBasicBlock.h"
Jakub Staszak760fa5d2013-03-10 13:11:23 +000027#include "llvm/CodeGen/MachineDominators.h"
Eugene Zelenko096e40d2017-02-22 22:32:51 +000028#include "llvm/CodeGen/MachineFunction.h"
29#include "llvm/CodeGen/MachineFunctionPass.h"
30#include "llvm/CodeGen/MachineInstr.h"
Jakub Staszak760fa5d2013-03-10 13:11:23 +000031#include "llvm/CodeGen/MachineLoopInfo.h"
Eugene Zelenko096e40d2017-02-22 22:32:51 +000032#include "llvm/CodeGen/MachineOperand.h"
33#include "llvm/CodeGen/MachinePassRegistry.h"
Andrew Trick1f8b48a2013-06-21 18:32:58 +000034#include "llvm/CodeGen/MachineRegisterInfo.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000035#include "llvm/CodeGen/Passes.h"
Andrew Trick15252602012-06-06 20:29:31 +000036#include "llvm/CodeGen/RegisterClassInfo.h"
Chandler Carruthe3e43d92017-06-06 11:49:48 +000037#include "llvm/CodeGen/RegisterPressure.h"
Eugene Zelenko096e40d2017-02-22 22:32:51 +000038#include "llvm/CodeGen/ScheduleDAG.h"
39#include "llvm/CodeGen/ScheduleDAGInstrs.h"
40#include "llvm/CodeGen/ScheduleDAGMutation.h"
Andrew Trick53e98a22012-11-28 05:13:24 +000041#include "llvm/CodeGen/ScheduleDFS.h"
Andrew Trick0a39d4e2012-05-24 22:11:09 +000042#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
Eugene Zelenko096e40d2017-02-22 22:32:51 +000043#include "llvm/CodeGen/SlotIndexes.h"
Francis Visoiu Mistrih50c71c52018-11-29 20:03:19 +000044#include "llvm/CodeGen/TargetFrameLowering.h"
David Blaikie48319232017-11-08 01:01:31 +000045#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikiee3a9b4c2017-11-17 01:07:10 +000046#include "llvm/CodeGen/TargetLowering.h"
Matthias Braun6a6190d2016-05-10 03:21:59 +000047#include "llvm/CodeGen/TargetPassConfig.h"
David Blaikiee3a9b4c2017-11-17 01:07:10 +000048#include "llvm/CodeGen/TargetRegisterInfo.h"
Eugene Zelenko096e40d2017-02-22 22:32:51 +000049#include "llvm/CodeGen/TargetSchedule.h"
David Blaikiee3a9b4c2017-11-17 01:07:10 +000050#include "llvm/CodeGen/TargetSubtargetInfo.h"
Nico Weber0f38c602018-04-30 14:59:11 +000051#include "llvm/Config/llvm-config.h"
Eugene Zelenko096e40d2017-02-22 22:32:51 +000052#include "llvm/MC/LaneBitmask.h"
53#include "llvm/Pass.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000054#include "llvm/Support/CommandLine.h"
Eugene Zelenko096e40d2017-02-22 22:32:51 +000055#include "llvm/Support/Compiler.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000056#include "llvm/Support/Debug.h"
57#include "llvm/Support/ErrorHandling.h"
Andrew Trick30849792013-01-25 07:45:29 +000058#include "llvm/Support/GraphWriter.h"
David Blaikie9d9a46a2018-03-23 23:58:25 +000059#include "llvm/Support/MachineValueType.h"
Andrew Trick96f678f2012-01-13 06:30:30 +000060#include "llvm/Support/raw_ostream.h"
Eugene Zelenko096e40d2017-02-22 22:32:51 +000061#include <algorithm>
62#include <cassert>
63#include <cstdint>
64#include <iterator>
65#include <limits>
66#include <memory>
67#include <string>
68#include <tuple>
69#include <utility>
70#include <vector>
Andrew Trickc6cf11b2012-01-17 06:55:07 +000071
Andrew Trick96f678f2012-01-13 06:30:30 +000072using namespace llvm;
73
Matthias Braun94c49042017-05-25 21:26:32 +000074#define DEBUG_TYPE "machine-scheduler"
Chandler Carruth8677f2f2014-04-22 02:02:50 +000075
Andrew Trick78e5efe2012-09-11 00:39:15 +000076namespace llvm {
Eugene Zelenko096e40d2017-02-22 22:32:51 +000077
Andrew Trick78e5efe2012-09-11 00:39:15 +000078cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
79 cl::desc("Force top-down list scheduling"));
80cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
81 cl::desc("Force bottom-up list scheduling"));
Gerolf Hoflehner9fbb0122014-08-07 21:49:44 +000082cl::opt<bool>
83DumpCriticalPathLength("misched-dcpl", cl::Hidden,
84 cl::desc("Print critical path length to stdout"));
Eugene Zelenko096e40d2017-02-22 22:32:51 +000085
86} // end namespace llvm
Andrew Trick17d35e52012-03-14 04:00:41 +000087
Andrew Trick0df7f882012-03-07 00:18:25 +000088#ifndef NDEBUG
89static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
90 cl::desc("Pop up a window to show MISched dags after they are processed"));
Lang Hames23f1cbb2012-03-19 18:38:38 +000091
Matthias Braun4bdc7f82015-09-17 21:09:59 +000092/// In some situations a few uninteresting nodes depend on nearly all other
93/// nodes in the graph, provide a cutoff to hide them.
94static cl::opt<unsigned> ViewMISchedCutoff("view-misched-cutoff", cl::Hidden,
95 cl::desc("Hide nodes with more predecessor/successor than cutoff"));
96
Lang Hames23f1cbb2012-03-19 18:38:38 +000097static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
98 cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
Andrew Trickd3f8d6e2013-12-28 21:57:02 +000099
100static cl::opt<std::string> SchedOnlyFunc("misched-only-func", cl::Hidden,
101 cl::desc("Only schedule this function"));
102static cl::opt<unsigned> SchedOnlyBlock("misched-only-block", cl::Hidden,
Francis Visoiu Mistrihca0df552017-12-04 17:18:51 +0000103 cl::desc("Only schedule this MBB#"));
Matthias Braun9214de52018-09-19 20:50:49 +0000104static cl::opt<bool> PrintDAGs("misched-print-dags", cl::Hidden,
105 cl::desc("Print schedule DAGs"));
Andrew Trick0df7f882012-03-07 00:18:25 +0000106#else
Matthias Braun9214de52018-09-19 20:50:49 +0000107static const bool ViewMISchedDAGs = false;
108static const bool PrintDAGs = false;
Andrew Trick0df7f882012-03-07 00:18:25 +0000109#endif // NDEBUG
110
Matthias Braun14c17392016-04-22 19:09:17 +0000111/// Avoid quadratic complexity in unusually large basic blocks by limiting the
112/// size of the ready lists.
113static cl::opt<unsigned> ReadyListLimit("misched-limit", cl::Hidden,
114 cl::desc("Limit ready list to N instructions"), cl::init(256));
115
Andrew Trick42ebb3a2013-09-04 20:59:59 +0000116static cl::opt<bool> EnableRegPressure("misched-regpressure", cl::Hidden,
117 cl::desc("Enable register pressure scheduling."), cl::init(true));
118
Andrew Trickea574332013-08-23 17:48:43 +0000119static cl::opt<bool> EnableCyclicPath("misched-cyclicpath", cl::Hidden,
Andrew Trickfc7fd092013-09-09 23:31:14 +0000120 cl::desc("Enable cyclic critical path analysis."), cl::init(true));
Andrew Trickea574332013-08-23 17:48:43 +0000121
Jun Bum Lim232aafc2016-04-15 14:58:38 +0000122static cl::opt<bool> EnableMemOpCluster("misched-cluster", cl::Hidden,
123 cl::desc("Enable memop clustering."),
124 cl::init(true));
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000125
Andrew Trickfff2d3a2013-03-08 05:40:34 +0000126static cl::opt<bool> VerifyScheduling("verify-misched", cl::Hidden,
127 cl::desc("Verify machine instrs before and after machine scheduling"));
128
Andrew Trick178f7d02013-01-25 04:01:04 +0000129// DAG subtrees must have at least this many nodes.
130static const unsigned MinSubtreeSize = 8;
131
Juergen Ributzka35436252013-11-19 00:57:56 +0000132// Pin the vtables to this file.
133void MachineSchedStrategy::anchor() {}
Eugene Zelenko096e40d2017-02-22 22:32:51 +0000134
Juergen Ributzka35436252013-11-19 00:57:56 +0000135void ScheduleDAGMutation::anchor() {}
136
Andrew Trick5edf2f02012-01-14 02:17:06 +0000137//===----------------------------------------------------------------------===//
138// Machine Instruction Scheduling Pass and Registry
139//===----------------------------------------------------------------------===//
140
Eugene Zelenko096e40d2017-02-22 22:32:51 +0000141MachineSchedContext::MachineSchedContext() {
Andrew Trick86b7e2a2012-04-24 20:36:19 +0000142 RegClassInfo = new RegisterClassInfo();
143}
144
145MachineSchedContext::~MachineSchedContext() {
146 delete RegClassInfo;
147}
148
Andrew Trick96f678f2012-01-13 06:30:30 +0000149namespace {
Eugene Zelenko096e40d2017-02-22 22:32:51 +0000150
Andrew Tricka38b0de2013-12-28 21:56:47 +0000151/// Base class for a machine scheduler class that can run at any point.
152class MachineSchedulerBase : public MachineSchedContext,
153 public MachineFunctionPass {
154public:
155 MachineSchedulerBase(char &ID): MachineFunctionPass(ID) {}
156
Craig Topper4ba84432014-04-14 00:51:57 +0000157 void print(raw_ostream &O, const Module* = nullptr) const override;
Andrew Tricka38b0de2013-12-28 21:56:47 +0000158
159protected:
Matthias Braune9564b22015-11-03 01:53:29 +0000160 void scheduleRegions(ScheduleDAGInstrs &Scheduler, bool FixKillFlags);
Andrew Tricka38b0de2013-12-28 21:56:47 +0000161};
162
Andrew Trick42b7a712012-01-17 06:55:03 +0000163/// MachineScheduler runs after coalescing and before register allocation.
Andrew Tricka38b0de2013-12-28 21:56:47 +0000164class MachineScheduler : public MachineSchedulerBase {
Andrew Trick96f678f2012-01-13 06:30:30 +0000165public:
Andrew Trick42b7a712012-01-17 06:55:03 +0000166 MachineScheduler();
Andrew Trick96f678f2012-01-13 06:30:30 +0000167
Craig Topper9f998de2014-03-07 09:26:03 +0000168 void getAnalysisUsage(AnalysisUsage &AU) const override;
Andrew Trick96f678f2012-01-13 06:30:30 +0000169
Craig Topper9f998de2014-03-07 09:26:03 +0000170 bool runOnMachineFunction(MachineFunction&) override;
Andrew Trick96f678f2012-01-13 06:30:30 +0000171
Andrew Trick96f678f2012-01-13 06:30:30 +0000172 static char ID; // Class identification, replacement for typeinfo
Andrew Trickf45edcc2013-09-20 05:14:41 +0000173
174protected:
175 ScheduleDAGInstrs *createMachineScheduler();
Andrew Trick96f678f2012-01-13 06:30:30 +0000176};
Andrew Trickc5443a92013-12-28 21:56:51 +0000177
178/// PostMachineScheduler runs after shortly before code emission.
179class PostMachineScheduler : public MachineSchedulerBase {
180public:
181 PostMachineScheduler();
182
Craig Topper9f998de2014-03-07 09:26:03 +0000183 void getAnalysisUsage(AnalysisUsage &AU) const override;
Andrew Trickc5443a92013-12-28 21:56:51 +0000184
Craig Topper9f998de2014-03-07 09:26:03 +0000185 bool runOnMachineFunction(MachineFunction&) override;
Andrew Trickc5443a92013-12-28 21:56:51 +0000186
187 static char ID; // Class identification, replacement for typeinfo
188
189protected:
190 ScheduleDAGInstrs *createPostMachineScheduler();
191};
Eugene Zelenko096e40d2017-02-22 22:32:51 +0000192
193} // end anonymous namespace
Andrew Trick96f678f2012-01-13 06:30:30 +0000194
Andrew Trick42b7a712012-01-17 06:55:03 +0000195char MachineScheduler::ID = 0;
Andrew Trick96f678f2012-01-13 06:30:30 +0000196
Andrew Trick42b7a712012-01-17 06:55:03 +0000197char &llvm::MachineSchedulerID = MachineScheduler::ID;
Andrew Trick96f678f2012-01-13 06:30:30 +0000198
Matthias Braun94c49042017-05-25 21:26:32 +0000199INITIALIZE_PASS_BEGIN(MachineScheduler, DEBUG_TYPE,
Andrew Trick96f678f2012-01-13 06:30:30 +0000200 "Machine Instruction Scheduler", false, false)
Chandler Carruth91468332015-09-09 17:55:00 +0000201INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Davide Italianoa7925b82017-03-24 20:52:56 +0000202INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
Andrew Trick96f678f2012-01-13 06:30:30 +0000203INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
204INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
Matthias Braun94c49042017-05-25 21:26:32 +0000205INITIALIZE_PASS_END(MachineScheduler, DEBUG_TYPE,
Andrew Trick96f678f2012-01-13 06:30:30 +0000206 "Machine Instruction Scheduler", false, false)
207
Eugene Zelenko8fd05042017-09-11 23:00:48 +0000208MachineScheduler::MachineScheduler() : MachineSchedulerBase(ID) {
Andrew Trick42b7a712012-01-17 06:55:03 +0000209 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Andrew Trick96f678f2012-01-13 06:30:30 +0000210}
211
Andrew Trick42b7a712012-01-17 06:55:03 +0000212void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
Andrew Trick96f678f2012-01-13 06:30:30 +0000213 AU.setPreservesCFG();
214 AU.addRequiredID(MachineDominatorsID);
215 AU.addRequired<MachineLoopInfo>();
Chandler Carruth91468332015-09-09 17:55:00 +0000216 AU.addRequired<AAResultsWrapperPass>();
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000217 AU.addRequired<TargetPassConfig>();
Andrew Trick96f678f2012-01-13 06:30:30 +0000218 AU.addRequired<SlotIndexes>();
219 AU.addPreserved<SlotIndexes>();
220 AU.addRequired<LiveIntervals>();
221 AU.addPreserved<LiveIntervals>();
Andrew Trick96f678f2012-01-13 06:30:30 +0000222 MachineFunctionPass::getAnalysisUsage(AU);
223}
224
Andrew Trickc5443a92013-12-28 21:56:51 +0000225char PostMachineScheduler::ID = 0;
226
227char &llvm::PostMachineSchedulerID = PostMachineScheduler::ID;
228
229INITIALIZE_PASS(PostMachineScheduler, "postmisched",
Saleem Abdulrasool69c6fc42013-12-28 22:47:55 +0000230 "PostRA Machine Instruction Scheduler", false, false)
Andrew Trickc5443a92013-12-28 21:56:51 +0000231
Eugene Zelenko8fd05042017-09-11 23:00:48 +0000232PostMachineScheduler::PostMachineScheduler() : MachineSchedulerBase(ID) {
Andrew Trickc5443a92013-12-28 21:56:51 +0000233 initializePostMachineSchedulerPass(*PassRegistry::getPassRegistry());
234}
235
236void PostMachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
237 AU.setPreservesCFG();
238 AU.addRequiredID(MachineDominatorsID);
239 AU.addRequired<MachineLoopInfo>();
240 AU.addRequired<TargetPassConfig>();
241 MachineFunctionPass::getAnalysisUsage(AU);
242}
243
Serge Gueltonbbe5fdb2018-11-09 17:19:45 +0000244MachinePassRegistry<MachineSchedRegistry::ScheduleDAGCtor>
245 MachineSchedRegistry::Registry;
Andrew Trick96f678f2012-01-13 06:30:30 +0000246
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000247/// A dummy default scheduler factory indicates whether the scheduler
248/// is overridden on the command line.
249static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
Craig Topper4ba84432014-04-14 00:51:57 +0000250 return nullptr;
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000251}
Andrew Trick96f678f2012-01-13 06:30:30 +0000252
253/// MachineSchedOpt allows command line selection of the scheduler.
254static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
Eugene Zelenko096e40d2017-02-22 22:32:51 +0000255 RegisterPassParser<MachineSchedRegistry>>
Andrew Trick96f678f2012-01-13 06:30:30 +0000256MachineSchedOpt("misched",
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000257 cl::init(&useDefaultMachineSched), cl::Hidden,
Andrew Trick96f678f2012-01-13 06:30:30 +0000258 cl::desc("Machine instruction scheduler to use"));
259
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000260static MachineSchedRegistry
Andrew Trick17d35e52012-03-14 04:00:41 +0000261DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000262 useDefaultMachineSched);
263
Eric Christopherfba5b652015-03-11 22:56:10 +0000264static cl::opt<bool> EnableMachineSched(
265 "enable-misched",
266 cl::desc("Enable the machine instruction scheduling pass."), cl::init(true),
267 cl::Hidden);
268
Chad Rosierf16748e2016-01-20 23:08:32 +0000269static cl::opt<bool> EnablePostRAMachineSched(
270 "enable-post-misched",
271 cl::desc("Enable the post-ra machine instruction scheduling pass."),
272 cl::init(true), cl::Hidden);
273
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000274/// Decrement this iterator until reaching the top or a non-debug instr.
Andrew Trick663bd992013-08-30 04:36:57 +0000275static MachineBasicBlock::const_iterator
276priorNonDebug(MachineBasicBlock::const_iterator I,
277 MachineBasicBlock::const_iterator Beg) {
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000278 assert(I != Beg && "reached the top of the region, cannot decrement");
279 while (--I != Beg) {
Shiva Chen24abe712018-05-09 02:42:00 +0000280 if (!I->isDebugInstr())
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000281 break;
282 }
283 return I;
284}
285
Andrew Trick663bd992013-08-30 04:36:57 +0000286/// Non-const version.
287static MachineBasicBlock::iterator
288priorNonDebug(MachineBasicBlock::iterator I,
289 MachineBasicBlock::const_iterator Beg) {
Duncan P. N. Exon Smithe3c3e552016-08-16 23:34:07 +0000290 return priorNonDebug(MachineBasicBlock::const_iterator(I), Beg)
291 .getNonConstIterator();
Andrew Trick663bd992013-08-30 04:36:57 +0000292}
293
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000294/// If this iterator is a debug value, increment until reaching the End or a
295/// non-debug instruction.
Andrew Trickc94e7b52013-08-31 05:17:58 +0000296static MachineBasicBlock::const_iterator
297nextIfDebug(MachineBasicBlock::const_iterator I,
298 MachineBasicBlock::const_iterator End) {
Andrew Trick811d92682012-05-17 18:35:03 +0000299 for(; I != End; ++I) {
Shiva Chen24abe712018-05-09 02:42:00 +0000300 if (!I->isDebugInstr())
Andrew Trickeb45ebb2012-04-24 18:04:34 +0000301 break;
302 }
303 return I;
304}
305
Andrew Trickc94e7b52013-08-31 05:17:58 +0000306/// Non-const version.
307static MachineBasicBlock::iterator
308nextIfDebug(MachineBasicBlock::iterator I,
309 MachineBasicBlock::const_iterator End) {
Duncan P. N. Exon Smithe3c3e552016-08-16 23:34:07 +0000310 return nextIfDebug(MachineBasicBlock::const_iterator(I), End)
311 .getNonConstIterator();
Andrew Trickc94e7b52013-08-31 05:17:58 +0000312}
313
Andrew Trickb0dfcee2013-09-24 17:11:19 +0000314/// Instantiate a ScheduleDAGInstrs that will be owned by the caller.
Andrew Trickf45edcc2013-09-20 05:14:41 +0000315ScheduleDAGInstrs *MachineScheduler::createMachineScheduler() {
316 // Select the scheduler, or set the default.
317 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
318 if (Ctor != useDefaultMachineSched)
319 return Ctor(this);
320
321 // Get the default scheduler set by the target for this function.
322 ScheduleDAGInstrs *Scheduler = PassConfig->createMachineScheduler(this);
323 if (Scheduler)
324 return Scheduler;
325
326 // Default to GenericScheduler.
Andrew Trick9e76e1d2013-12-28 21:56:57 +0000327 return createGenericSchedLive(this);
Andrew Trickf45edcc2013-09-20 05:14:41 +0000328}
329
Andrew Trickc5443a92013-12-28 21:56:51 +0000330/// Instantiate a ScheduleDAGInstrs for PostRA scheduling that will be owned by
331/// the caller. We don't have a command line option to override the postRA
332/// scheduler. The Target must configure it.
333ScheduleDAGInstrs *PostMachineScheduler::createPostMachineScheduler() {
334 // Get the postRA scheduler set by the target for this function.
335 ScheduleDAGInstrs *Scheduler = PassConfig->createPostMachineScheduler(this);
336 if (Scheduler)
337 return Scheduler;
338
339 // Default to GenericScheduler.
Andrew Trick9e76e1d2013-12-28 21:56:57 +0000340 return createGenericSchedPostRA(this);
Andrew Trickc5443a92013-12-28 21:56:51 +0000341}
342
Andrew Trickcb058d52012-03-14 04:00:38 +0000343/// Top-level MachineScheduler pass driver.
344///
345/// Visit blocks in function order. Divide each block into scheduling regions
Andrew Trick17d35e52012-03-14 04:00:41 +0000346/// and visit them bottom-up. Visiting regions bottom-up is not required, but is
347/// consistent with the DAG builder, which traverses the interior of the
348/// scheduling regions bottom-up.
Andrew Trickcb058d52012-03-14 04:00:38 +0000349///
350/// This design avoids exposing scheduling boundaries to the DAG builder,
Andrew Trick17d35e52012-03-14 04:00:41 +0000351/// simplifying the DAG builder's support for "special" target instructions.
352/// At the same time the design allows target schedulers to operate across
Hiroshi Inoue73d058a2018-06-20 05:29:26 +0000353/// scheduling boundaries, for example to bundle the boundary instructions
Andrew Trickcb058d52012-03-14 04:00:38 +0000354/// without reordering them. This creates complexity, because the target
355/// scheduler must update the RegionBegin and RegionEnd positions cached by
356/// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
357/// design would be to split blocks at scheduling boundaries, but LLVM has a
358/// general bias against block splitting purely for implementation simplicity.
Andrew Trick42b7a712012-01-17 06:55:03 +0000359bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
Matthias Braund3181392017-12-15 22:22:58 +0000360 if (skipFunction(mf.getFunction()))
Chad Rosier1355bf72016-01-20 22:38:25 +0000361 return false;
362
Eric Christopherfba5b652015-03-11 22:56:10 +0000363 if (EnableMachineSched.getNumOccurrences()) {
364 if (!EnableMachineSched)
365 return false;
366 } else if (!mf.getSubtarget().enableMachineScheduler())
367 return false;
368
Nicola Zaghen0818e782018-05-14 12:53:11 +0000369 LLVM_DEBUG(dbgs() << "Before MISched:\n"; mf.print(dbgs()));
Andrew Trick89c324b2012-05-10 21:06:21 +0000370
Andrew Trick96f678f2012-01-13 06:30:30 +0000371 // Initialize the context of the pass.
372 MF = &mf;
373 MLI = &getAnalysis<MachineLoopInfo>();
374 MDT = &getAnalysis<MachineDominatorTree>();
Andrew Trickd04ec0c2012-03-09 00:52:20 +0000375 PassConfig = &getAnalysis<TargetPassConfig>();
Chandler Carruth91468332015-09-09 17:55:00 +0000376 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Andrew Trickc174eaf2012-03-08 01:41:12 +0000377
Lang Hames907cc8f2012-01-27 22:36:19 +0000378 LIS = &getAnalysis<LiveIntervals>();
Andrew Trick96f678f2012-01-13 06:30:30 +0000379
Andrew Trickfff2d3a2013-03-08 05:40:34 +0000380 if (VerifyScheduling) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000381 LLVM_DEBUG(LIS->dump());
Andrew Trickfff2d3a2013-03-08 05:40:34 +0000382 MF->verify(this, "Before machine scheduling.");
383 }
Andrew Trick86b7e2a2012-04-24 20:36:19 +0000384 RegClassInfo->runOnMachineFunction(*MF);
Andrew Trick006e1ab2012-04-24 17:56:43 +0000385
Andrew Trickf45edcc2013-09-20 05:14:41 +0000386 // Instantiate the selected scheduler for this target, function, and
387 // optimization level.
Ahmed Charlesf4ccd112014-03-06 05:51:42 +0000388 std::unique_ptr<ScheduleDAGInstrs> Scheduler(createMachineScheduler());
Matthias Braune9564b22015-11-03 01:53:29 +0000389 scheduleRegions(*Scheduler, false);
Andrew Tricka38b0de2013-12-28 21:56:47 +0000390
Nicola Zaghen0818e782018-05-14 12:53:11 +0000391 LLVM_DEBUG(LIS->dump());
Andrew Tricka38b0de2013-12-28 21:56:47 +0000392 if (VerifyScheduling)
393 MF->verify(this, "After machine scheduling.");
394 return true;
395}
396
Andrew Trickc5443a92013-12-28 21:56:51 +0000397bool PostMachineScheduler::runOnMachineFunction(MachineFunction &mf) {
Matthias Braund3181392017-12-15 22:22:58 +0000398 if (skipFunction(mf.getFunction()))
Paul Robinson5fa58a52014-03-31 17:43:35 +0000399 return false;
400
Chad Rosierf16748e2016-01-20 23:08:32 +0000401 if (EnablePostRAMachineSched.getNumOccurrences()) {
402 if (!EnablePostRAMachineSched)
403 return false;
404 } else if (!mf.getSubtarget().enablePostRAScheduler()) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000405 LLVM_DEBUG(dbgs() << "Subtarget disables post-MI-sched.\n");
Andrew Trick5f22dd72014-06-04 07:06:27 +0000406 return false;
407 }
Nicola Zaghen0818e782018-05-14 12:53:11 +0000408 LLVM_DEBUG(dbgs() << "Before post-MI-sched:\n"; mf.print(dbgs()));
Andrew Trickc5443a92013-12-28 21:56:51 +0000409
410 // Initialize the context of the pass.
411 MF = &mf;
Jonas Paulsson59bdb882017-08-17 08:33:44 +0000412 MLI = &getAnalysis<MachineLoopInfo>();
Andrew Trickc5443a92013-12-28 21:56:51 +0000413 PassConfig = &getAnalysis<TargetPassConfig>();
414
415 if (VerifyScheduling)
416 MF->verify(this, "Before post machine scheduling.");
417
418 // Instantiate the selected scheduler for this target, function, and
419 // optimization level.
Ahmed Charlesf4ccd112014-03-06 05:51:42 +0000420 std::unique_ptr<ScheduleDAGInstrs> Scheduler(createPostMachineScheduler());
Matthias Braune9564b22015-11-03 01:53:29 +0000421 scheduleRegions(*Scheduler, true);
Andrew Trickc5443a92013-12-28 21:56:51 +0000422
423 if (VerifyScheduling)
424 MF->verify(this, "After post machine scheduling.");
425 return true;
426}
427
Andrew Trick9e76e1d2013-12-28 21:56:57 +0000428/// Return true of the given instruction should not be included in a scheduling
429/// region.
430///
431/// MachineScheduler does not currently support scheduling across calls. To
432/// handle calls, the DAG builder needs to be modified to create register
433/// anti/output dependencies on the registers clobbered by the call's regmask
434/// operand. In PreRA scheduling, the stack pointer adjustment already prevents
435/// scheduling across calls. In PostRA scheduling, we need the isCall to enforce
436/// the boundary, but there would be no benefit to postRA scheduling across
437/// calls this late anyway.
438static bool isSchedBoundary(MachineBasicBlock::iterator MI,
439 MachineBasicBlock *MBB,
440 MachineFunction *MF,
Matthias Braune9564b22015-11-03 01:53:29 +0000441 const TargetInstrInfo *TII) {
Duncan P. N. Exon Smith567409d2016-06-30 00:01:54 +0000442 return MI->isCall() || TII->isSchedulingBoundary(*MI, MBB, *MF);
Andrew Trick9e76e1d2013-12-28 21:56:57 +0000443}
444
Jonas Paulsson59bdb882017-08-17 08:33:44 +0000445/// A region of an MBB for scheduling.
Mikael Holmendb486282017-09-13 14:07:47 +0000446namespace {
Jonas Paulsson59bdb882017-08-17 08:33:44 +0000447struct SchedRegion {
448 /// RegionBegin is the first instruction in the scheduling region, and
449 /// RegionEnd is either MBB->end() or the scheduling boundary after the
450 /// last instruction in the scheduling region. These iterators cannot refer
451 /// to instructions outside of the identified scheduling region because
452 /// those may be reordered before scheduling this region.
453 MachineBasicBlock::iterator RegionBegin;
454 MachineBasicBlock::iterator RegionEnd;
455 unsigned NumRegionInstrs;
Eugene Zelenko8fd05042017-09-11 23:00:48 +0000456
Jonas Paulsson59bdb882017-08-17 08:33:44 +0000457 SchedRegion(MachineBasicBlock::iterator B, MachineBasicBlock::iterator E,
458 unsigned N) :
459 RegionBegin(B), RegionEnd(E), NumRegionInstrs(N) {}
460};
Mikael Holmendb486282017-09-13 14:07:47 +0000461} // end anonymous namespace
Jonas Paulsson59bdb882017-08-17 08:33:44 +0000462
Eugene Zelenko8fd05042017-09-11 23:00:48 +0000463using MBBRegionsVector = SmallVector<SchedRegion, 16>;
464
Jonas Paulsson59bdb882017-08-17 08:33:44 +0000465static void
466getSchedRegions(MachineBasicBlock *MBB,
467 MBBRegionsVector &Regions,
468 bool RegionsTopDown) {
469 MachineFunction *MF = MBB->getParent();
470 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
471
472 MachineBasicBlock::iterator I = nullptr;
473 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
474 RegionEnd != MBB->begin(); RegionEnd = I) {
475
476 // Avoid decrementing RegionEnd for blocks with no terminator.
477 if (RegionEnd != MBB->end() ||
478 isSchedBoundary(&*std::prev(RegionEnd), &*MBB, MF, TII)) {
479 --RegionEnd;
480 }
481
482 // The next region starts above the previous region. Look backward in the
483 // instruction stream until we find the nearest boundary.
484 unsigned NumRegionInstrs = 0;
485 I = RegionEnd;
486 for (;I != MBB->begin(); --I) {
487 MachineInstr &MI = *std::prev(I);
488 if (isSchedBoundary(&MI, &*MBB, MF, TII))
489 break;
Shiva Chen24abe712018-05-09 02:42:00 +0000490 if (!MI.isDebugInstr())
Jonas Paulsson59bdb882017-08-17 08:33:44 +0000491 // MBB::size() uses instr_iterator to count. Here we need a bundle to
492 // count as a single instruction.
493 ++NumRegionInstrs;
494 }
495
496 Regions.push_back(SchedRegion(I, RegionEnd, NumRegionInstrs));
497 }
498
499 if (RegionsTopDown)
500 std::reverse(Regions.begin(), Regions.end());
501}
502
Andrew Tricka38b0de2013-12-28 21:56:47 +0000503/// Main driver for both MachineScheduler and PostMachineScheduler.
Matthias Braune9564b22015-11-03 01:53:29 +0000504void MachineSchedulerBase::scheduleRegions(ScheduleDAGInstrs &Scheduler,
505 bool FixKillFlags) {
Andrew Trick96f678f2012-01-13 06:30:30 +0000506 // Visit all machine basic blocks.
Andrew Trick006e1ab2012-04-24 17:56:43 +0000507 //
508 // TODO: Visit blocks in global postorder or postorder within the bottom-up
509 // loop tree. Then we can optionally compute global RegPressure.
Andrew Trick96f678f2012-01-13 06:30:30 +0000510 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
511 MBB != MBBEnd; ++MBB) {
512
Duncan P. N. Exon Smith9731c602015-10-09 19:40:45 +0000513 Scheduler.startBlock(&*MBB);
Andrew Trick1fabd9f2012-03-09 08:02:51 +0000514
Andrew Trickd3f8d6e2013-12-28 21:57:02 +0000515#ifndef NDEBUG
516 if (SchedOnlyFunc.getNumOccurrences() && SchedOnlyFunc != MF->getName())
517 continue;
518 if (SchedOnlyBlock.getNumOccurrences()
519 && (int)SchedOnlyBlock != MBB->getNumber())
520 continue;
521#endif
522
Jonas Paulsson59bdb882017-08-17 08:33:44 +0000523 // Break the block into scheduling regions [I, RegionEnd). RegionEnd
524 // points to the scheduling boundary at the bottom of the region. The DAG
525 // does not include RegionEnd, but the region does (i.e. the next
526 // RegionEnd is above the previous RegionBegin). If the current block has
527 // no terminator then RegionEnd == MBB->end() for the bottom region.
528 //
529 // All the regions of MBB are first found and stored in MBBRegions, which
530 // will be processed (MBB) top-down if initialized with true.
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000531 //
532 // The Scheduler may insert instructions during either schedule() or
533 // exitRegion(), even for empty regions. So the local iterators 'I' and
Jonas Paulsson59bdb882017-08-17 08:33:44 +0000534 // 'RegionEnd' are invalid across these calls. Instructions must not be
535 // added to other regions than the current one without updating MBBRegions.
Andrew Trick006e1ab2012-04-24 17:56:43 +0000536
Jonas Paulsson59bdb882017-08-17 08:33:44 +0000537 MBBRegionsVector MBBRegions;
538 getSchedRegions(&*MBB, MBBRegions, Scheduler.doMBBSchedRegionsTopDown());
539 for (MBBRegionsVector::iterator R = MBBRegions.begin();
540 R != MBBRegions.end(); ++R) {
541 MachineBasicBlock::iterator I = R->RegionBegin;
542 MachineBasicBlock::iterator RegionEnd = R->RegionEnd;
543 unsigned NumRegionInstrs = R->NumRegionInstrs;
Andrew Trick1fabd9f2012-03-09 08:02:51 +0000544
Andrew Trick47c14452012-03-07 05:21:52 +0000545 // Notify the scheduler of the region, even if we may skip scheduling
546 // it. Perhaps it still needs to be bundled.
Duncan P. N. Exon Smith9731c602015-10-09 19:40:45 +0000547 Scheduler.enterRegion(&*MBB, I, RegionEnd, NumRegionInstrs);
Andrew Trick47c14452012-03-07 05:21:52 +0000548
549 // Skip empty scheduling regions (0 or 1 schedulable instructions).
Benjamin Kramerd628f192014-03-02 12:27:27 +0000550 if (I == RegionEnd || I == std::prev(RegionEnd)) {
Andrew Trick47c14452012-03-07 05:21:52 +0000551 // Close the current region. Bundle the terminator if needed.
Andrew Trickfe4d6df2012-03-09 22:34:56 +0000552 // This invalidates 'RegionEnd' and 'I'.
Andrew Tricka38b0de2013-12-28 21:56:47 +0000553 Scheduler.exitRegion();
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000554 continue;
Andrew Trick3c58ba82012-01-14 02:17:18 +0000555 }
Nicola Zaghen0818e782018-05-14 12:53:11 +0000556 LLVM_DEBUG(dbgs() << "********** MI Scheduling **********\n");
557 LLVM_DEBUG(dbgs() << MF->getName() << ":" << printMBBReference(*MBB)
558 << " " << MBB->getName() << "\n From: " << *I
559 << " To: ";
560 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
561 else dbgs() << "End";
562 dbgs() << " RegionInstrs: " << NumRegionInstrs << '\n');
Gerolf Hoflehner9fbb0122014-08-07 21:49:44 +0000563 if (DumpCriticalPathLength) {
564 errs() << MF->getName();
Francis Visoiu Mistrihca0df552017-12-04 17:18:51 +0000565 errs() << ":%bb. " << MBB->getNumber();
Gerolf Hoflehner9fbb0122014-08-07 21:49:44 +0000566 errs() << " " << MBB->getName() << " \n";
567 }
Andrew Trickc6cf11b2012-01-17 06:55:07 +0000568
Andrew Trickd24da972012-03-09 03:46:42 +0000569 // Schedule a region: possibly reorder instructions.
Jonas Paulsson59bdb882017-08-17 08:33:44 +0000570 // This invalidates the original region iterators.
Andrew Tricka38b0de2013-12-28 21:56:47 +0000571 Scheduler.schedule();
Andrew Trickd24da972012-03-09 03:46:42 +0000572
573 // Close the current region.
Andrew Tricka38b0de2013-12-28 21:56:47 +0000574 Scheduler.exitRegion();
Andrew Tricke9ef4ed2012-01-14 02:17:09 +0000575 }
Andrew Tricka38b0de2013-12-28 21:56:47 +0000576 Scheduler.finishBlock();
Matthias Braune9564b22015-11-03 01:53:29 +0000577 // FIXME: Ideally, no further passes should rely on kill flags. However,
578 // thumb2 size reduction is currently an exception, so the PostMIScheduler
579 // needs to do this.
580 if (FixKillFlags)
Matthias Braun0248ff92017-05-27 02:50:50 +0000581 Scheduler.fixupKills(*MBB);
Andrew Trick96f678f2012-01-13 06:30:30 +0000582 }
Andrew Tricka38b0de2013-12-28 21:56:47 +0000583 Scheduler.finalizeSchedule();
Andrew Trick96f678f2012-01-13 06:30:30 +0000584}
585
Andrew Tricka38b0de2013-12-28 21:56:47 +0000586void MachineSchedulerBase::print(raw_ostream &O, const Module* m) const {
Andrew Trick96f678f2012-01-13 06:30:30 +0000587 // unimplemented
588}
589
Aaron Ballman1d03d382017-10-15 14:32:27 +0000590#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Sam Cleggb2092062017-06-21 22:19:17 +0000591LLVM_DUMP_METHOD void ReadyQueue::dump() const {
James Y Knightdc18fbb2015-09-18 18:52:20 +0000592 dbgs() << "Queue " << Name << ": ";
Javed Absar829442a2017-06-21 09:10:10 +0000593 for (const SUnit *SU : Queue)
594 dbgs() << SU->NodeNum << " ";
Andrew Trick78e5efe2012-09-11 00:39:15 +0000595 dbgs() << "\n";
596}
Matthias Braun88d20752017-01-28 02:02:38 +0000597#endif
Andrew Trick17d35e52012-03-14 04:00:41 +0000598
599//===----------------------------------------------------------------------===//
Andrew Tricka38b0de2013-12-28 21:56:47 +0000600// ScheduleDAGMI - Basic machine instruction scheduling. This is
601// independent of PreRA/PostRA scheduling and involves no extra book-keeping for
602// virtual registers.
603// ===----------------------------------------------------------------------===/
Andrew Trick17d35e52012-03-14 04:00:41 +0000604
David Blaikie52d629e2014-04-21 20:32:32 +0000605// Provide a vtable anchor.
Eugene Zelenko096e40d2017-02-22 22:32:51 +0000606ScheduleDAGMI::~ScheduleDAGMI() = default;
Andrew Trick178f7d02013-01-25 04:01:04 +0000607
Andrew Tricke38afe12013-04-24 15:54:43 +0000608bool ScheduleDAGMI::canAddEdge(SUnit *SuccSU, SUnit *PredSU) {
609 return SuccSU == &ExitSU || !Topo.IsReachable(PredSU, SuccSU);
610}
611
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000612bool ScheduleDAGMI::addEdge(SUnit *SuccSU, const SDep &PredDep) {
Andrew Trick6996fd02012-11-12 19:52:20 +0000613 if (SuccSU != &ExitSU) {
614 // Do not use WillCreateCycle, it assumes SD scheduling.
615 // If Pred is reachable from Succ, then the edge creates a cycle.
616 if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
617 return false;
618 Topo.AddPred(SuccSU, PredDep.getSUnit());
619 }
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000620 SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
621 // Return true regardless of whether a new edge needed to be inserted.
622 return true;
623}
624
Andrew Trickc174eaf2012-03-08 01:41:12 +0000625/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
626/// NumPredsLeft reaches zero, release the successor node.
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000627///
628/// FIXME: Adjust SuccSU height based on MinLatency.
Andrew Trick17d35e52012-03-14 04:00:41 +0000629void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
Andrew Trickc174eaf2012-03-08 01:41:12 +0000630 SUnit *SuccSU = SuccEdge->getSUnit();
631
Andrew Trickae692f22012-11-12 19:28:57 +0000632 if (SuccEdge->isWeak()) {
633 --SuccSU->WeakPredsLeft;
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000634 if (SuccEdge->isCluster())
635 NextClusterSucc = SuccSU;
Andrew Trickae692f22012-11-12 19:28:57 +0000636 return;
637 }
Andrew Trickc174eaf2012-03-08 01:41:12 +0000638#ifndef NDEBUG
639 if (SuccSU->NumPredsLeft == 0) {
640 dbgs() << "*** Scheduling failed! ***\n";
Matthias Braunb064c242018-09-19 00:23:35 +0000641 dumpNode(*SuccSU);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000642 dbgs() << " has been released too many times!\n";
Craig Topper4ba84432014-04-14 00:51:57 +0000643 llvm_unreachable(nullptr);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000644 }
645#endif
Andrew Trick808823c2014-06-07 01:48:43 +0000646 // SU->TopReadyCycle was set to CurrCycle when it was scheduled. However,
647 // CurrCycle may have advanced since then.
648 if (SuccSU->TopReadyCycle < SU->TopReadyCycle + SuccEdge->getLatency())
649 SuccSU->TopReadyCycle = SU->TopReadyCycle + SuccEdge->getLatency();
650
Andrew Trickc174eaf2012-03-08 01:41:12 +0000651 --SuccSU->NumPredsLeft;
652 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
Andrew Trick17d35e52012-03-14 04:00:41 +0000653 SchedImpl->releaseTopNode(SuccSU);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000654}
655
656/// releaseSuccessors - Call releaseSucc on each of SU's successors.
Andrew Trick17d35e52012-03-14 04:00:41 +0000657void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
Javed Absar829442a2017-06-21 09:10:10 +0000658 for (SDep &Succ : SU->Succs)
659 releaseSucc(SU, &Succ);
Andrew Trickc174eaf2012-03-08 01:41:12 +0000660}
661
Andrew Trick17d35e52012-03-14 04:00:41 +0000662/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
663/// NumSuccsLeft reaches zero, release the predecessor node.
Andrew Trick0a39d4e2012-05-24 22:11:09 +0000664///
665/// FIXME: Adjust PredSU height based on MinLatency.
Andrew Trick17d35e52012-03-14 04:00:41 +0000666void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
667 SUnit *PredSU = PredEdge->getSUnit();
668
Andrew Trickae692f22012-11-12 19:28:57 +0000669 if (PredEdge->isWeak()) {
670 --PredSU->WeakSuccsLeft;
Andrew Trick9b5caaa2012-11-12 19:40:10 +0000671 if (PredEdge->isCluster())
672 NextClusterPred = PredSU;
Andrew Trickae692f22012-11-12 19:28:57 +0000673 return;
674 }
Andrew Trick17d35e52012-03-14 04:00:41 +0000675#ifndef NDEBUG
676 if (PredSU->NumSuccsLeft == 0) {
677 dbgs() << "*** Scheduling failed! ***\n";
Matthias Braunb064c242018-09-19 00:23:35 +0000678 dumpNode(*PredSU);
Andrew Trick17d35e52012-03-14 04:00:41 +0000679 dbgs() << " has been released too many times!\n";
Craig Topper4ba84432014-04-14 00:51:57 +0000680 llvm_unreachable(nullptr);
Andrew Trick17d35e52012-03-14 04:00:41 +0000681 }
682#endif
Andrew Trick808823c2014-06-07 01:48:43 +0000683 // SU->BotReadyCycle was set to CurrCycle when it was scheduled. However,
684 // CurrCycle may have advanced since then.
685 if (PredSU->BotReadyCycle < SU->BotReadyCycle + PredEdge->getLatency())
686 PredSU->BotReadyCycle = SU->BotReadyCycle + PredEdge->getLatency();
687
Andrew Trick17d35e52012-03-14 04:00:41 +0000688 --PredSU->NumSuccsLeft;
689 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
690 SchedImpl->releaseBottomNode(PredSU);
691}
692
693/// releasePredecessors - Call releasePred on each of SU's predecessors.
694void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
Javed Absar829442a2017-06-21 09:10:10 +0000695 for (SDep &Pred : SU->Preds)
696 releasePred(SU, &Pred);
Andrew Trick17d35e52012-03-14 04:00:41 +0000697}
698
Jonas Paulsson59bdb882017-08-17 08:33:44 +0000699void ScheduleDAGMI::startBlock(MachineBasicBlock *bb) {
700 ScheduleDAGInstrs::startBlock(bb);
701 SchedImpl->enterMBB(bb);
702}
703
704void ScheduleDAGMI::finishBlock() {
705 SchedImpl->leaveMBB();
706 ScheduleDAGInstrs::finishBlock();
707}
708
Andrew Tricka38b0de2013-12-28 21:56:47 +0000709/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
710/// crossing a scheduling boundary. [begin, end) includes all instructions in
711/// the region, including the boundary itself and single-instruction regions
712/// that don't get scheduled.
713void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
714 MachineBasicBlock::iterator begin,
715 MachineBasicBlock::iterator end,
716 unsigned regioninstrs)
717{
718 ScheduleDAGInstrs::enterRegion(bb, begin, end, regioninstrs);
719
720 SchedImpl->initPolicy(begin, end, regioninstrs);
721}
722
Andrew Trick4392f0f2013-04-13 06:07:40 +0000723/// This is normally called from the main scheduler loop but may also be invoked
724/// by the scheduling strategy to perform additional code motion.
Andrew Tricka38b0de2013-12-28 21:56:47 +0000725void ScheduleDAGMI::moveInstruction(
726 MachineInstr *MI, MachineBasicBlock::iterator InsertPos) {
Andrew Trick811d92682012-05-17 18:35:03 +0000727 // Advance RegionBegin if the first instruction moves down.
Andrew Trick1ce062f2012-03-21 04:12:10 +0000728 if (&*RegionBegin == MI)
Andrew Trick811d92682012-05-17 18:35:03 +0000729 ++RegionBegin;
730
731 // Update the instruction stream.
Andrew Trick17d35e52012-03-14 04:00:41 +0000732 BB->splice(InsertPos, BB, MI);
Andrew Trick811d92682012-05-17 18:35:03 +0000733
734 // Update LiveIntervals
Andrew Tricka38b0de2013-12-28 21:56:47 +0000735 if (LIS)
Duncan P. N. Exon Smith5144d352016-02-27 20:14:29 +0000736 LIS->handleMove(*MI, /*UpdateFlags=*/true);
Andrew Trick811d92682012-05-17 18:35:03 +0000737
738 // Recede RegionBegin if an instruction moves above the first.
Andrew Trick17d35e52012-03-14 04:00:41 +0000739 if (RegionBegin == InsertPos)
740 RegionBegin = MI;
741}
742
Andrew Trick0b0d8992012-03-21 04:12:07 +0000743bool ScheduleDAGMI::checkSchedLimit() {
744#ifndef NDEBUG
745 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
746 CurrentTop = CurrentBottom;
747 return false;
748 }
749 ++NumInstrsScheduled;
750#endif
751 return true;
752}
753
Andrew Tricka38b0de2013-12-28 21:56:47 +0000754/// Per-region scheduling driver, called back from
755/// MachineScheduler::runOnMachineFunction. This is a simplified driver that
756/// does not consider liveness or register pressure. It is useful for PostRA
757/// scheduling and potentially other custom schedulers.
758void ScheduleDAGMI::schedule() {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000759 LLVM_DEBUG(dbgs() << "ScheduleDAGMI::schedule starting\n");
760 LLVM_DEBUG(SchedImpl->dumpPolicy());
James Y Knightdc18fbb2015-09-18 18:52:20 +0000761
Andrew Tricka38b0de2013-12-28 21:56:47 +0000762 // Build the DAG.
763 buildSchedGraph(AA);
764
765 Topo.InitDAGTopologicalSorting();
766
767 postprocessDAG();
768
769 SmallVector<SUnit*, 8> TopRoots, BotRoots;
770 findRootsAndBiasEdges(TopRoots, BotRoots);
771
Matthias Braunb064c242018-09-19 00:23:35 +0000772 LLVM_DEBUG(dump());
Matthias Braun9214de52018-09-19 20:50:49 +0000773 if (PrintDAGs) dump();
Andrew Tricka38b0de2013-12-28 21:56:47 +0000774 if (ViewMISchedDAGs) viewGraph();
775
Jonas Paulsson31f34392018-03-05 16:31:49 +0000776 // Initialize the strategy before modifying the DAG.
777 // This may initialize a DFSResult to be used for queue priority.
778 SchedImpl->initialize(this);
779
Andrew Tricka38b0de2013-12-28 21:56:47 +0000780 // Initialize ready queues now that the DAG and priority data are finalized.
781 initQueues(TopRoots, BotRoots);
782
783 bool IsTopNode = false;
James Y Knightdc18fbb2015-09-18 18:52:20 +0000784 while (true) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000785 LLVM_DEBUG(dbgs() << "** ScheduleDAGMI::schedule picking next node\n");
James Y Knightdc18fbb2015-09-18 18:52:20 +0000786 SUnit *SU = SchedImpl->pickNode(IsTopNode);
787 if (!SU) break;
788
Andrew Tricka38b0de2013-12-28 21:56:47 +0000789 assert(!SU->isScheduled && "Node already scheduled");
790 if (!checkSchedLimit())
791 break;
792
793 MachineInstr *MI = SU->getInstr();
794 if (IsTopNode) {
795 assert(SU->isTopReady() && "node still has unscheduled dependencies");
796 if (&*CurrentTop == MI)
797 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
798 else
799 moveInstruction(MI, CurrentTop);
Matthias Braund3962152016-04-21 01:54:13 +0000800 } else {
Andrew Tricka38b0de2013-12-28 21:56:47 +0000801 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
802 MachineBasicBlock::iterator priorII =
803 priorNonDebug(CurrentBottom, CurrentTop);
804 if (&*priorII == MI)
805 CurrentBottom = priorII;
806 else {
807 if (&*CurrentTop == MI)
808 CurrentTop = nextIfDebug(++CurrentTop, priorII);
809 moveInstruction(MI, CurrentBottom);
810 CurrentBottom = MI;
811 }
812 }
Andrew Trick808823c2014-06-07 01:48:43 +0000813 // Notify the scheduling strategy before updating the DAG.
Andrew Trick796f1142014-06-12 22:36:28 +0000814 // This sets the scheduled node's ReadyCycle to CurrCycle. When updateQueues
Andrew Trick808823c2014-06-07 01:48:43 +0000815 // runs, it can then use the accurate ReadyCycle time to determine whether
816 // newly released nodes can move to the readyQ.
Andrew Tricka38b0de2013-12-28 21:56:47 +0000817 SchedImpl->schedNode(SU, IsTopNode);
Andrew Trick808823c2014-06-07 01:48:43 +0000818
819 updateQueues(SU, IsTopNode);
Andrew Tricka38b0de2013-12-28 21:56:47 +0000820 }
821 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
822
823 placeDebugValues();
824
Nicola Zaghen0818e782018-05-14 12:53:11 +0000825 LLVM_DEBUG({
Francis Visoiu Mistrihca0df552017-12-04 17:18:51 +0000826 dbgs() << "*** Final schedule for "
827 << printMBBReference(*begin()->getParent()) << " ***\n";
828 dumpSchedule();
829 dbgs() << '\n';
830 });
Andrew Tricka38b0de2013-12-28 21:56:47 +0000831}
832
833/// Apply each ScheduleDAGMutation step in order.
834void ScheduleDAGMI::postprocessDAG() {
Javed Absar829442a2017-06-21 09:10:10 +0000835 for (auto &m : Mutations)
836 m->apply(this);
Andrew Tricka38b0de2013-12-28 21:56:47 +0000837}
838
839void ScheduleDAGMI::
840findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
841 SmallVectorImpl<SUnit*> &BotRoots) {
Javed Absar829442a2017-06-21 09:10:10 +0000842 for (SUnit &SU : SUnits) {
843 assert(!SU.isBoundaryNode() && "Boundary node should not be in SUnits");
Andrew Tricka38b0de2013-12-28 21:56:47 +0000844
845 // Order predecessors so DFSResult follows the critical path.
Javed Absar829442a2017-06-21 09:10:10 +0000846 SU.biasCriticalPath();
Andrew Tricka38b0de2013-12-28 21:56:47 +0000847
848 // A SUnit is ready to top schedule if it has no predecessors.
Javed Absar829442a2017-06-21 09:10:10 +0000849 if (!SU.NumPredsLeft)
850 TopRoots.push_back(&SU);
Andrew Tricka38b0de2013-12-28 21:56:47 +0000851 // A SUnit is ready to bottom schedule if it has no successors.
Javed Absar829442a2017-06-21 09:10:10 +0000852 if (!SU.NumSuccsLeft)
853 BotRoots.push_back(&SU);
Andrew Tricka38b0de2013-12-28 21:56:47 +0000854 }
855 ExitSU.biasCriticalPath();
856}
857
858/// Identify DAG roots and setup scheduler queues.
859void ScheduleDAGMI::initQueues(ArrayRef<SUnit*> TopRoots,
860 ArrayRef<SUnit*> BotRoots) {
Craig Topper4ba84432014-04-14 00:51:57 +0000861 NextClusterSucc = nullptr;
862 NextClusterPred = nullptr;
Andrew Tricka38b0de2013-12-28 21:56:47 +0000863
864 // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
865 //
866 // Nodes with unreleased weak edges can still be roots.
867 // Release top roots in forward order.
Javed Absar829442a2017-06-21 09:10:10 +0000868 for (SUnit *SU : TopRoots)
869 SchedImpl->releaseTopNode(SU);
870
Andrew Tricka38b0de2013-12-28 21:56:47 +0000871 // Release bottom roots in reverse order so the higher priority nodes appear
872 // first. This is more natural and slightly more efficient.
873 for (SmallVectorImpl<SUnit*>::const_reverse_iterator
874 I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I) {
875 SchedImpl->releaseBottomNode(*I);
876 }
877
878 releaseSuccessors(&EntrySU);
879 releasePredecessors(&ExitSU);
880
881 SchedImpl->registerRoots();
882
883 // Advance past initial DebugValues.
884 CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
885 CurrentBottom = RegionEnd;
886}
887
888/// Update scheduler queues after scheduling an instruction.
889void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
890 // Release dependent instructions for scheduling.
891 if (IsTopNode)
892 releaseSuccessors(SU);
893 else
894 releasePredecessors(SU);
895
896 SU->isScheduled = true;
897}
898
899/// Reinsert any remaining debug_values, just like the PostRA scheduler.
900void ScheduleDAGMI::placeDebugValues() {
901 // If first instruction was a DBG_VALUE then put it back.
902 if (FirstDbgValue) {
903 BB->splice(RegionBegin, BB, FirstDbgValue);
904 RegionBegin = FirstDbgValue;
905 }
906
Eugene Zelenko096e40d2017-02-22 22:32:51 +0000907 for (std::vector<std::pair<MachineInstr *, MachineInstr *>>::iterator
Andrew Tricka38b0de2013-12-28 21:56:47 +0000908 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
Benjamin Kramerd628f192014-03-02 12:27:27 +0000909 std::pair<MachineInstr *, MachineInstr *> P = *std::prev(DI);
Andrew Tricka38b0de2013-12-28 21:56:47 +0000910 MachineInstr *DbgValue = P.first;
911 MachineBasicBlock::iterator OrigPrevMI = P.second;
912 if (&*RegionBegin == DbgValue)
913 ++RegionBegin;
914 BB->splice(++OrigPrevMI, BB, DbgValue);
Benjamin Kramerd628f192014-03-02 12:27:27 +0000915 if (OrigPrevMI == std::prev(RegionEnd))
Andrew Tricka38b0de2013-12-28 21:56:47 +0000916 RegionEnd = DbgValue;
917 }
918 DbgValues.clear();
Craig Topper4ba84432014-04-14 00:51:57 +0000919 FirstDbgValue = nullptr;
Andrew Tricka38b0de2013-12-28 21:56:47 +0000920}
921
Aaron Ballman1d03d382017-10-15 14:32:27 +0000922#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Matthias Braun88d20752017-01-28 02:02:38 +0000923LLVM_DUMP_METHOD void ScheduleDAGMI::dumpSchedule() const {
Andrew Tricka38b0de2013-12-28 21:56:47 +0000924 for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
925 if (SUnit *SU = getSUnit(&(*MI)))
Matthias Braunb064c242018-09-19 00:23:35 +0000926 dumpNode(*SU);
Andrew Tricka38b0de2013-12-28 21:56:47 +0000927 else
928 dbgs() << "Missing SUnit\n";
929 }
930}
931#endif
932
933//===----------------------------------------------------------------------===//
934// ScheduleDAGMILive - Base class for MachineInstr scheduling with LiveIntervals
935// preservation.
936//===----------------------------------------------------------------------===//
937
938ScheduleDAGMILive::~ScheduleDAGMILive() {
939 delete DFSResult;
940}
941
Matthias Braun97c4b7a2016-11-11 22:37:31 +0000942void ScheduleDAGMILive::collectVRegUses(SUnit &SU) {
943 const MachineInstr &MI = *SU.getInstr();
944 for (const MachineOperand &MO : MI.operands()) {
945 if (!MO.isReg())
946 continue;
947 if (!MO.readsReg())
948 continue;
949 if (TrackLaneMasks && !MO.isUse())
950 continue;
951
952 unsigned Reg = MO.getReg();
953 if (!TargetRegisterInfo::isVirtualRegister(Reg))
954 continue;
955
956 // Ignore re-defs.
957 if (TrackLaneMasks) {
958 bool FoundDef = false;
959 for (const MachineOperand &MO2 : MI.operands()) {
960 if (MO2.isReg() && MO2.isDef() && MO2.getReg() == Reg && !MO2.isDead()) {
961 FoundDef = true;
962 break;
963 }
964 }
965 if (FoundDef)
966 continue;
967 }
968
969 // Record this local VReg use.
970 VReg2SUnitMultiMap::iterator UI = VRegUses.find(Reg);
971 for (; UI != VRegUses.end(); ++UI) {
972 if (UI->SU == &SU)
973 break;
974 }
975 if (UI == VRegUses.end())
Krzysztof Parzyszekd6ca3f02016-12-15 14:36:06 +0000976 VRegUses.insert(VReg2SUnit(Reg, LaneBitmask::getNone(), &SU));
Matthias Braun97c4b7a2016-11-11 22:37:31 +0000977 }
978}
979
Andrew Trick006e1ab2012-04-24 17:56:43 +0000980/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
981/// crossing a scheduling boundary. [begin, end) includes all instructions in
982/// the region, including the boundary itself and single-instruction regions
983/// that don't get scheduled.
Andrew Tricka38b0de2013-12-28 21:56:47 +0000984void ScheduleDAGMILive::enterRegion(MachineBasicBlock *bb,
Andrew Trick006e1ab2012-04-24 17:56:43 +0000985 MachineBasicBlock::iterator begin,
986 MachineBasicBlock::iterator end,
Andrew Trickd2763f62013-08-23 17:48:33 +0000987 unsigned regioninstrs)
Andrew Trick006e1ab2012-04-24 17:56:43 +0000988{
Andrew Tricka38b0de2013-12-28 21:56:47 +0000989 // ScheduleDAGMI initializes SchedImpl's per-region policy.
990 ScheduleDAGMI::enterRegion(bb, begin, end, regioninstrs);
Andrew Trick7f8ab782012-05-10 21:06:10 +0000991
992 // For convenience remember the end of the liveness region.
Benjamin Kramerd628f192014-03-02 12:27:27 +0000993 LiveRegionEnd = (RegionEnd == bb->end()) ? RegionEnd : std::next(RegionEnd);
Andrew Trick38e61122013-09-06 17:32:34 +0000994
Andrew Trickfb386db2013-09-06 17:32:47 +0000995 SUPressureDiffs.clear();
996
Andrew Trick38e61122013-09-06 17:32:34 +0000997 ShouldTrackPressure = SchedImpl->shouldTrackPressure();
Matthias Braund267d372016-01-20 00:23:32 +0000998 ShouldTrackLaneMasks = SchedImpl->shouldTrackLaneMasks();
999
Matthias Braun1cd242f2016-05-31 22:38:06 +00001000 assert((!ShouldTrackLaneMasks || ShouldTrackPressure) &&
1001 "ShouldTrackLaneMasks requires ShouldTrackPressure");
Andrew Trick7f8ab782012-05-10 21:06:10 +00001002}
1003
1004// Setup the register pressure trackers for the top scheduled top and bottom
1005// scheduled regions.
Andrew Tricka38b0de2013-12-28 21:56:47 +00001006void ScheduleDAGMILive::initRegPressure() {
Matthias Braun97c4b7a2016-11-11 22:37:31 +00001007 VRegUses.clear();
1008 VRegUses.setUniverse(MRI.getNumVirtRegs());
1009 for (SUnit &SU : SUnits)
1010 collectVRegUses(SU);
1011
Matthias Braund267d372016-01-20 00:23:32 +00001012 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin,
1013 ShouldTrackLaneMasks, false);
1014 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
1015 ShouldTrackLaneMasks, false);
Andrew Trick7f8ab782012-05-10 21:06:10 +00001016
1017 // Close the RPTracker to finalize live ins.
1018 RPTracker.closeRegion();
1019
Nicola Zaghen0818e782018-05-14 12:53:11 +00001020 LLVM_DEBUG(RPTracker.dump());
Andrew Trickbb0a2422012-05-24 22:11:14 +00001021
Andrew Trick7f8ab782012-05-10 21:06:10 +00001022 // Initialize the live ins and live outs.
Matthias Braund68f4c02015-09-17 21:12:24 +00001023 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
1024 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
Andrew Trick7f8ab782012-05-10 21:06:10 +00001025
1026 // Close one end of the tracker so we can call
1027 // getMaxUpward/DownwardPressureDelta before advancing across any
1028 // instructions. This converts currently live regs into live ins/outs.
1029 TopRPTracker.closeTop();
1030 BotRPTracker.closeBottom();
1031
Andrew Trickd71efff2013-07-30 19:59:12 +00001032 BotRPTracker.initLiveThru(RPTracker);
1033 if (!BotRPTracker.getLiveThru().empty()) {
1034 TopRPTracker.initLiveThru(BotRPTracker.getLiveThru());
Nicola Zaghen0818e782018-05-14 12:53:11 +00001035 LLVM_DEBUG(dbgs() << "Live Thru: ";
1036 dumpRegSetPressure(BotRPTracker.getLiveThru(), TRI));
Andrew Trickd71efff2013-07-30 19:59:12 +00001037 };
1038
Andrew Trick663bd992013-08-30 04:36:57 +00001039 // For each live out vreg reduce the pressure change associated with other
1040 // uses of the same vreg below the live-out reaching def.
Matthias Braund68f4c02015-09-17 21:12:24 +00001041 updatePressureDiffs(RPTracker.getPressure().LiveOutRegs);
Andrew Trick663bd992013-08-30 04:36:57 +00001042
Andrew Trick7f8ab782012-05-10 21:06:10 +00001043 // Account for liveness generated by the region boundary.
Andrew Trick663bd992013-08-30 04:36:57 +00001044 if (LiveRegionEnd != RegionEnd) {
Matthias Braun051b30e2016-01-20 00:23:26 +00001045 SmallVector<RegisterMaskPair, 8> LiveUses;
Andrew Trick663bd992013-08-30 04:36:57 +00001046 BotRPTracker.recede(&LiveUses);
1047 updatePressureDiffs(LiveUses);
1048 }
Andrew Trick7f8ab782012-05-10 21:06:10 +00001049
Nicola Zaghen0818e782018-05-14 12:53:11 +00001050 LLVM_DEBUG(dbgs() << "Top Pressure:\n";
1051 dumpRegSetPressure(TopRPTracker.getRegSetPressureAtPos(), TRI);
1052 dbgs() << "Bottom Pressure:\n";
1053 dumpRegSetPressure(BotRPTracker.getRegSetPressureAtPos(), TRI););
Matthias Braunf724d182015-11-13 22:30:31 +00001054
Yaxun Liu06d39e22017-12-15 03:56:57 +00001055 assert((BotRPTracker.getPos() == RegionEnd ||
Shiva Chen24abe712018-05-09 02:42:00 +00001056 (RegionEnd->isDebugInstr() &&
Yaxun Liu06d39e22017-12-15 03:56:57 +00001057 BotRPTracker.getPos() == priorNonDebug(RegionEnd, RegionBegin))) &&
1058 "Can't find the region bottom");
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001059
1060 // Cache the list of excess pressure sets in this region. This will also track
1061 // the max pressure in the scheduled code for these sets.
1062 RegionCriticalPSets.clear();
Jakub Staszakb74564a2013-01-25 21:44:27 +00001063 const std::vector<unsigned> &RegionPressure =
1064 RPTracker.getPressure().MaxSetPressure;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001065 for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
Andrew Trick1f8b48a2013-06-21 18:32:58 +00001066 unsigned Limit = RegClassInfo->getRegPressureSetLimit(i);
Andrew Trick3bf23302013-06-21 18:33:01 +00001067 if (RegionPressure[i] > Limit) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00001068 LLVM_DEBUG(dbgs() << TRI->getRegPressureSetName(i) << " Limit " << Limit
1069 << " Actual " << RegionPressure[i] << "\n");
Andrew Trick4c60b8a2013-08-30 03:49:48 +00001070 RegionCriticalPSets.push_back(PressureChange(i));
Andrew Trick3bf23302013-06-21 18:33:01 +00001071 }
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001072 }
Nicola Zaghen0818e782018-05-14 12:53:11 +00001073 LLVM_DEBUG(dbgs() << "Excess PSets: ";
1074 for (const PressureChange &RCPS
1075 : RegionCriticalPSets) dbgs()
1076 << TRI->getRegPressureSetName(RCPS.getPSet()) << " ";
1077 dbgs() << "\n");
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001078}
1079
Andrew Tricka38b0de2013-12-28 21:56:47 +00001080void ScheduleDAGMILive::
Andrew Trickfb386db2013-09-06 17:32:47 +00001081updateScheduledPressure(const SUnit *SU,
1082 const std::vector<unsigned> &NewMaxPressure) {
1083 const PressureDiff &PDiff = getPressureDiff(SU);
1084 unsigned CritIdx = 0, CritEnd = RegionCriticalPSets.size();
Javed Absar829442a2017-06-21 09:10:10 +00001085 for (const PressureChange &PC : PDiff) {
1086 if (!PC.isValid())
Andrew Trickfb386db2013-09-06 17:32:47 +00001087 break;
Javed Absar829442a2017-06-21 09:10:10 +00001088 unsigned ID = PC.getPSet();
Andrew Trickfb386db2013-09-06 17:32:47 +00001089 while (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() < ID)
1090 ++CritIdx;
1091 if (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() == ID) {
1092 if ((int)NewMaxPressure[ID] > RegionCriticalPSets[CritIdx].getUnitInc()
Simon Pilgrimee4b4ec2017-02-23 12:00:34 +00001093 && NewMaxPressure[ID] <= (unsigned)std::numeric_limits<int16_t>::max())
Andrew Trickfb386db2013-09-06 17:32:47 +00001094 RegionCriticalPSets[CritIdx].setUnitInc(NewMaxPressure[ID]);
1095 }
1096 unsigned Limit = RegClassInfo->getRegPressureSetLimit(ID);
1097 if (NewMaxPressure[ID] >= Limit - 2) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00001098 LLVM_DEBUG(dbgs() << " " << TRI->getRegPressureSetName(ID) << ": "
1099 << NewMaxPressure[ID]
1100 << ((NewMaxPressure[ID] > Limit) ? " > " : " <= ")
1101 << Limit << "(+ " << BotRPTracker.getLiveThru()[ID]
1102 << " livethru)\n");
Andrew Trickfb386db2013-09-06 17:32:47 +00001103 }
Andrew Trick73a0d8e2012-05-17 18:35:10 +00001104 }
Andrew Trick006e1ab2012-04-24 17:56:43 +00001105}
1106
Andrew Trick663bd992013-08-30 04:36:57 +00001107/// Update the PressureDiff array for liveness after scheduling this
1108/// instruction.
Matthias Braun051b30e2016-01-20 00:23:26 +00001109void ScheduleDAGMILive::updatePressureDiffs(
1110 ArrayRef<RegisterMaskPair> LiveUses) {
1111 for (const RegisterMaskPair &P : LiveUses) {
Matthias Braun051b30e2016-01-20 00:23:26 +00001112 unsigned Reg = P.RegUnit;
Matthias Braund267d372016-01-20 00:23:32 +00001113 /// FIXME: Currently assuming single-use physregs.
Andrew Trick663bd992013-08-30 04:36:57 +00001114 if (!TRI->isVirtualRegister(Reg))
1115 continue;
Andrew Trick1251bcc2013-09-06 17:32:39 +00001116
Matthias Braund267d372016-01-20 00:23:32 +00001117 if (ShouldTrackLaneMasks) {
1118 // If the register has just become live then other uses won't change
1119 // this fact anymore => decrement pressure.
1120 // If the register has just become dead then other uses make it come
1121 // back to life => increment pressure.
Krzysztof Parzyszek308c60d2016-12-16 19:11:56 +00001122 bool Decrement = P.LaneMask.any();
Matthias Braund267d372016-01-20 00:23:32 +00001123
1124 for (const VReg2SUnit &V2SU
1125 : make_range(VRegUses.find(Reg), VRegUses.end())) {
1126 SUnit &SU = *V2SU.SU;
1127 if (SU.isScheduled || &SU == &ExitSU)
1128 continue;
1129
1130 PressureDiff &PDiff = getPressureDiff(&SU);
Stanislav Mekhanoshinfef0dbe2017-02-24 21:56:16 +00001131 PDiff.addPressureChange(Reg, Decrement, &MRI);
Nicola Zaghen0818e782018-05-14 12:53:11 +00001132 LLVM_DEBUG(dbgs() << " UpdateRegP: SU(" << SU.NodeNum << ") "
1133 << printReg(Reg, TRI) << ':'
1134 << PrintLaneMask(P.LaneMask) << ' ' << *SU.getInstr();
1135 dbgs() << " to "; PDiff.dump(*TRI););
Matthias Braund267d372016-01-20 00:23:32 +00001136 }
1137 } else {
Krzysztof Parzyszek308c60d2016-12-16 19:11:56 +00001138 assert(P.LaneMask.any());
Nicola Zaghen0818e782018-05-14 12:53:11 +00001139 LLVM_DEBUG(dbgs() << " LiveReg: " << printVRegOrUnit(Reg, TRI) << "\n");
Matthias Braund267d372016-01-20 00:23:32 +00001140 // This may be called before CurrentBottom has been initialized. However,
1141 // BotRPTracker must have a valid position. We want the value live into the
1142 // instruction or live out of the block, so ask for the previous
1143 // instruction's live-out.
1144 const LiveInterval &LI = LIS->getInterval(Reg);
1145 VNInfo *VNI;
1146 MachineBasicBlock::const_iterator I =
1147 nextIfDebug(BotRPTracker.getPos(), BB->end());
1148 if (I == BB->end())
1149 VNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
1150 else {
Duncan P. N. Exon Smith42e18352016-02-27 06:40:41 +00001151 LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(*I));
Matthias Braund267d372016-01-20 00:23:32 +00001152 VNI = LRQ.valueIn();
1153 }
1154 // RegisterPressureTracker guarantees that readsReg is true for LiveUses.
1155 assert(VNI && "No live value at use.");
1156 for (const VReg2SUnit &V2SU
1157 : make_range(VRegUses.find(Reg), VRegUses.end())) {
1158 SUnit *SU = V2SU.SU;
1159 // If this use comes before the reaching def, it cannot be a last use,
1160 // so decrease its pressure change.
1161 if (!SU->isScheduled && SU != &ExitSU) {
Duncan P. N. Exon Smith42e18352016-02-27 06:40:41 +00001162 LiveQueryResult LRQ =
1163 LI.Query(LIS->getInstructionIndex(*SU->getInstr()));
Matthias Braund267d372016-01-20 00:23:32 +00001164 if (LRQ.valueIn() == VNI) {
1165 PressureDiff &PDiff = getPressureDiff(SU);
Stanislav Mekhanoshinfef0dbe2017-02-24 21:56:16 +00001166 PDiff.addPressureChange(Reg, true, &MRI);
Nicola Zaghen0818e782018-05-14 12:53:11 +00001167 LLVM_DEBUG(dbgs() << " UpdateRegP: SU(" << SU->NodeNum << ") "
1168 << *SU->getInstr();
1169 dbgs() << " to "; PDiff.dump(*TRI););
Matthias Braund267d372016-01-20 00:23:32 +00001170 }
Matthias Braun810bd4f2015-11-06 20:59:02 +00001171 }
Andrew Trick663bd992013-08-30 04:36:57 +00001172 }
1173 }
1174 }
1175}
1176
Matthias Braunb064c242018-09-19 00:23:35 +00001177void ScheduleDAGMILive::dump() const {
1178#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1179 if (EntrySU.getInstr() != nullptr)
1180 dumpNodeAll(EntrySU);
1181 for (const SUnit &SU : SUnits) {
1182 dumpNodeAll(SU);
1183 if (ShouldTrackPressure) {
1184 dbgs() << " Pressure Diff : ";
1185 getPressureDiff(&SU).dump(*TRI);
1186 }
1187 dbgs() << " Single Issue : ";
1188 if (SchedModel.mustBeginGroup(SU.getInstr()) &&
1189 SchedModel.mustEndGroup(SU.getInstr()))
1190 dbgs() << "true;";
1191 else
1192 dbgs() << "false;";
1193 dbgs() << '\n';
1194 }
1195 if (ExitSU.getInstr() != nullptr)
1196 dumpNodeAll(ExitSU);
1197#endif
1198}
1199
Andrew Trick17d35e52012-03-14 04:00:41 +00001200/// schedule - Called back from MachineScheduler::runOnMachineFunction
Andrew Trick006e1ab2012-04-24 17:56:43 +00001201/// after setting up the current scheduling region. [RegionBegin, RegionEnd)
1202/// only includes instructions that have DAG nodes, not scheduling boundaries.
Andrew Trick78e5efe2012-09-11 00:39:15 +00001203///
1204/// This is a skeletal driver, with all the functionality pushed into helpers,
Nick Lewyckycca41d32015-08-18 22:41:58 +00001205/// so that it can be easily extended by experimental schedulers. Generally,
Andrew Trick78e5efe2012-09-11 00:39:15 +00001206/// implementing MachineSchedStrategy should be sufficient to implement a new
1207/// scheduling algorithm. However, if a scheduler further subclasses
Andrew Tricka38b0de2013-12-28 21:56:47 +00001208/// ScheduleDAGMILive then it will want to override this virtual method in order
1209/// to update any specialized state.
1210void ScheduleDAGMILive::schedule() {
Nicola Zaghen0818e782018-05-14 12:53:11 +00001211 LLVM_DEBUG(dbgs() << "ScheduleDAGMILive::schedule starting\n");
1212 LLVM_DEBUG(SchedImpl->dumpPolicy());
Andrew Trick78e5efe2012-09-11 00:39:15 +00001213 buildDAGWithRegPressure();
1214
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001215 Topo.InitDAGTopologicalSorting();
1216
Andrew Trickd039b382012-09-14 17:22:42 +00001217 postprocessDAG();
1218
Andrew Trick4e1fb182013-01-25 06:33:57 +00001219 SmallVector<SUnit*, 8> TopRoots, BotRoots;
1220 findRootsAndBiasEdges(TopRoots, BotRoots);
1221
1222 // Initialize the strategy before modifying the DAG.
1223 // This may initialize a DFSResult to be used for queue priority.
1224 SchedImpl->initialize(this);
1225
Matthias Braunb064c242018-09-19 00:23:35 +00001226 LLVM_DEBUG(dump());
Matthias Braun9214de52018-09-19 20:50:49 +00001227 if (PrintDAGs) dump();
Andrew Trick4e1fb182013-01-25 06:33:57 +00001228 if (ViewMISchedDAGs) viewGraph();
Andrew Trick78e5efe2012-09-11 00:39:15 +00001229
Andrew Trick4e1fb182013-01-25 06:33:57 +00001230 // Initialize ready queues now that the DAG and priority data are finalized.
1231 initQueues(TopRoots, BotRoots);
Andrew Trick78e5efe2012-09-11 00:39:15 +00001232
1233 bool IsTopNode = false;
James Y Knightdc18fbb2015-09-18 18:52:20 +00001234 while (true) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00001235 LLVM_DEBUG(dbgs() << "** ScheduleDAGMILive::schedule picking next node\n");
James Y Knightdc18fbb2015-09-18 18:52:20 +00001236 SUnit *SU = SchedImpl->pickNode(IsTopNode);
1237 if (!SU) break;
1238
Andrew Trick30c6ec22012-10-08 18:53:53 +00001239 assert(!SU->isScheduled && "Node already scheduled");
Andrew Trick78e5efe2012-09-11 00:39:15 +00001240 if (!checkSchedLimit())
1241 break;
1242
1243 scheduleMI(SU, IsTopNode);
1244
Andrew Tricka38b0de2013-12-28 21:56:47 +00001245 if (DFSResult) {
1246 unsigned SubtreeID = DFSResult->getSubtreeID(SU);
1247 if (!ScheduledTrees.test(SubtreeID)) {
1248 ScheduledTrees.set(SubtreeID);
1249 DFSResult->scheduleTree(SubtreeID);
1250 SchedImpl->scheduleTree(SubtreeID);
1251 }
1252 }
1253
1254 // Notify the scheduling strategy after updating the DAG.
1255 SchedImpl->schedNode(SU, IsTopNode);
Andrew Trick92179162015-03-27 06:10:13 +00001256
1257 updateQueues(SU, IsTopNode);
Andrew Trick78e5efe2012-09-11 00:39:15 +00001258 }
1259 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
1260
1261 placeDebugValues();
Andrew Trick3b87f622012-11-07 07:05:09 +00001262
Nicola Zaghen0818e782018-05-14 12:53:11 +00001263 LLVM_DEBUG({
Francis Visoiu Mistrihca0df552017-12-04 17:18:51 +00001264 dbgs() << "*** Final schedule for "
1265 << printMBBReference(*begin()->getParent()) << " ***\n";
1266 dumpSchedule();
1267 dbgs() << '\n';
1268 });
Andrew Trick78e5efe2012-09-11 00:39:15 +00001269}
1270
1271/// Build the DAG and setup three register pressure trackers.
Andrew Tricka38b0de2013-12-28 21:56:47 +00001272void ScheduleDAGMILive::buildDAGWithRegPressure() {
Andrew Trick42ebb3a2013-09-04 20:59:59 +00001273 if (!ShouldTrackPressure) {
1274 RPTracker.reset();
1275 RegionCriticalPSets.clear();
1276 buildSchedGraph(AA);
1277 return;
1278 }
1279
Andrew Trick7f8ab782012-05-10 21:06:10 +00001280 // Initialize the register pressure tracker used by buildSchedGraph.
Andrew Trickd71efff2013-07-30 19:59:12 +00001281 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
Matthias Braund267d372016-01-20 00:23:32 +00001282 ShouldTrackLaneMasks, /*TrackUntiedDefs=*/true);
Andrew Trick006e1ab2012-04-24 17:56:43 +00001283
Andrew Trick7f8ab782012-05-10 21:06:10 +00001284 // Account for liveness generate by the region boundary.
1285 if (LiveRegionEnd != RegionEnd)
1286 RPTracker.recede();
1287
1288 // Build the DAG, and compute current register pressure.
Matthias Braund267d372016-01-20 00:23:32 +00001289 buildSchedGraph(AA, &RPTracker, &SUPressureDiffs, LIS, ShouldTrackLaneMasks);
Andrew Trickc174eaf2012-03-08 01:41:12 +00001290
Andrew Trick7f8ab782012-05-10 21:06:10 +00001291 // Initialize top/bottom trackers after computing region pressure.
1292 initRegPressure();
Andrew Trick78e5efe2012-09-11 00:39:15 +00001293}
Andrew Trick7f8ab782012-05-10 21:06:10 +00001294
Andrew Tricka38b0de2013-12-28 21:56:47 +00001295void ScheduleDAGMILive::computeDFSResult() {
Andrew Trick178f7d02013-01-25 04:01:04 +00001296 if (!DFSResult)
1297 DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize);
1298 DFSResult->clear();
Andrew Trick178f7d02013-01-25 04:01:04 +00001299 ScheduledTrees.clear();
Andrew Trick4e1fb182013-01-25 06:33:57 +00001300 DFSResult->resize(SUnits.size());
1301 DFSResult->compute(SUnits);
Andrew Trick178f7d02013-01-25 04:01:04 +00001302 ScheduledTrees.resize(DFSResult->getNumSubtrees());
1303}
1304
Andrew Trick851bb2c2013-08-29 18:04:49 +00001305/// Compute the max cyclic critical path through the DAG. The scheduling DAG
1306/// only provides the critical path for single block loops. To handle loops that
1307/// span blocks, we could use the vreg path latencies provided by
1308/// MachineTraceMetrics instead. However, MachineTraceMetrics is not currently
1309/// available for use in the scheduler.
1310///
1311/// The cyclic path estimation identifies a def-use pair that crosses the back
Andrew Trick6dc6a892013-08-30 02:02:12 +00001312/// edge and considers the depth and height of the nodes. For example, consider
Andrew Trick851bb2c2013-08-29 18:04:49 +00001313/// the following instruction sequence where each instruction has unit latency
1314/// and defines an epomymous virtual register:
1315///
1316/// a->b(a,c)->c(b)->d(c)->exit
1317///
1318/// The cyclic critical path is a two cycles: b->c->b
1319/// The acyclic critical path is four cycles: a->b->c->d->exit
1320/// LiveOutHeight = height(c) = len(c->d->exit) = 2
1321/// LiveOutDepth = depth(c) + 1 = len(a->b->c) + 1 = 3
1322/// LiveInHeight = height(b) + 1 = len(b->c->d->exit) + 1 = 4
1323/// LiveInDepth = depth(b) = len(a->b) = 1
1324///
1325/// LiveOutDepth - LiveInDepth = 3 - 1 = 2
1326/// LiveInHeight - LiveOutHeight = 4 - 2 = 2
1327/// CyclicCriticalPath = min(2, 2) = 2
Andrew Tricka38b0de2013-12-28 21:56:47 +00001328///
1329/// This could be relevant to PostRA scheduling, but is currently implemented
1330/// assuming LiveIntervals.
1331unsigned ScheduleDAGMILive::computeCyclicCriticalPath() {
Andrew Trick851bb2c2013-08-29 18:04:49 +00001332 // This only applies to single block loop.
1333 if (!BB->isSuccessor(BB))
1334 return 0;
1335
1336 unsigned MaxCyclicLatency = 0;
1337 // Visit each live out vreg def to find def/use pairs that cross iterations.
Matthias Braun051b30e2016-01-20 00:23:26 +00001338 for (const RegisterMaskPair &P : RPTracker.getPressure().LiveOutRegs) {
1339 unsigned Reg = P.RegUnit;
Andrew Trick851bb2c2013-08-29 18:04:49 +00001340 if (!TRI->isVirtualRegister(Reg))
1341 continue;
1342 const LiveInterval &LI = LIS->getInterval(Reg);
1343 const VNInfo *DefVNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
1344 if (!DefVNI)
1345 continue;
1346
1347 MachineInstr *DefMI = LIS->getInstructionFromIndex(DefVNI->def);
1348 const SUnit *DefSU = getSUnit(DefMI);
1349 if (!DefSU)
1350 continue;
1351
1352 unsigned LiveOutHeight = DefSU->getHeight();
1353 unsigned LiveOutDepth = DefSU->getDepth() + DefSU->Latency;
1354 // Visit all local users of the vreg def.
Matthias Braun6f23ba22015-10-29 03:57:17 +00001355 for (const VReg2SUnit &V2SU
1356 : make_range(VRegUses.find(Reg), VRegUses.end())) {
1357 SUnit *SU = V2SU.SU;
1358 if (SU == &ExitSU)
Andrew Trick851bb2c2013-08-29 18:04:49 +00001359 continue;
1360
1361 // Only consider uses of the phi.
Duncan P. N. Exon Smith42e18352016-02-27 06:40:41 +00001362 LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(*SU->getInstr()));
Andrew Trick851bb2c2013-08-29 18:04:49 +00001363 if (!LRQ.valueIn()->isPHIDef())
1364 continue;
1365
1366 // Assume that a path spanning two iterations is a cycle, which could
1367 // overestimate in strange cases. This allows cyclic latency to be
1368 // estimated as the minimum slack of the vreg's depth or height.
1369 unsigned CyclicLatency = 0;
Matthias Braun6f23ba22015-10-29 03:57:17 +00001370 if (LiveOutDepth > SU->getDepth())
1371 CyclicLatency = LiveOutDepth - SU->getDepth();
Andrew Trick851bb2c2013-08-29 18:04:49 +00001372
Matthias Braun6f23ba22015-10-29 03:57:17 +00001373 unsigned LiveInHeight = SU->getHeight() + DefSU->Latency;
Andrew Trick851bb2c2013-08-29 18:04:49 +00001374 if (LiveInHeight > LiveOutHeight) {
1375 if (LiveInHeight - LiveOutHeight < CyclicLatency)
1376 CyclicLatency = LiveInHeight - LiveOutHeight;
Matthias Braund3962152016-04-21 01:54:13 +00001377 } else
Andrew Trick851bb2c2013-08-29 18:04:49 +00001378 CyclicLatency = 0;
1379
Nicola Zaghen0818e782018-05-14 12:53:11 +00001380 LLVM_DEBUG(dbgs() << "Cyclic Path: SU(" << DefSU->NodeNum << ") -> SU("
1381 << SU->NodeNum << ") = " << CyclicLatency << "c\n");
Andrew Trick851bb2c2013-08-29 18:04:49 +00001382 if (CyclicLatency > MaxCyclicLatency)
1383 MaxCyclicLatency = CyclicLatency;
1384 }
1385 }
Nicola Zaghen0818e782018-05-14 12:53:11 +00001386 LLVM_DEBUG(dbgs() << "Cyclic Critical Path: " << MaxCyclicLatency << "c\n");
Andrew Trick851bb2c2013-08-29 18:04:49 +00001387 return MaxCyclicLatency;
1388}
1389
Krzysztof Parzyszek6af1d8f2016-04-28 19:17:44 +00001390/// Release ExitSU predecessors and setup scheduler queues. Re-position
1391/// the Top RP tracker in case the region beginning has changed.
1392void ScheduleDAGMILive::initQueues(ArrayRef<SUnit*> TopRoots,
1393 ArrayRef<SUnit*> BotRoots) {
1394 ScheduleDAGMI::initQueues(TopRoots, BotRoots);
1395 if (ShouldTrackPressure) {
1396 assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
1397 TopRPTracker.setPos(CurrentTop);
1398 }
1399}
1400
Andrew Trick78e5efe2012-09-11 00:39:15 +00001401/// Move an instruction and update register pressure.
Andrew Tricka38b0de2013-12-28 21:56:47 +00001402void ScheduleDAGMILive::scheduleMI(SUnit *SU, bool IsTopNode) {
Andrew Trick78e5efe2012-09-11 00:39:15 +00001403 // Move the instruction to its new location in the instruction stream.
1404 MachineInstr *MI = SU->getInstr();
Andrew Trickc174eaf2012-03-08 01:41:12 +00001405
Andrew Trick78e5efe2012-09-11 00:39:15 +00001406 if (IsTopNode) {
1407 assert(SU->isTopReady() && "node still has unscheduled dependencies");
1408 if (&*CurrentTop == MI)
1409 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
Andrew Trick17d35e52012-03-14 04:00:41 +00001410 else {
Andrew Trick78e5efe2012-09-11 00:39:15 +00001411 moveInstruction(MI, CurrentTop);
1412 TopRPTracker.setPos(MI);
Andrew Trick17d35e52012-03-14 04:00:41 +00001413 }
Andrew Trick000b2502012-04-24 18:04:37 +00001414
Andrew Trick42ebb3a2013-09-04 20:59:59 +00001415 if (ShouldTrackPressure) {
1416 // Update top scheduled pressure.
Matthias Braund267d372016-01-20 00:23:32 +00001417 RegisterOperands RegOpers;
1418 RegOpers.collect(*MI, *TRI, MRI, ShouldTrackLaneMasks, false);
1419 if (ShouldTrackLaneMasks) {
1420 // Adjust liveness and add missing dead+read-undef flags.
Duncan P. N. Exon Smith42e18352016-02-27 06:40:41 +00001421 SlotIndex SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot();
Matthias Braund267d372016-01-20 00:23:32 +00001422 RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx, MI);
1423 } else {
1424 // Adjust for missing dead-def flags.
1425 RegOpers.detectDeadDefs(*MI, *LIS);
1426 }
1427
1428 TopRPTracker.advance(RegOpers);
Andrew Trick42ebb3a2013-09-04 20:59:59 +00001429 assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
Nicola Zaghen0818e782018-05-14 12:53:11 +00001430 LLVM_DEBUG(dbgs() << "Top Pressure:\n"; dumpRegSetPressure(
1431 TopRPTracker.getRegSetPressureAtPos(), TRI););
Matthias Braun810bd4f2015-11-06 20:59:02 +00001432
Andrew Trickfb386db2013-09-06 17:32:47 +00001433 updateScheduledPressure(SU, TopRPTracker.getPressure().MaxSetPressure);
Andrew Trick42ebb3a2013-09-04 20:59:59 +00001434 }
Matthias Braund3962152016-04-21 01:54:13 +00001435 } else {
Andrew Trick78e5efe2012-09-11 00:39:15 +00001436 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
1437 MachineBasicBlock::iterator priorII =
1438 priorNonDebug(CurrentBottom, CurrentTop);
1439 if (&*priorII == MI)
1440 CurrentBottom = priorII;
1441 else {
1442 if (&*CurrentTop == MI) {
1443 CurrentTop = nextIfDebug(++CurrentTop, priorII);
1444 TopRPTracker.setPos(CurrentTop);
1445 }
1446 moveInstruction(MI, CurrentBottom);
1447 CurrentBottom = MI;
Yaxun Liu73f65822018-01-23 16:04:53 +00001448 BotRPTracker.setPos(CurrentBottom);
Andrew Trick78e5efe2012-09-11 00:39:15 +00001449 }
Andrew Trick42ebb3a2013-09-04 20:59:59 +00001450 if (ShouldTrackPressure) {
Matthias Braund267d372016-01-20 00:23:32 +00001451 RegisterOperands RegOpers;
1452 RegOpers.collect(*MI, *TRI, MRI, ShouldTrackLaneMasks, false);
1453 if (ShouldTrackLaneMasks) {
1454 // Adjust liveness and add missing dead+read-undef flags.
Duncan P. N. Exon Smith42e18352016-02-27 06:40:41 +00001455 SlotIndex SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot();
Matthias Braund267d372016-01-20 00:23:32 +00001456 RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx, MI);
1457 } else {
1458 // Adjust for missing dead-def flags.
1459 RegOpers.detectDeadDefs(*MI, *LIS);
1460 }
1461
Yaxun Liu06d39e22017-12-15 03:56:57 +00001462 if (BotRPTracker.getPos() != CurrentBottom)
1463 BotRPTracker.recedeSkipDebugValues();
Matthias Braun051b30e2016-01-20 00:23:26 +00001464 SmallVector<RegisterMaskPair, 8> LiveUses;
Matthias Braund267d372016-01-20 00:23:32 +00001465 BotRPTracker.recede(RegOpers, &LiveUses);
Andrew Trick42ebb3a2013-09-04 20:59:59 +00001466 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
Nicola Zaghen0818e782018-05-14 12:53:11 +00001467 LLVM_DEBUG(dbgs() << "Bottom Pressure:\n"; dumpRegSetPressure(
1468 BotRPTracker.getRegSetPressureAtPos(), TRI););
Matthias Braun810bd4f2015-11-06 20:59:02 +00001469
Andrew Trickfb386db2013-09-06 17:32:47 +00001470 updateScheduledPressure(SU, BotRPTracker.getPressure().MaxSetPressure);
Andrew Trick42ebb3a2013-09-04 20:59:59 +00001471 updatePressureDiffs(LiveUses);
Andrew Trick42ebb3a2013-09-04 20:59:59 +00001472 }
Andrew Trick78e5efe2012-09-11 00:39:15 +00001473 }
1474}
1475
Andrew Trick6996fd02012-11-12 19:52:20 +00001476//===----------------------------------------------------------------------===//
Jun Bum Lim232aafc2016-04-15 14:58:38 +00001477// BaseMemOpClusterMutation - DAG post-processing to cluster loads or stores.
Andrew Trick6996fd02012-11-12 19:52:20 +00001478//===----------------------------------------------------------------------===//
1479
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001480namespace {
Eugene Zelenko096e40d2017-02-22 22:32:51 +00001481
Adrian Prantl26b584c2018-05-01 15:54:18 +00001482/// Post-process the DAG to create cluster edges between neighboring
Jun Bum Lim232aafc2016-04-15 14:58:38 +00001483/// loads or between neighboring stores.
1484class BaseMemOpClusterMutation : public ScheduleDAGMutation {
1485 struct MemOpInfo {
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001486 SUnit *SU;
Francis Visoiu Mistrih83895b32018-11-28 12:00:20 +00001487 MachineOperand *BaseOp;
Chad Rosiercd3a68c2016-03-09 16:00:35 +00001488 int64_t Offset;
Eugene Zelenko096e40d2017-02-22 22:32:51 +00001489
Francis Visoiu Mistrih83895b32018-11-28 12:00:20 +00001490 MemOpInfo(SUnit *su, MachineOperand *Op, int64_t ofs)
1491 : SU(su), BaseOp(Op), Offset(ofs) {}
Benjamin Kramere1362f12014-03-07 21:35:39 +00001492
Francis Visoiu Mistrih83895b32018-11-28 12:00:20 +00001493 bool operator<(const MemOpInfo &RHS) const {
Francis Visoiu Mistrih9ba9c032018-11-28 12:00:28 +00001494 if (BaseOp->getType() != RHS.BaseOp->getType())
1495 return BaseOp->getType() < RHS.BaseOp->getType();
1496
1497 if (BaseOp->isReg())
1498 return std::make_tuple(BaseOp->getReg(), Offset, SU->NodeNum) <
1499 std::make_tuple(RHS.BaseOp->getReg(), RHS.Offset,
1500 RHS.SU->NodeNum);
Francis Visoiu Mistrih50c71c52018-11-29 20:03:19 +00001501 if (BaseOp->isFI()) {
1502 const MachineFunction &MF =
1503 *BaseOp->getParent()->getParent()->getParent();
1504 const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
1505 bool StackGrowsDown = TFI.getStackGrowthDirection() ==
1506 TargetFrameLowering::StackGrowsDown;
1507 // Can't use tuple comparison here since we might need to use a
1508 // different order when the stack grows down.
1509 if (BaseOp->getIndex() != RHS.BaseOp->getIndex())
1510 return StackGrowsDown ? BaseOp->getIndex() > RHS.BaseOp->getIndex()
1511 : BaseOp->getIndex() < RHS.BaseOp->getIndex();
1512
1513 if (Offset != RHS.Offset)
1514 return StackGrowsDown ? Offset > RHS.Offset : Offset < RHS.Offset;
1515
1516 return SU->NodeNum < RHS.SU->NodeNum;
1517 }
Francis Visoiu Mistrih9ba9c032018-11-28 12:00:28 +00001518
1519 llvm_unreachable("MemOpClusterMutation only supports register or frame "
1520 "index bases.");
Benjamin Kramere1362f12014-03-07 21:35:39 +00001521 }
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001522 };
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001523
1524 const TargetInstrInfo *TII;
1525 const TargetRegisterInfo *TRI;
Jun Bum Lim232aafc2016-04-15 14:58:38 +00001526 bool IsLoad;
1527
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001528public:
Jun Bum Lim232aafc2016-04-15 14:58:38 +00001529 BaseMemOpClusterMutation(const TargetInstrInfo *tii,
1530 const TargetRegisterInfo *tri, bool IsLoad)
1531 : TII(tii), TRI(tri), IsLoad(IsLoad) {}
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001532
Krzysztof Parzyszek0c79dd72016-03-05 15:45:23 +00001533 void apply(ScheduleDAGInstrs *DAGInstrs) override;
Jun Bum Lim232aafc2016-04-15 14:58:38 +00001534
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001535protected:
Jun Bum Lim232aafc2016-04-15 14:58:38 +00001536 void clusterNeighboringMemOps(ArrayRef<SUnit *> MemOps, ScheduleDAGMI *DAG);
1537};
1538
1539class StoreClusterMutation : public BaseMemOpClusterMutation {
1540public:
1541 StoreClusterMutation(const TargetInstrInfo *tii,
1542 const TargetRegisterInfo *tri)
1543 : BaseMemOpClusterMutation(tii, tri, false) {}
1544};
1545
1546class LoadClusterMutation : public BaseMemOpClusterMutation {
1547public:
1548 LoadClusterMutation(const TargetInstrInfo *tii, const TargetRegisterInfo *tri)
1549 : BaseMemOpClusterMutation(tii, tri, true) {}
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001550};
Eugene Zelenko096e40d2017-02-22 22:32:51 +00001551
1552} // end anonymous namespace
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001553
Tom Stellard9163bca2016-08-19 19:59:18 +00001554namespace llvm {
1555
1556std::unique_ptr<ScheduleDAGMutation>
1557createLoadClusterDAGMutation(const TargetInstrInfo *TII,
1558 const TargetRegisterInfo *TRI) {
Eugene Zelenko096e40d2017-02-22 22:32:51 +00001559 return EnableMemOpCluster ? llvm::make_unique<LoadClusterMutation>(TII, TRI)
Matthias Braun05bdd2e2016-11-28 20:11:54 +00001560 : nullptr;
Tom Stellard9163bca2016-08-19 19:59:18 +00001561}
1562
1563std::unique_ptr<ScheduleDAGMutation>
1564createStoreClusterDAGMutation(const TargetInstrInfo *TII,
1565 const TargetRegisterInfo *TRI) {
Eugene Zelenko096e40d2017-02-22 22:32:51 +00001566 return EnableMemOpCluster ? llvm::make_unique<StoreClusterMutation>(TII, TRI)
Matthias Braun05bdd2e2016-11-28 20:11:54 +00001567 : nullptr;
Tom Stellard9163bca2016-08-19 19:59:18 +00001568}
1569
Eugene Zelenko096e40d2017-02-22 22:32:51 +00001570} // end namespace llvm
Tom Stellard9163bca2016-08-19 19:59:18 +00001571
Jun Bum Lim232aafc2016-04-15 14:58:38 +00001572void BaseMemOpClusterMutation::clusterNeighboringMemOps(
1573 ArrayRef<SUnit *> MemOps, ScheduleDAGMI *DAG) {
1574 SmallVector<MemOpInfo, 32> MemOpRecords;
Javed Absar829442a2017-06-21 09:10:10 +00001575 for (SUnit *SU : MemOps) {
Francis Visoiu Mistrih83895b32018-11-28 12:00:20 +00001576 MachineOperand *BaseOp;
Chad Rosiercd3a68c2016-03-09 16:00:35 +00001577 int64_t Offset;
Francis Visoiu Mistrih83895b32018-11-28 12:00:20 +00001578 if (TII->getMemOperandWithOffset(*SU->getInstr(), BaseOp, Offset, TRI))
1579 MemOpRecords.push_back(MemOpInfo(SU, BaseOp, Offset));
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001580 }
Jun Bum Lim232aafc2016-04-15 14:58:38 +00001581 if (MemOpRecords.size() < 2)
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001582 return;
Jun Bum Lim232aafc2016-04-15 14:58:38 +00001583
Fangrui Song3b35e172018-09-27 02:13:45 +00001584 llvm::sort(MemOpRecords);
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001585 unsigned ClusterLength = 1;
Jun Bum Lim232aafc2016-04-15 14:58:38 +00001586 for (unsigned Idx = 0, End = MemOpRecords.size(); Idx < (End - 1); ++Idx) {
Jun Bum Lim232aafc2016-04-15 14:58:38 +00001587 SUnit *SUa = MemOpRecords[Idx].SU;
1588 SUnit *SUb = MemOpRecords[Idx+1].SU;
Francis Visoiu Mistrih83895b32018-11-28 12:00:20 +00001589 if (TII->shouldClusterMemOps(*MemOpRecords[Idx].BaseOp,
1590 *MemOpRecords[Idx + 1].BaseOp,
Duncan P. N. Exon Smith567409d2016-06-30 00:01:54 +00001591 ClusterLength) &&
1592 DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00001593 LLVM_DEBUG(dbgs() << "Cluster ld/st SU(" << SUa->NodeNum << ") - SU("
1594 << SUb->NodeNum << ")\n");
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001595 // Copy successor edges from SUa to SUb. Interleaving computation
1596 // dependent on SUa can prevent load combining due to register reuse.
1597 // Predecessor edges do not need to be copied from SUb to SUa since nearby
1598 // loads should have effectively the same inputs.
Javed Absar829442a2017-06-21 09:10:10 +00001599 for (const SDep &Succ : SUa->Succs) {
1600 if (Succ.getSUnit() == SUb)
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001601 continue;
Nicola Zaghen0818e782018-05-14 12:53:11 +00001602 LLVM_DEBUG(dbgs() << " Copy Succ SU(" << Succ.getSUnit()->NodeNum
1603 << ")\n");
Javed Absar829442a2017-06-21 09:10:10 +00001604 DAG->addEdge(Succ.getSUnit(), SDep(SUb, SDep::Artificial));
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001605 }
1606 ++ClusterLength;
Matthias Braund3962152016-04-21 01:54:13 +00001607 } else
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001608 ClusterLength = 1;
1609 }
1610}
1611
Adrian Prantl26b584c2018-05-01 15:54:18 +00001612/// Callback from DAG postProcessing to create cluster edges for loads.
Jun Bum Lim232aafc2016-04-15 14:58:38 +00001613void BaseMemOpClusterMutation::apply(ScheduleDAGInstrs *DAGInstrs) {
Krzysztof Parzyszek0c79dd72016-03-05 15:45:23 +00001614 ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs);
1615
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001616 // Map DAG NodeNum to store chain ID.
1617 DenseMap<unsigned, unsigned> StoreChainIDs;
Jun Bum Lim232aafc2016-04-15 14:58:38 +00001618 // Map each store chain to a set of dependent MemOps.
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001619 SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
Javed Absar829442a2017-06-21 09:10:10 +00001620 for (SUnit &SU : DAG->SUnits) {
1621 if ((IsLoad && !SU.getInstr()->mayLoad()) ||
1622 (!IsLoad && !SU.getInstr()->mayStore()))
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001623 continue;
Jun Bum Lim232aafc2016-04-15 14:58:38 +00001624
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001625 unsigned ChainPredID = DAG->SUnits.size();
Javed Absar829442a2017-06-21 09:10:10 +00001626 for (const SDep &Pred : SU.Preds) {
1627 if (Pred.isCtrl()) {
1628 ChainPredID = Pred.getSUnit()->NodeNum;
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001629 break;
1630 }
1631 }
1632 // Check if this chain-like pred has been seen
Jun Bum Lim232aafc2016-04-15 14:58:38 +00001633 // before. ChainPredID==MaxNodeID at the top of the schedule.
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001634 unsigned NumChains = StoreChainDependents.size();
1635 std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
1636 StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
1637 if (Result.second)
1638 StoreChainDependents.resize(NumChains + 1);
Javed Absar829442a2017-06-21 09:10:10 +00001639 StoreChainDependents[Result.first->second].push_back(&SU);
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001640 }
Jun Bum Lim232aafc2016-04-15 14:58:38 +00001641
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001642 // Iterate over the store chains.
Javed Absar829442a2017-06-21 09:10:10 +00001643 for (auto &SCD : StoreChainDependents)
1644 clusterNeighboringMemOps(SCD, DAG);
Andrew Trick9b5caaa2012-11-12 19:40:10 +00001645}
1646
Andrew Trickc174eaf2012-03-08 01:41:12 +00001647//===----------------------------------------------------------------------===//
Andrew Tricke38afe12013-04-24 15:54:43 +00001648// CopyConstrain - DAG post-processing to encourage copy elimination.
1649//===----------------------------------------------------------------------===//
1650
1651namespace {
Eugene Zelenko096e40d2017-02-22 22:32:51 +00001652
Adrian Prantl26b584c2018-05-01 15:54:18 +00001653/// Post-process the DAG to create weak edges from all uses of a copy to
Andrew Tricke38afe12013-04-24 15:54:43 +00001654/// the one use that defines the copy's source vreg, most likely an induction
1655/// variable increment.
1656class CopyConstrain : public ScheduleDAGMutation {
1657 // Transient state.
1658 SlotIndex RegionBeginIdx;
Eugene Zelenko8fd05042017-09-11 23:00:48 +00001659
Andrew Tricka264a202013-04-24 23:19:56 +00001660 // RegionEndIdx is the slot index of the last non-debug instruction in the
1661 // scheduling region. So we may have RegionBeginIdx == RegionEndIdx.
Andrew Tricke38afe12013-04-24 15:54:43 +00001662 SlotIndex RegionEndIdx;
Eugene Zelenko096e40d2017-02-22 22:32:51 +00001663
Andrew Tricke38afe12013-04-24 15:54:43 +00001664public:
1665 CopyConstrain(const TargetInstrInfo *, const TargetRegisterInfo *) {}
1666
Krzysztof Parzyszek0c79dd72016-03-05 15:45:23 +00001667 void apply(ScheduleDAGInstrs *DAGInstrs) override;
Andrew Tricke38afe12013-04-24 15:54:43 +00001668
1669protected:
Andrew Tricka38b0de2013-12-28 21:56:47 +00001670 void constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG);
Andrew Tricke38afe12013-04-24 15:54:43 +00001671};
Eugene Zelenko096e40d2017-02-22 22:32:51 +00001672
1673} // end anonymous namespace
Andrew Tricke38afe12013-04-24 15:54:43 +00001674
Tom Stellard9163bca2016-08-19 19:59:18 +00001675namespace llvm {
1676
1677std::unique_ptr<ScheduleDAGMutation>
1678createCopyConstrainDAGMutation(const TargetInstrInfo *TII,
Eugene Zelenko096e40d2017-02-22 22:32:51 +00001679 const TargetRegisterInfo *TRI) {
1680 return llvm::make_unique<CopyConstrain>(TII, TRI);
Tom Stellard9163bca2016-08-19 19:59:18 +00001681}
1682
Eugene Zelenko096e40d2017-02-22 22:32:51 +00001683} // end namespace llvm
Tom Stellard9163bca2016-08-19 19:59:18 +00001684
Andrew Tricke38afe12013-04-24 15:54:43 +00001685/// constrainLocalCopy handles two possibilities:
1686/// 1) Local src:
1687/// I0: = dst
1688/// I1: src = ...
1689/// I2: = dst
1690/// I3: dst = src (copy)
1691/// (create pred->succ edges I0->I1, I2->I1)
1692///
1693/// 2) Local copy:
1694/// I0: dst = src (copy)
1695/// I1: = dst
1696/// I2: src = ...
1697/// I3: = dst
1698/// (create pred->succ edges I1->I2, I3->I2)
1699///
1700/// Although the MachineScheduler is currently constrained to single blocks,
1701/// this algorithm should handle extended blocks. An EBB is a set of
1702/// contiguously numbered blocks such that the previous block in the EBB is
1703/// always the single predecessor.
Andrew Tricka38b0de2013-12-28 21:56:47 +00001704void CopyConstrain::constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG) {
Andrew Tricke38afe12013-04-24 15:54:43 +00001705 LiveIntervals *LIS = DAG->getLIS();
1706 MachineInstr *Copy = CopySU->getInstr();
1707
1708 // Check for pure vreg copies.
Matthias Braunbc774222016-04-04 21:23:46 +00001709 const MachineOperand &SrcOp = Copy->getOperand(1);
1710 unsigned SrcReg = SrcOp.getReg();
1711 if (!TargetRegisterInfo::isVirtualRegister(SrcReg) || !SrcOp.readsReg())
Andrew Tricke38afe12013-04-24 15:54:43 +00001712 return;
1713
Matthias Braunbc774222016-04-04 21:23:46 +00001714 const MachineOperand &DstOp = Copy->getOperand(0);
1715 unsigned DstReg = DstOp.getReg();
1716 if (!TargetRegisterInfo::isVirtualRegister(DstReg) || DstOp.isDead())
Andrew Tricke38afe12013-04-24 15:54:43 +00001717 return;
1718
1719 // Check if either the dest or source is local. If it's live across a back
1720 // edge, it's not local. Note that if both vregs are live across the back
1721 // edge, we cannot successfully contrain the copy without cyclic scheduling.
Michael Kuperstein5a0c8602015-01-19 07:30:47 +00001722 // If both the copy's source and dest are local live intervals, then we
1723 // should treat the dest as the global for the purpose of adding
1724 // constraints. This adds edges from source's other uses to the copy.
1725 unsigned LocalReg = SrcReg;
1726 unsigned GlobalReg = DstReg;
Andrew Tricke38afe12013-04-24 15:54:43 +00001727 LiveInterval *LocalLI = &LIS->getInterval(LocalReg);
1728 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx)) {
Michael Kuperstein5a0c8602015-01-19 07:30:47 +00001729 LocalReg = DstReg;
1730 GlobalReg = SrcReg;
Andrew Tricke38afe12013-04-24 15:54:43 +00001731 LocalLI = &LIS->getInterval(LocalReg);
1732 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx))
1733 return;
1734 }
1735 LiveInterval *GlobalLI = &LIS->getInterval(GlobalReg);
1736
1737 // Find the global segment after the start of the local LI.
1738 LiveInterval::iterator GlobalSegment = GlobalLI->find(LocalLI->beginIndex());
1739 // If GlobalLI does not overlap LocalLI->start, then a copy directly feeds a
1740 // local live range. We could create edges from other global uses to the local
1741 // start, but the coalescer should have already eliminated these cases, so
1742 // don't bother dealing with it.
1743 if (GlobalSegment == GlobalLI->end())
1744 return;
1745
1746 // If GlobalSegment is killed at the LocalLI->start, the call to find()
1747 // returned the next global segment. But if GlobalSegment overlaps with
Hiroshi Inoue73d058a2018-06-20 05:29:26 +00001748 // LocalLI->start, then advance to the next segment. If a hole in GlobalLI
Andrew Tricke38afe12013-04-24 15:54:43 +00001749 // exists in LocalLI's vicinity, GlobalSegment will be the end of the hole.
1750 if (GlobalSegment->contains(LocalLI->beginIndex()))
1751 ++GlobalSegment;
1752
1753 if (GlobalSegment == GlobalLI->end())
1754 return;
1755
1756 // Check if GlobalLI contains a hole in the vicinity of LocalLI.
1757 if (GlobalSegment != GlobalLI->begin()) {
1758 // Two address defs have no hole.
Benjamin Kramerd628f192014-03-02 12:27:27 +00001759 if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->end,
Andrew Tricke38afe12013-04-24 15:54:43 +00001760 GlobalSegment->start)) {
1761 return;
1762 }
Andrew Trick1e46fcd2013-07-30 19:59:08 +00001763 // If the prior global segment may be defined by the same two-address
1764 // instruction that also defines LocalLI, then can't make a hole here.
Benjamin Kramerd628f192014-03-02 12:27:27 +00001765 if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->start,
Andrew Trick1e46fcd2013-07-30 19:59:08 +00001766 LocalLI->beginIndex())) {
1767 return;
1768 }
Andrew Tricke38afe12013-04-24 15:54:43 +00001769 // If GlobalLI has a prior segment, it must be live into the EBB. Otherwise
1770 // it would be a disconnected component in the live range.
Benjamin Kramerd628f192014-03-02 12:27:27 +00001771 assert(std::prev(GlobalSegment)->start < LocalLI->beginIndex() &&
Andrew Tricke38afe12013-04-24 15:54:43 +00001772 "Disconnected LRG within the scheduling region.");
1773 }
1774 MachineInstr *GlobalDef = LIS->getInstructionFromIndex(GlobalSegment->start);
1775 if (!GlobalDef)
1776 return;
1777
1778 SUnit *GlobalSU = DAG->getSUnit(GlobalDef);
1779 if (!GlobalSU)
1780 return;
1781
1782 // GlobalDef is the bottom of the GlobalLI hole. Open the hole by
1783 // constraining the uses of the last local def to precede GlobalDef.
1784 SmallVector<SUnit*,8> LocalUses;
1785 const VNInfo *LastLocalVN = LocalLI->getVNInfoBefore(LocalLI->endIndex());
1786 MachineInstr *LastLocalDef = LIS->getInstructionFromIndex(LastLocalVN->def);
1787 SUnit *LastLocalSU = DAG->getSUnit(LastLocalDef);
Javed Absar829442a2017-06-21 09:10:10 +00001788 for (const SDep &Succ : LastLocalSU->Succs) {
1789 if (Succ.getKind() != SDep::Data || Succ.getReg() != LocalReg)
Andrew Tricke38afe12013-04-24 15:54:43 +00001790 continue;
Javed Absar829442a2017-06-21 09:10:10 +00001791 if (Succ.getSUnit() == GlobalSU)
Andrew Tricke38afe12013-04-24 15:54:43 +00001792 continue;
Javed Absar829442a2017-06-21 09:10:10 +00001793 if (!DAG->canAddEdge(GlobalSU, Succ.getSUnit()))
Andrew Tricke38afe12013-04-24 15:54:43 +00001794 return;
Javed Absar829442a2017-06-21 09:10:10 +00001795 LocalUses.push_back(Succ.getSUnit());
Andrew Tricke38afe12013-04-24 15:54:43 +00001796 }
1797 // Open the top of the GlobalLI hole by constraining any earlier global uses
1798 // to precede the start of LocalLI.
1799 SmallVector<SUnit*,8> GlobalUses;
1800 MachineInstr *FirstLocalDef =
1801 LIS->getInstructionFromIndex(LocalLI->beginIndex());
1802 SUnit *FirstLocalSU = DAG->getSUnit(FirstLocalDef);
Javed Absar829442a2017-06-21 09:10:10 +00001803 for (const SDep &Pred : GlobalSU->Preds) {
1804 if (Pred.getKind() != SDep::Anti || Pred.getReg() != GlobalReg)
Andrew Tricke38afe12013-04-24 15:54:43 +00001805 continue;
Javed Absar829442a2017-06-21 09:10:10 +00001806 if (Pred.getSUnit() == FirstLocalSU)
Andrew Tricke38afe12013-04-24 15:54:43 +00001807 continue;
Javed Absar829442a2017-06-21 09:10:10 +00001808 if (!DAG->canAddEdge(FirstLocalSU, Pred.getSUnit()))
Andrew Tricke38afe12013-04-24 15:54:43 +00001809 return;
Javed Absar829442a2017-06-21 09:10:10 +00001810 GlobalUses.push_back(Pred.getSUnit());
Andrew Tricke38afe12013-04-24 15:54:43 +00001811 }
Nicola Zaghen0818e782018-05-14 12:53:11 +00001812 LLVM_DEBUG(dbgs() << "Constraining copy SU(" << CopySU->NodeNum << ")\n");
Andrew Tricke38afe12013-04-24 15:54:43 +00001813 // Add the weak edges.
1814 for (SmallVectorImpl<SUnit*>::const_iterator
1815 I = LocalUses.begin(), E = LocalUses.end(); I != E; ++I) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00001816 LLVM_DEBUG(dbgs() << " Local use SU(" << (*I)->NodeNum << ") -> SU("
1817 << GlobalSU->NodeNum << ")\n");
Andrew Tricke38afe12013-04-24 15:54:43 +00001818 DAG->addEdge(GlobalSU, SDep(*I, SDep::Weak));
1819 }
1820 for (SmallVectorImpl<SUnit*>::const_iterator
1821 I = GlobalUses.begin(), E = GlobalUses.end(); I != E; ++I) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00001822 LLVM_DEBUG(dbgs() << " Global use SU(" << (*I)->NodeNum << ") -> SU("
1823 << FirstLocalSU->NodeNum << ")\n");
Andrew Tricke38afe12013-04-24 15:54:43 +00001824 DAG->addEdge(FirstLocalSU, SDep(*I, SDep::Weak));
1825 }
1826}
1827
Adrian Prantl26b584c2018-05-01 15:54:18 +00001828/// Callback from DAG postProcessing to create weak edges to encourage
Andrew Tricke38afe12013-04-24 15:54:43 +00001829/// copy elimination.
Krzysztof Parzyszek0c79dd72016-03-05 15:45:23 +00001830void CopyConstrain::apply(ScheduleDAGInstrs *DAGInstrs) {
1831 ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs);
Andrew Tricka38b0de2013-12-28 21:56:47 +00001832 assert(DAG->hasVRegLiveness() && "Expect VRegs with LiveIntervals");
1833
Andrew Tricka264a202013-04-24 23:19:56 +00001834 MachineBasicBlock::iterator FirstPos = nextIfDebug(DAG->begin(), DAG->end());
1835 if (FirstPos == DAG->end())
1836 return;
Duncan P. N. Exon Smith42e18352016-02-27 06:40:41 +00001837 RegionBeginIdx = DAG->getLIS()->getInstructionIndex(*FirstPos);
Andrew Tricke38afe12013-04-24 15:54:43 +00001838 RegionEndIdx = DAG->getLIS()->getInstructionIndex(
Duncan P. N. Exon Smith42e18352016-02-27 06:40:41 +00001839 *priorNonDebug(DAG->end(), DAG->begin()));
Andrew Tricke38afe12013-04-24 15:54:43 +00001840
Javed Absar829442a2017-06-21 09:10:10 +00001841 for (SUnit &SU : DAG->SUnits) {
1842 if (!SU.getInstr()->isCopy())
Andrew Tricke38afe12013-04-24 15:54:43 +00001843 continue;
1844
Javed Absar829442a2017-06-21 09:10:10 +00001845 constrainLocalCopy(&SU, static_cast<ScheduleDAGMILive*>(DAG));
Andrew Tricke38afe12013-04-24 15:54:43 +00001846 }
1847}
1848
1849//===----------------------------------------------------------------------===//
Andrew Trickdcddd712013-12-07 05:59:44 +00001850// MachineSchedStrategy helpers used by GenericScheduler, GenericPostScheduler
1851// and possibly other custom schedulers.
Andrew Trick9e76e1d2013-12-28 21:56:57 +00001852//===----------------------------------------------------------------------===//
Andrew Trick42b7a712012-01-17 06:55:03 +00001853
Andrew Trick6606ef02013-12-05 17:56:02 +00001854static const unsigned InvalidCycle = ~0U;
1855
Andrew Trickdcddd712013-12-07 05:59:44 +00001856SchedBoundary::~SchedBoundary() { delete HazardRec; }
Andrew Trick3b87f622012-11-07 07:05:09 +00001857
Jonas Paulsson18622832017-10-25 08:23:33 +00001858/// Given a Count of resource usage and a Latency value, return true if a
1859/// SchedBoundary becomes resource limited.
1860static bool checkResourceLimit(unsigned LFactor, unsigned Count,
1861 unsigned Latency) {
1862 return (int)(Count - (Latency * LFactor)) > (int)LFactor;
1863}
1864
Andrew Trickdcddd712013-12-07 05:59:44 +00001865void SchedBoundary::reset() {
1866 // A new HazardRec is created for each DAG and owned by SchedBoundary.
1867 // Destroying and reconstructing it is very expensive though. So keep
1868 // invalid, placeholder HazardRecs.
1869 if (HazardRec && HazardRec->isEnabled()) {
1870 delete HazardRec;
Craig Topper4ba84432014-04-14 00:51:57 +00001871 HazardRec = nullptr;
Andrew Trickdcddd712013-12-07 05:59:44 +00001872 }
1873 Available.clear();
1874 Pending.clear();
1875 CheckPending = false;
Andrew Trickdcddd712013-12-07 05:59:44 +00001876 CurrCycle = 0;
1877 CurrMOps = 0;
Eugene Zelenko096e40d2017-02-22 22:32:51 +00001878 MinReadyCycle = std::numeric_limits<unsigned>::max();
Andrew Trickdcddd712013-12-07 05:59:44 +00001879 ExpectedLatency = 0;
1880 DependentLatency = 0;
1881 RetiredMOps = 0;
1882 MaxExecutedResCount = 0;
1883 ZoneCritResIdx = 0;
1884 IsResourceLimited = false;
1885 ReservedCycles.clear();
Andrew Trick3b87f622012-11-07 07:05:09 +00001886#ifndef NDEBUG
Andrew Trick9e76e1d2013-12-28 21:56:57 +00001887 // Track the maximum number of stall cycles that could arise either from the
1888 // latency of a DAG edge or the number of cycles that a processor resource is
1889 // reserved (SchedBoundary::ReservedCycles).
Andrew Trick808823c2014-06-07 01:48:43 +00001890 MaxObservedStall = 0;
Andrew Trick3b87f622012-11-07 07:05:09 +00001891#endif
Andrew Trickdcddd712013-12-07 05:59:44 +00001892 // Reserve a zero-count for invalid CritResIdx.
1893 ExecutedResCounts.resize(1);
1894 assert(!ExecutedResCounts[0] && "nonzero count for bad resource");
1895}
Andrew Trick3b87f622012-11-07 07:05:09 +00001896
Andrew Trickdcddd712013-12-07 05:59:44 +00001897void SchedRemainder::
Andrew Trick3b87f622012-11-07 07:05:09 +00001898init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
1899 reset();
1900 if (!SchedModel->hasInstrSchedModel())
1901 return;
1902 RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
Javed Absar829442a2017-06-21 09:10:10 +00001903 for (SUnit &SU : DAG->SUnits) {
1904 const MCSchedClassDesc *SC = DAG->getSchedClass(&SU);
1905 RemIssueCount += SchedModel->getNumMicroOps(SU.getInstr(), SC)
Andrew Trickfa989e72013-06-15 05:39:19 +00001906 * SchedModel->getMicroOpFactor();
Andrew Trick3b87f622012-11-07 07:05:09 +00001907 for (TargetSchedModel::ProcResIter
1908 PI = SchedModel->getWriteProcResBegin(SC),
1909 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1910 unsigned PIdx = PI->ProcResourceIdx;
1911 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1912 RemainingCounts[PIdx] += (Factor * PI->Cycles);
1913 }
1914 }
1915}
1916
Andrew Trickdcddd712013-12-07 05:59:44 +00001917void SchedBoundary::
Andrew Trick3b87f622012-11-07 07:05:09 +00001918init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
1919 reset();
1920 DAG = dag;
1921 SchedModel = smodel;
1922 Rem = rem;
Andrew Trick6606ef02013-12-05 17:56:02 +00001923 if (SchedModel->hasInstrSchedModel()) {
Andrew Trickfa989e72013-06-15 05:39:19 +00001924 ExecutedResCounts.resize(SchedModel->getNumProcResourceKinds());
Andrew Trick6606ef02013-12-05 17:56:02 +00001925 ReservedCycles.resize(SchedModel->getNumProcResourceKinds(), InvalidCycle);
1926 }
Andrew Trick3b87f622012-11-07 07:05:09 +00001927}
1928
Andrew Trick57393132013-12-05 17:55:58 +00001929/// Compute the stall cycles based on this SUnit's ready time. Heuristics treat
1930/// these "soft stalls" differently than the hard stall cycles based on CPU
1931/// resources and computed by checkHazard(). A fully in-order model
1932/// (MicroOpBufferSize==0) will not make use of this since instructions are not
1933/// available for scheduling until they are ready. However, a weaker in-order
1934/// model may use this for heuristics. For example, if a processor has in-order
1935/// behavior when reading certain resources, this may come into play.
Andrew Trickdcddd712013-12-07 05:59:44 +00001936unsigned SchedBoundary::getLatencyStallCycles(SUnit *SU) {
Andrew Trick57393132013-12-05 17:55:58 +00001937 if (!SU->isUnbuffered)
1938 return 0;
1939
1940 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
1941 if (ReadyCycle > CurrCycle)
1942 return ReadyCycle - CurrCycle;
1943 return 0;
1944}
1945
Andrew Trick6606ef02013-12-05 17:56:02 +00001946/// Compute the next cycle at which the given processor resource can be
1947/// scheduled.
Andrew Trickdcddd712013-12-07 05:59:44 +00001948unsigned SchedBoundary::
Andrew Trick6606ef02013-12-05 17:56:02 +00001949getNextResourceCycle(unsigned PIdx, unsigned Cycles) {
1950 unsigned NextUnreserved = ReservedCycles[PIdx];
1951 // If this resource has never been used, always return cycle zero.
1952 if (NextUnreserved == InvalidCycle)
1953 return 0;
1954 // For bottom-up scheduling add the cycles needed for the current operation.
1955 if (!isTop())
1956 NextUnreserved += Cycles;
1957 return NextUnreserved;
1958}
1959
Andrew Trick5559ffa2012-06-29 03:23:24 +00001960/// Does this SU have a hazard within the current instruction group.
1961///
1962/// The scheduler supports two modes of hazard recognition. The first is the
1963/// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
1964/// supports highly complicated in-order reservation tables
Hiroshi Inoue73d058a2018-06-20 05:29:26 +00001965/// (ScoreboardHazardRecognizer) and arbitrary target-specific logic.
Andrew Trick5559ffa2012-06-29 03:23:24 +00001966///
1967/// The second is a streamlined mechanism that checks for hazards based on
1968/// simple counters that the scheduler itself maintains. It explicitly checks
1969/// for instruction dispatch limitations, including the number of micro-ops that
1970/// can dispatch per cycle.
1971///
1972/// TODO: Also check whether the SU must start a new group.
Andrew Trickdcddd712013-12-07 05:59:44 +00001973bool SchedBoundary::checkHazard(SUnit *SU) {
Andrew Trick9e76e1d2013-12-28 21:56:57 +00001974 if (HazardRec->isEnabled()
1975 && HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard) {
1976 return true;
1977 }
Javed Absar47652292017-03-27 20:46:37 +00001978
Andrew Trick412cd2f2012-10-10 05:43:09 +00001979 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
Andrew Trickbacb2492013-06-15 04:49:49 +00001980 if ((CurrMOps > 0) && (CurrMOps + uops > SchedModel->getIssueWidth())) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00001981 LLVM_DEBUG(dbgs() << " SU(" << SU->NodeNum << ") uops="
1982 << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
Andrew Trick5559ffa2012-06-29 03:23:24 +00001983 return true;
Andrew Trick3b87f622012-11-07 07:05:09 +00001984 }
Javed Absar47652292017-03-27 20:46:37 +00001985
1986 if (CurrMOps > 0 &&
1987 ((isTop() && SchedModel->mustBeginGroup(SU->getInstr())) ||
1988 (!isTop() && SchedModel->mustEndGroup(SU->getInstr())))) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00001989 LLVM_DEBUG(dbgs() << " hazard: SU(" << SU->NodeNum << ") must "
1990 << (isTop() ? "begin" : "end") << " group\n");
Javed Absar47652292017-03-27 20:46:37 +00001991 return true;
1992 }
1993
Andrew Trick6606ef02013-12-05 17:56:02 +00001994 if (SchedModel->hasInstrSchedModel() && SU->hasReservedResource) {
1995 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
Javed Absar1f4dc262017-10-03 09:35:04 +00001996 for (const MCWriteProcResEntry &PE :
1997 make_range(SchedModel->getWriteProcResBegin(SC),
1998 SchedModel->getWriteProcResEnd(SC))) {
1999 unsigned ResIdx = PE.ProcResourceIdx;
2000 unsigned Cycles = PE.Cycles;
2001 unsigned NRCycle = getNextResourceCycle(ResIdx, Cycles);
Andrew Tricke8f8db12014-06-27 04:57:05 +00002002 if (NRCycle > CurrCycle) {
Andrew Trickac5b1ec2014-06-27 05:09:36 +00002003#ifndef NDEBUG
Javed Absar1f4dc262017-10-03 09:35:04 +00002004 MaxObservedStall = std::max(Cycles, MaxObservedStall);
Andrew Trickac5b1ec2014-06-27 05:09:36 +00002005#endif
Nicola Zaghen0818e782018-05-14 12:53:11 +00002006 LLVM_DEBUG(dbgs() << " SU(" << SU->NodeNum << ") "
2007 << SchedModel->getResourceName(ResIdx) << "="
2008 << NRCycle << "c\n");
Andrew Trick6606ef02013-12-05 17:56:02 +00002009 return true;
Andrew Tricke8f8db12014-06-27 04:57:05 +00002010 }
Andrew Trick6606ef02013-12-05 17:56:02 +00002011 }
2012 }
Andrew Trick5559ffa2012-06-29 03:23:24 +00002013 return false;
2014}
2015
Andrew Trickfa989e72013-06-15 05:39:19 +00002016// Find the unscheduled node in ReadySUs with the highest latency.
Andrew Trickdcddd712013-12-07 05:59:44 +00002017unsigned SchedBoundary::
Andrew Trickfa989e72013-06-15 05:39:19 +00002018findMaxLatency(ArrayRef<SUnit*> ReadySUs) {
Craig Topper4ba84432014-04-14 00:51:57 +00002019 SUnit *LateSU = nullptr;
Andrew Trickfa989e72013-06-15 05:39:19 +00002020 unsigned RemLatency = 0;
Javed Absar829442a2017-06-21 09:10:10 +00002021 for (SUnit *SU : ReadySUs) {
2022 unsigned L = getUnscheduledLatency(SU);
Andrew Trick2c465a32013-06-15 04:49:44 +00002023 if (L > RemLatency) {
Andrew Trick44fd0bc2012-12-18 20:52:56 +00002024 RemLatency = L;
Javed Absar829442a2017-06-21 09:10:10 +00002025 LateSU = SU;
Andrew Trick2c465a32013-06-15 04:49:44 +00002026 }
Andrew Trick44fd0bc2012-12-18 20:52:56 +00002027 }
Andrew Trickfa989e72013-06-15 05:39:19 +00002028 if (LateSU) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00002029 LLVM_DEBUG(dbgs() << Available.getName() << " RemLatency SU("
2030 << LateSU->NodeNum << ") " << RemLatency << "c\n");
Andrew Trick44fd0bc2012-12-18 20:52:56 +00002031 }
Andrew Trickfa989e72013-06-15 05:39:19 +00002032 return RemLatency;
2033}
Andrew Trick2c465a32013-06-15 04:49:44 +00002034
Andrew Trickfa989e72013-06-15 05:39:19 +00002035// Count resources in this zone and the remaining unscheduled
2036// instruction. Return the max count, scaled. Set OtherCritIdx to the critical
2037// resource index, or zero if the zone is issue limited.
Andrew Trickdcddd712013-12-07 05:59:44 +00002038unsigned SchedBoundary::
Andrew Trickfa989e72013-06-15 05:39:19 +00002039getOtherResourceCount(unsigned &OtherCritIdx) {
Alexey Samsonov86dc6f92013-07-19 08:55:18 +00002040 OtherCritIdx = 0;
Andrew Trickfa989e72013-06-15 05:39:19 +00002041 if (!SchedModel->hasInstrSchedModel())
2042 return 0;
2043
2044 unsigned OtherCritCount = Rem->RemIssueCount
2045 + (RetiredMOps * SchedModel->getMicroOpFactor());
Nicola Zaghen0818e782018-05-14 12:53:11 +00002046 LLVM_DEBUG(dbgs() << " " << Available.getName() << " + Remain MOps: "
2047 << OtherCritCount / SchedModel->getMicroOpFactor() << '\n');
Andrew Trickfa989e72013-06-15 05:39:19 +00002048 for (unsigned PIdx = 1, PEnd = SchedModel->getNumProcResourceKinds();
2049 PIdx != PEnd; ++PIdx) {
2050 unsigned OtherCount = getResourceCount(PIdx) + Rem->RemainingCounts[PIdx];
2051 if (OtherCount > OtherCritCount) {
2052 OtherCritCount = OtherCount;
2053 OtherCritIdx = PIdx;
2054 }
Andrew Trick3b87f622012-11-07 07:05:09 +00002055 }
Andrew Trickfa989e72013-06-15 05:39:19 +00002056 if (OtherCritIdx) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00002057 LLVM_DEBUG(
2058 dbgs() << " " << Available.getName() << " + Remain CritRes: "
2059 << OtherCritCount / SchedModel->getResourceFactor(OtherCritIdx)
2060 << " " << SchedModel->getResourceName(OtherCritIdx) << "\n");
Andrew Trickfa989e72013-06-15 05:39:19 +00002061 }
2062 return OtherCritCount;
2063}
2064
Andrew Trickdcddd712013-12-07 05:59:44 +00002065void SchedBoundary::releaseNode(SUnit *SU, unsigned ReadyCycle) {
Andrew Trick808823c2014-06-07 01:48:43 +00002066 assert(SU->getInstr() && "Scheduled SUnit must have instr");
2067
2068#ifndef NDEBUG
Andrew Trick796f1142014-06-12 22:36:28 +00002069 // ReadyCycle was been bumped up to the CurrCycle when this node was
2070 // scheduled, but CurrCycle may have been eagerly advanced immediately after
2071 // scheduling, so may now be greater than ReadyCycle.
2072 if (ReadyCycle > CurrCycle)
2073 MaxObservedStall = std::max(ReadyCycle - CurrCycle, MaxObservedStall);
Andrew Trick808823c2014-06-07 01:48:43 +00002074#endif
2075
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002076 if (ReadyCycle < MinReadyCycle)
2077 MinReadyCycle = ReadyCycle;
2078
2079 // Check for interlocks first. For the purpose of other heuristics, an
2080 // instruction that cannot issue appears as if it's not in the ReadyQueue.
Andrew Trickfa989e72013-06-15 05:39:19 +00002081 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
Matthias Braun14c17392016-04-22 19:09:17 +00002082 if ((!IsBuffered && ReadyCycle > CurrCycle) || checkHazard(SU) ||
2083 Available.size() >= ReadyListLimit)
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002084 Pending.push(SU);
2085 else
2086 Available.push(SU);
2087}
2088
2089/// Move the boundary of scheduled code by one cycle.
Andrew Trickdcddd712013-12-07 05:59:44 +00002090void SchedBoundary::bumpCycle(unsigned NextCycle) {
Andrew Trickfa989e72013-06-15 05:39:19 +00002091 if (SchedModel->getMicroOpBufferSize() == 0) {
Eugene Zelenko096e40d2017-02-22 22:32:51 +00002092 assert(MinReadyCycle < std::numeric_limits<unsigned>::max() &&
2093 "MinReadyCycle uninitialized");
Andrew Trickfa989e72013-06-15 05:39:19 +00002094 if (MinReadyCycle > NextCycle)
2095 NextCycle = MinReadyCycle;
Andrew Trick3b87f622012-11-07 07:05:09 +00002096 }
Andrew Trickfa989e72013-06-15 05:39:19 +00002097 // Update the current micro-ops, which will issue in the next cycle.
2098 unsigned DecMOps = SchedModel->getIssueWidth() * (NextCycle - CurrCycle);
2099 CurrMOps = (CurrMOps <= DecMOps) ? 0 : CurrMOps - DecMOps;
2100
2101 // Decrement DependentLatency based on the next cycle.
Andrew Trick2c465a32013-06-15 04:49:44 +00002102 if ((NextCycle - CurrCycle) > DependentLatency)
2103 DependentLatency = 0;
2104 else
2105 DependentLatency -= (NextCycle - CurrCycle);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002106
2107 if (!HazardRec->isEnabled()) {
Andrew Trickb7e02892012-06-05 21:11:27 +00002108 // Bypass HazardRec virtual calls.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002109 CurrCycle = NextCycle;
Matthias Braund3962152016-04-21 01:54:13 +00002110 } else {
Andrew Trickb7e02892012-06-05 21:11:27 +00002111 // Bypass getHazardType calls in case of long latency.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002112 for (; CurrCycle != NextCycle; ++CurrCycle) {
2113 if (isTop())
2114 HazardRec->AdvanceCycle();
2115 else
2116 HazardRec->RecedeCycle();
2117 }
2118 }
2119 CheckPending = true;
Andrew Trickfa989e72013-06-15 05:39:19 +00002120 IsResourceLimited =
Jonas Paulsson18622832017-10-25 08:23:33 +00002121 checkResourceLimit(SchedModel->getLatencyFactor(), getCriticalCount(),
2122 getScheduledLatency());
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002123
Nicola Zaghen0818e782018-05-14 12:53:11 +00002124 LLVM_DEBUG(dbgs() << "Cycle: " << CurrCycle << ' ' << Available.getName()
2125 << '\n');
Andrew Trickfa989e72013-06-15 05:39:19 +00002126}
2127
Andrew Trickdcddd712013-12-07 05:59:44 +00002128void SchedBoundary::incExecutedResources(unsigned PIdx, unsigned Count) {
Andrew Trickfa989e72013-06-15 05:39:19 +00002129 ExecutedResCounts[PIdx] += Count;
2130 if (ExecutedResCounts[PIdx] > MaxExecutedResCount)
2131 MaxExecutedResCount = ExecutedResCounts[PIdx];
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002132}
2133
Andrew Trick3b87f622012-11-07 07:05:09 +00002134/// Add the given processor resource to this scheduled zone.
Andrew Trickfa989e72013-06-15 05:39:19 +00002135///
2136/// \param Cycles indicates the number of consecutive (non-pipelined) cycles
2137/// during which this resource is consumed.
2138///
2139/// \return the next cycle at which the instruction may execute without
2140/// oversubscribing resources.
Andrew Trickdcddd712013-12-07 05:59:44 +00002141unsigned SchedBoundary::
Andrew Trick6606ef02013-12-05 17:56:02 +00002142countResource(unsigned PIdx, unsigned Cycles, unsigned NextCycle) {
Andrew Trick3b87f622012-11-07 07:05:09 +00002143 unsigned Factor = SchedModel->getResourceFactor(PIdx);
Andrew Trick3b87f622012-11-07 07:05:09 +00002144 unsigned Count = Factor * Cycles;
Nicola Zaghen0818e782018-05-14 12:53:11 +00002145 LLVM_DEBUG(dbgs() << " " << SchedModel->getResourceName(PIdx) << " +"
2146 << Cycles << "x" << Factor << "u\n");
Andrew Trickfa989e72013-06-15 05:39:19 +00002147
2148 // Update Executed resources counts.
2149 incExecutedResources(PIdx, Count);
Andrew Trick3b87f622012-11-07 07:05:09 +00002150 assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
2151 Rem->RemainingCounts[PIdx] -= Count;
2152
Andrew Trick4e389802013-07-19 00:20:07 +00002153 // Check if this resource exceeds the current critical resource. If so, it
2154 // becomes the critical resource.
2155 if (ZoneCritResIdx != PIdx && (getResourceCount(PIdx) > getCriticalCount())) {
Andrew Trickfa989e72013-06-15 05:39:19 +00002156 ZoneCritResIdx = PIdx;
Nicola Zaghen0818e782018-05-14 12:53:11 +00002157 LLVM_DEBUG(dbgs() << " *** Critical resource "
2158 << SchedModel->getResourceName(PIdx) << ": "
2159 << getResourceCount(PIdx) / SchedModel->getLatencyFactor()
2160 << "c\n");
Andrew Trick3b87f622012-11-07 07:05:09 +00002161 }
Andrew Trick6606ef02013-12-05 17:56:02 +00002162 // For reserved resources, record the highest cycle using the resource.
2163 unsigned NextAvailable = getNextResourceCycle(PIdx, Cycles);
2164 if (NextAvailable > CurrCycle) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00002165 LLVM_DEBUG(dbgs() << " Resource conflict: "
2166 << SchedModel->getProcResource(PIdx)->Name
2167 << " reserved until @" << NextAvailable << "\n");
Andrew Trick6606ef02013-12-05 17:56:02 +00002168 }
2169 return NextAvailable;
Andrew Trick3b87f622012-11-07 07:05:09 +00002170}
2171
Andrew Trickb7e02892012-06-05 21:11:27 +00002172/// Move the boundary of scheduled code by one SUnit.
Andrew Trickdcddd712013-12-07 05:59:44 +00002173void SchedBoundary::bumpNode(SUnit *SU) {
Andrew Trickb7e02892012-06-05 21:11:27 +00002174 // Update the reservation table.
2175 if (HazardRec->isEnabled()) {
2176 if (!isTop() && SU->isCall) {
2177 // Calls are scheduled with their preceding instructions. For bottom-up
2178 // scheduling, clear the pipeline state before emitting.
2179 HazardRec->Reset();
2180 }
2181 HazardRec->EmitInstruction(SU);
2182 }
Andrew Trick6606ef02013-12-05 17:56:02 +00002183 // checkHazard should prevent scheduling multiple instructions per cycle that
2184 // exceed the issue width.
Andrew Trickfa989e72013-06-15 05:39:19 +00002185 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
2186 unsigned IncMOps = SchedModel->getNumMicroOps(SU->getInstr());
Daniel Jasper21c34932013-12-06 08:58:22 +00002187 assert(
2188 (CurrMOps == 0 || (CurrMOps + IncMOps) <= SchedModel->getIssueWidth()) &&
Andrew Trickc0081522013-12-06 17:19:20 +00002189 "Cannot schedule this instruction's MicroOps in the current cycle.");
Andrew Trick6606ef02013-12-05 17:56:02 +00002190
Andrew Trickfa989e72013-06-15 05:39:19 +00002191 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
Nicola Zaghen0818e782018-05-14 12:53:11 +00002192 LLVM_DEBUG(dbgs() << " Ready @" << ReadyCycle << "c\n");
Andrew Trickfa989e72013-06-15 05:39:19 +00002193
Andrew Trick6606ef02013-12-05 17:56:02 +00002194 unsigned NextCycle = CurrCycle;
Andrew Trickfa989e72013-06-15 05:39:19 +00002195 switch (SchedModel->getMicroOpBufferSize()) {
2196 case 0:
2197 assert(ReadyCycle <= CurrCycle && "Broken PendingQueue");
2198 break;
2199 case 1:
2200 if (ReadyCycle > NextCycle) {
2201 NextCycle = ReadyCycle;
Nicola Zaghen0818e782018-05-14 12:53:11 +00002202 LLVM_DEBUG(dbgs() << " *** Stall until: " << ReadyCycle << "\n");
Andrew Trickfa989e72013-06-15 05:39:19 +00002203 }
2204 break;
2205 default:
2206 // We don't currently model the OOO reorder buffer, so consider all
Andrew Trick57393132013-12-05 17:55:58 +00002207 // scheduled MOps to be "retired". We do loosely model in-order resource
2208 // latency. If this instruction uses an in-order resource, account for any
2209 // likely stall cycles.
2210 if (SU->isUnbuffered && ReadyCycle > NextCycle)
2211 NextCycle = ReadyCycle;
Andrew Trickfa989e72013-06-15 05:39:19 +00002212 break;
2213 }
2214 RetiredMOps += IncMOps;
2215
2216 // Update resource counts and critical resource.
2217 if (SchedModel->hasInstrSchedModel()) {
2218 unsigned DecRemIssue = IncMOps * SchedModel->getMicroOpFactor();
2219 assert(Rem->RemIssueCount >= DecRemIssue && "MOps double counted");
2220 Rem->RemIssueCount -= DecRemIssue;
2221 if (ZoneCritResIdx) {
2222 // Scale scheduled micro-ops for comparing with the critical resource.
2223 unsigned ScaledMOps =
2224 RetiredMOps * SchedModel->getMicroOpFactor();
2225
2226 // If scaled micro-ops are now more than the previous critical resource by
2227 // a full cycle, then micro-ops issue becomes critical.
2228 if ((int)(ScaledMOps - getResourceCount(ZoneCritResIdx))
2229 >= (int)SchedModel->getLatencyFactor()) {
2230 ZoneCritResIdx = 0;
Nicola Zaghen0818e782018-05-14 12:53:11 +00002231 LLVM_DEBUG(dbgs() << " *** Critical resource NumMicroOps: "
2232 << ScaledMOps / SchedModel->getLatencyFactor()
2233 << "c\n");
Andrew Trickfa989e72013-06-15 05:39:19 +00002234 }
2235 }
2236 for (TargetSchedModel::ProcResIter
2237 PI = SchedModel->getWriteProcResBegin(SC),
2238 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2239 unsigned RCycle =
Andrew Trick6606ef02013-12-05 17:56:02 +00002240 countResource(PI->ProcResourceIdx, PI->Cycles, NextCycle);
Andrew Trickfa989e72013-06-15 05:39:19 +00002241 if (RCycle > NextCycle)
2242 NextCycle = RCycle;
2243 }
Andrew Trick6606ef02013-12-05 17:56:02 +00002244 if (SU->hasReservedResource) {
2245 // For reserved resources, record the highest cycle using the resource.
2246 // For top-down scheduling, this is the cycle in which we schedule this
2247 // instruction plus the number of cycles the operations reserves the
2248 // resource. For bottom-up is it simply the instruction's cycle.
2249 for (TargetSchedModel::ProcResIter
2250 PI = SchedModel->getWriteProcResBegin(SC),
2251 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2252 unsigned PIdx = PI->ProcResourceIdx;
Andrew Trick9e76e1d2013-12-28 21:56:57 +00002253 if (SchedModel->getProcResource(PIdx)->BufferSize == 0) {
Chad Rosier5ee1c8f2014-07-02 16:46:08 +00002254 if (isTop()) {
2255 ReservedCycles[PIdx] =
2256 std::max(getNextResourceCycle(PIdx, 0), NextCycle + PI->Cycles);
2257 }
2258 else
2259 ReservedCycles[PIdx] = NextCycle;
Andrew Trick9e76e1d2013-12-28 21:56:57 +00002260 }
Andrew Trick6606ef02013-12-05 17:56:02 +00002261 }
2262 }
Andrew Trickfa989e72013-06-15 05:39:19 +00002263 }
2264 // Update ExpectedLatency and DependentLatency.
2265 unsigned &TopLatency = isTop() ? ExpectedLatency : DependentLatency;
2266 unsigned &BotLatency = isTop() ? DependentLatency : ExpectedLatency;
2267 if (SU->getDepth() > TopLatency) {
2268 TopLatency = SU->getDepth();
Nicola Zaghen0818e782018-05-14 12:53:11 +00002269 LLVM_DEBUG(dbgs() << " " << Available.getName() << " TopLatency SU("
2270 << SU->NodeNum << ") " << TopLatency << "c\n");
Andrew Trickfa989e72013-06-15 05:39:19 +00002271 }
2272 if (SU->getHeight() > BotLatency) {
2273 BotLatency = SU->getHeight();
Nicola Zaghen0818e782018-05-14 12:53:11 +00002274 LLVM_DEBUG(dbgs() << " " << Available.getName() << " BotLatency SU("
2275 << SU->NodeNum << ") " << BotLatency << "c\n");
Andrew Trickfa989e72013-06-15 05:39:19 +00002276 }
2277 // If we stall for any reason, bump the cycle.
Jonas Paulsson18622832017-10-25 08:23:33 +00002278 if (NextCycle > CurrCycle)
Andrew Trickfa989e72013-06-15 05:39:19 +00002279 bumpCycle(NextCycle);
Jonas Paulsson18622832017-10-25 08:23:33 +00002280 else
Andrew Trickfa989e72013-06-15 05:39:19 +00002281 // After updating ZoneCritResIdx and ExpectedLatency, check if we're
Alp Tokerae43cab62014-01-24 17:20:08 +00002282 // resource limited. If a stall occurred, bumpCycle does this.
Andrew Trickfa989e72013-06-15 05:39:19 +00002283 IsResourceLimited =
Jonas Paulsson18622832017-10-25 08:23:33 +00002284 checkResourceLimit(SchedModel->getLatencyFactor(), getCriticalCount(),
2285 getScheduledLatency());
2286
Andrew Trick6606ef02013-12-05 17:56:02 +00002287 // Update CurrMOps after calling bumpCycle to handle stalls, since bumpCycle
2288 // resets CurrMOps. Loop to handle instructions with more MOps than issue in
2289 // one cycle. Since we commonly reach the max MOps here, opportunistically
2290 // bump the cycle to avoid uselessly checking everything in the readyQ.
2291 CurrMOps += IncMOps;
Javed Absar47652292017-03-27 20:46:37 +00002292
2293 // Bump the cycle count for issue group constraints.
2294 // This must be done after NextCycle has been adjust for all other stalls.
2295 // Calling bumpCycle(X) will reduce CurrMOps by one issue group and set
2296 // currCycle to X.
2297 if ((isTop() && SchedModel->mustEndGroup(SU->getInstr())) ||
2298 (!isTop() && SchedModel->mustBeginGroup(SU->getInstr()))) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00002299 LLVM_DEBUG(dbgs() << " Bump cycle to " << (isTop() ? "end" : "begin")
2300 << " group\n");
Javed Absar47652292017-03-27 20:46:37 +00002301 bumpCycle(++NextCycle);
2302 }
2303
Andrew Trick6606ef02013-12-05 17:56:02 +00002304 while (CurrMOps >= SchedModel->getIssueWidth()) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00002305 LLVM_DEBUG(dbgs() << " *** Max MOps " << CurrMOps << " at cycle "
2306 << CurrCycle << '\n');
Andrew Trick9e76e1d2013-12-28 21:56:57 +00002307 bumpCycle(++NextCycle);
Andrew Trick6606ef02013-12-05 17:56:02 +00002308 }
Nicola Zaghen0818e782018-05-14 12:53:11 +00002309 LLVM_DEBUG(dumpScheduledState());
Andrew Trickb7e02892012-06-05 21:11:27 +00002310}
2311
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002312/// Release pending ready nodes in to the available queue. This makes them
2313/// visible to heuristics.
Andrew Trickdcddd712013-12-07 05:59:44 +00002314void SchedBoundary::releasePending() {
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002315 // If the available queue is empty, it is safe to reset MinReadyCycle.
2316 if (Available.empty())
Eugene Zelenko096e40d2017-02-22 22:32:51 +00002317 MinReadyCycle = std::numeric_limits<unsigned>::max();
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002318
2319 // Check to see if any of the pending instructions are ready to issue. If
2320 // so, add them to the available queue.
Andrew Trickfa989e72013-06-15 05:39:19 +00002321 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002322 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
2323 SUnit *SU = *(Pending.begin()+i);
Andrew Trickb7e02892012-06-05 21:11:27 +00002324 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002325
2326 if (ReadyCycle < MinReadyCycle)
2327 MinReadyCycle = ReadyCycle;
2328
Andrew Trickfa989e72013-06-15 05:39:19 +00002329 if (!IsBuffered && ReadyCycle > CurrCycle)
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002330 continue;
2331
Andrew Trick5559ffa2012-06-29 03:23:24 +00002332 if (checkHazard(SU))
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002333 continue;
2334
Matthias Braun14c17392016-04-22 19:09:17 +00002335 if (Available.size() >= ReadyListLimit)
2336 break;
2337
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002338 Available.push(SU);
2339 Pending.remove(Pending.begin()+i);
2340 --i; --e;
2341 }
2342 CheckPending = false;
2343}
2344
2345/// Remove SU from the ready set for this boundary.
Andrew Trickdcddd712013-12-07 05:59:44 +00002346void SchedBoundary::removeReady(SUnit *SU) {
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002347 if (Available.isInQueue(SU))
2348 Available.remove(Available.find(SU));
2349 else {
2350 assert(Pending.isInQueue(SU) && "bad ready count");
2351 Pending.remove(Pending.find(SU));
2352 }
2353}
2354
2355/// If this queue only has one ready candidate, return it. As a side effect,
Andrew Trick3b87f622012-11-07 07:05:09 +00002356/// defer any nodes that now hit a hazard, and advance the cycle until at least
2357/// one node is ready. If multiple instructions are ready, return NULL.
Andrew Trickdcddd712013-12-07 05:59:44 +00002358SUnit *SchedBoundary::pickOnlyChoice() {
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002359 if (CheckPending)
2360 releasePending();
2361
Andrew Trickbacb2492013-06-15 04:49:49 +00002362 if (CurrMOps > 0) {
Andrew Trick3b87f622012-11-07 07:05:09 +00002363 // Defer any ready instrs that now have a hazard.
2364 for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
2365 if (checkHazard(*I)) {
2366 Pending.push(*I);
2367 I = Available.remove(I);
2368 continue;
2369 }
2370 ++I;
2371 }
2372 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002373 for (unsigned i = 0; Available.empty(); ++i) {
Chad Rosier5ee1c8f2014-07-02 16:46:08 +00002374// FIXME: Re-enable assert once PR20057 is resolved.
2375// assert(i <= (HazardRec->getMaxLookAhead() + MaxObservedStall) &&
2376// "permanent hazard");
2377 (void)i;
Andrew Trickfa989e72013-06-15 05:39:19 +00002378 bumpCycle(CurrCycle + 1);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002379 releasePending();
2380 }
Matthias Braun680b0dd2016-06-23 21:27:38 +00002381
Nicola Zaghen0818e782018-05-14 12:53:11 +00002382 LLVM_DEBUG(Pending.dump());
2383 LLVM_DEBUG(Available.dump());
Matthias Braun680b0dd2016-06-23 21:27:38 +00002384
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002385 if (Available.size() == 1)
2386 return *Available.begin();
Craig Topper4ba84432014-04-14 00:51:57 +00002387 return nullptr;
Andrew Trick0a39d4e2012-05-24 22:11:09 +00002388}
2389
Aaron Ballman1d03d382017-10-15 14:32:27 +00002390#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Andrew Trickfa989e72013-06-15 05:39:19 +00002391// This is useful information to dump after bumpNode.
2392// Note that the Queue contents are more useful before pickNodeFromQueue.
Sam Cleggb2092062017-06-21 22:19:17 +00002393LLVM_DUMP_METHOD void SchedBoundary::dumpScheduledState() const {
Andrew Trickfa989e72013-06-15 05:39:19 +00002394 unsigned ResFactor;
2395 unsigned ResCount;
2396 if (ZoneCritResIdx) {
2397 ResFactor = SchedModel->getResourceFactor(ZoneCritResIdx);
2398 ResCount = getResourceCount(ZoneCritResIdx);
Matthias Braund3962152016-04-21 01:54:13 +00002399 } else {
Andrew Trickfa989e72013-06-15 05:39:19 +00002400 ResFactor = SchedModel->getMicroOpFactor();
Javed Absardccccce2017-09-27 10:31:58 +00002401 ResCount = RetiredMOps * ResFactor;
Andrew Trick3b87f622012-11-07 07:05:09 +00002402 }
Andrew Trickfa989e72013-06-15 05:39:19 +00002403 unsigned LFactor = SchedModel->getLatencyFactor();
2404 dbgs() << Available.getName() << " @" << CurrCycle << "c\n"
2405 << " Retired: " << RetiredMOps;
2406 dbgs() << "\n Executed: " << getExecutedCount() / LFactor << "c";
2407 dbgs() << "\n Critical: " << ResCount / LFactor << "c, "
Andrew Trickdcddd712013-12-07 05:59:44 +00002408 << ResCount / ResFactor << " "
2409 << SchedModel->getResourceName(ZoneCritResIdx)
Andrew Trickfa989e72013-06-15 05:39:19 +00002410 << "\n ExpectedLatency: " << ExpectedLatency << "c\n"
2411 << (IsResourceLimited ? " - Resource" : " - Latency")
2412 << " limited.\n";
Andrew Trick3b87f622012-11-07 07:05:09 +00002413}
Andrew Trickaaaae512013-06-15 05:46:47 +00002414#endif
Andrew Trick3b87f622012-11-07 07:05:09 +00002415
Andrew Trickdcddd712013-12-07 05:59:44 +00002416//===----------------------------------------------------------------------===//
Andrew Trick9e76e1d2013-12-28 21:56:57 +00002417// GenericScheduler - Generic implementation of MachineSchedStrategy.
Andrew Trickdcddd712013-12-07 05:59:44 +00002418//===----------------------------------------------------------------------===//
2419
Andrew Trick9e76e1d2013-12-28 21:56:57 +00002420void GenericSchedulerBase::SchedCandidate::
2421initResourceDelta(const ScheduleDAGMI *DAG,
2422 const TargetSchedModel *SchedModel) {
2423 if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
2424 return;
2425
2426 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
2427 for (TargetSchedModel::ProcResIter
2428 PI = SchedModel->getWriteProcResBegin(SC),
2429 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2430 if (PI->ProcResourceIdx == Policy.ReduceResIdx)
2431 ResDelta.CritResources += PI->Cycles;
2432 if (PI->ProcResourceIdx == Policy.DemandResIdx)
2433 ResDelta.DemandedResources += PI->Cycles;
2434 }
2435}
2436
Tom Stellard486f7d62018-08-21 21:48:43 +00002437/// Compute remaining latency. We need this both to determine whether the
2438/// overall schedule has become latency-limited and whether the instructions
2439/// outside this zone are resource or latency limited.
2440///
2441/// The "dependent" latency is updated incrementally during scheduling as the
2442/// max height/depth of scheduled nodes minus the cycles since it was
2443/// scheduled:
2444/// DLat = max (N.depth - (CurrCycle - N.ReadyCycle) for N in Zone
2445///
2446/// The "independent" latency is the max ready queue depth:
2447/// ILat = max N.depth for N in Available|Pending
2448///
2449/// RemainingLatency is the greater of independent and dependent latency.
2450///
2451/// These computations are expensive, especially in DAGs with many edges, so
2452/// only do them if necessary.
2453static unsigned computeRemLatency(SchedBoundary &CurrZone) {
2454 unsigned RemLatency = CurrZone.getDependentLatency();
2455 RemLatency = std::max(RemLatency,
2456 CurrZone.findMaxLatency(CurrZone.Available.elements()));
2457 RemLatency = std::max(RemLatency,
2458 CurrZone.findMaxLatency(CurrZone.Pending.elements()));
2459 return RemLatency;
2460}
2461
2462/// Returns true if the current cycle plus remaning latency is greater than
Hiroshi Inoue7a9527e2019-01-09 05:11:10 +00002463/// the critical path in the scheduling region.
Tom Stellard486f7d62018-08-21 21:48:43 +00002464bool GenericSchedulerBase::shouldReduceLatency(const CandPolicy &Policy,
2465 SchedBoundary &CurrZone,
2466 bool ComputeRemLatency,
2467 unsigned &RemLatency) const {
2468 // The current cycle is already greater than the critical path, so we are
Hiroshi Inoue7a9527e2019-01-09 05:11:10 +00002469 // already latency limited and don't need to compute the remaining latency.
Tom Stellard486f7d62018-08-21 21:48:43 +00002470 if (CurrZone.getCurrCycle() > Rem.CriticalPath)
2471 return true;
2472
2473 // If we haven't scheduled anything yet, then we aren't latency limited.
2474 if (CurrZone.getCurrCycle() == 0)
2475 return false;
2476
2477 if (ComputeRemLatency)
2478 RemLatency = computeRemLatency(CurrZone);
2479
2480 return RemLatency + CurrZone.getCurrCycle() > Rem.CriticalPath;
2481}
2482
Andrew Trick9e76e1d2013-12-28 21:56:57 +00002483/// Set the CandPolicy given a scheduling zone given the current resources and
2484/// latencies inside and outside the zone.
Matthias Braund3962152016-04-21 01:54:13 +00002485void GenericSchedulerBase::setPolicy(CandPolicy &Policy, bool IsPostRA,
Andrew Trick9e76e1d2013-12-28 21:56:57 +00002486 SchedBoundary &CurrZone,
2487 SchedBoundary *OtherZone) {
Eric Christopher933d2bd2015-06-19 01:53:21 +00002488 // Apply preemptive heuristics based on the total latency and resources
Andrew Trick9e76e1d2013-12-28 21:56:57 +00002489 // inside and outside this zone. Potential stalls should be considered before
2490 // following this policy.
2491
Andrew Trick9e76e1d2013-12-28 21:56:57 +00002492 // Compute the critical resource outside the zone.
Andrew Trick7d1a69d2013-12-28 22:25:57 +00002493 unsigned OtherCritIdx = 0;
Andrew Trick9e76e1d2013-12-28 21:56:57 +00002494 unsigned OtherCount =
2495 OtherZone ? OtherZone->getOtherResourceCount(OtherCritIdx) : 0;
2496
2497 bool OtherResLimited = false;
Tom Stellard486f7d62018-08-21 21:48:43 +00002498 unsigned RemLatency = 0;
2499 bool RemLatencyComputed = false;
2500 if (SchedModel->hasInstrSchedModel() && OtherCount != 0) {
2501 RemLatency = computeRemLatency(CurrZone);
2502 RemLatencyComputed = true;
Jonas Paulsson18622832017-10-25 08:23:33 +00002503 OtherResLimited = checkResourceLimit(SchedModel->getLatencyFactor(),
2504 OtherCount, RemLatency);
Tom Stellard486f7d62018-08-21 21:48:43 +00002505 }
Jonas Paulsson18622832017-10-25 08:23:33 +00002506
Andrew Trick9e76e1d2013-12-28 21:56:57 +00002507 // Schedule aggressively for latency in PostRA mode. We don't check for
2508 // acyclic latency during PostRA, and highly out-of-order processors will
2509 // skip PostRA scheduling.
Tom Stellard486f7d62018-08-21 21:48:43 +00002510 if (!OtherResLimited &&
2511 (IsPostRA || shouldReduceLatency(Policy, CurrZone, !RemLatencyComputed,
2512 RemLatency))) {
2513 Policy.ReduceLatency |= true;
2514 LLVM_DEBUG(dbgs() << " " << CurrZone.Available.getName()
2515 << " RemainingLatency " << RemLatency << " + "
2516 << CurrZone.getCurrCycle() << "c > CritPath "
2517 << Rem.CriticalPath << "\n");
Andrew Trick9e76e1d2013-12-28 21:56:57 +00002518 }
2519 // If the same resource is limiting inside and outside the zone, do nothing.
2520 if (CurrZone.getZoneCritResIdx() == OtherCritIdx)
2521 return;
2522
Nicola Zaghen0818e782018-05-14 12:53:11 +00002523 LLVM_DEBUG(if (CurrZone.isResourceLimited()) {
2524 dbgs() << " " << CurrZone.Available.getName() << " ResourceLimited: "
2525 << SchedModel->getResourceName(CurrZone.getZoneCritResIdx()) << "\n";
2526 } if (OtherResLimited) dbgs()
2527 << " RemainingLimit: "
2528 << SchedModel->getResourceName(OtherCritIdx) << "\n";
2529 if (!CurrZone.isResourceLimited() && !OtherResLimited) dbgs()
2530 << " Latency limited both directions.\n");
Andrew Trick9e76e1d2013-12-28 21:56:57 +00002531
2532 if (CurrZone.isResourceLimited() && !Policy.ReduceResIdx)
2533 Policy.ReduceResIdx = CurrZone.getZoneCritResIdx();
2534
2535 if (OtherResLimited)
2536 Policy.DemandResIdx = OtherCritIdx;
2537}
2538
2539#ifndef NDEBUG
2540const char *GenericSchedulerBase::getReasonStr(
2541 GenericSchedulerBase::CandReason Reason) {
2542 switch (Reason) {
2543 case NoCand: return "NOCAND ";
Matthias Brauna827bf12016-05-27 22:14:26 +00002544 case Only1: return "ONLY1 ";
Nirav Davec8c80b02018-11-14 21:11:53 +00002545 case PhysReg: return "PHYS-REG ";
Andrew Trick9e76e1d2013-12-28 21:56:57 +00002546 case RegExcess: return "REG-EXCESS";
2547 case RegCritical: return "REG-CRIT ";
2548 case Stall: return "STALL ";
2549 case Cluster: return "CLUSTER ";
2550 case Weak: return "WEAK ";
2551 case RegMax: return "REG-MAX ";
2552 case ResourceReduce: return "RES-REDUCE";
2553 case ResourceDemand: return "RES-DEMAND";
2554 case TopDepthReduce: return "TOP-DEPTH ";
2555 case TopPathReduce: return "TOP-PATH ";
2556 case BotHeightReduce:return "BOT-HEIGHT";
2557 case BotPathReduce: return "BOT-PATH ";
2558 case NextDefUse: return "DEF-USE ";
2559 case NodeOrder: return "ORDER ";
2560 };
2561 llvm_unreachable("Unknown reason!");
2562}
2563
2564void GenericSchedulerBase::traceCandidate(const SchedCandidate &Cand) {
2565 PressureChange P;
2566 unsigned ResIdx = 0;
2567 unsigned Latency = 0;
2568 switch (Cand.Reason) {
2569 default:
2570 break;
2571 case RegExcess:
2572 P = Cand.RPDelta.Excess;
2573 break;
2574 case RegCritical:
2575 P = Cand.RPDelta.CriticalMax;
2576 break;
2577 case RegMax:
2578 P = Cand.RPDelta.CurrentMax;
2579 break;
2580 case ResourceReduce:
2581 ResIdx = Cand.Policy.ReduceResIdx;
2582 break;
2583 case ResourceDemand:
2584 ResIdx = Cand.Policy.DemandResIdx;
2585 break;
2586 case TopDepthReduce:
2587 Latency = Cand.SU->getDepth();
2588 break;
2589 case TopPathReduce:
2590 Latency = Cand.SU->getHeight();
2591 break;
2592 case BotHeightReduce:
2593 Latency = Cand.SU->getHeight();
2594 break;
2595 case BotPathReduce:
2596 Latency = Cand.SU->getDepth();
2597 break;
2598 }
James Y Knightdc18fbb2015-09-18 18:52:20 +00002599 dbgs() << " Cand SU(" << Cand.SU->NodeNum << ") " << getReasonStr(Cand.Reason);
Andrew Trick9e76e1d2013-12-28 21:56:57 +00002600 if (P.isValid())
2601 dbgs() << " " << TRI->getRegPressureSetName(P.getPSet())
2602 << ":" << P.getUnitInc() << " ";
2603 else
2604 dbgs() << " ";
2605 if (ResIdx)
2606 dbgs() << " " << SchedModel->getProcResource(ResIdx)->Name << " ";
2607 else
2608 dbgs() << " ";
2609 if (Latency)
2610 dbgs() << " " << Latency << " cycles ";
2611 else
2612 dbgs() << " ";
2613 dbgs() << '\n';
2614}
2615#endif
2616
Jonas Paulssona83aa7c2018-04-12 07:21:39 +00002617namespace llvm {
Andrew Trick9e76e1d2013-12-28 21:56:57 +00002618/// Return true if this heuristic determines order.
Jonas Paulssona83aa7c2018-04-12 07:21:39 +00002619bool tryLess(int TryVal, int CandVal,
2620 GenericSchedulerBase::SchedCandidate &TryCand,
2621 GenericSchedulerBase::SchedCandidate &Cand,
2622 GenericSchedulerBase::CandReason Reason) {
Andrew Trick9e76e1d2013-12-28 21:56:57 +00002623 if (TryVal < CandVal) {
2624 TryCand.Reason = Reason;
2625 return true;
2626 }
2627 if (TryVal > CandVal) {
2628 if (Cand.Reason > Reason)
2629 Cand.Reason = Reason;
2630 return true;
2631 }
Andrew Trick9e76e1d2013-12-28 21:56:57 +00002632 return false;
2633}
2634
Jonas Paulssona83aa7c2018-04-12 07:21:39 +00002635bool tryGreater(int TryVal, int CandVal,
2636 GenericSchedulerBase::SchedCandidate &TryCand,
2637 GenericSchedulerBase::SchedCandidate &Cand,
2638 GenericSchedulerBase::CandReason Reason) {
Andrew Trick9e76e1d2013-12-28 21:56:57 +00002639 if (TryVal > CandVal) {
2640 TryCand.Reason = Reason;
2641 return true;
2642 }
2643 if (TryVal < CandVal) {
2644 if (Cand.Reason > Reason)
2645 Cand.Reason = Reason;
2646 return true;
2647 }
Andrew Trick9e76e1d2013-12-28 21:56:57 +00002648 return false;
2649}
2650
Jonas Paulssona83aa7c2018-04-12 07:21:39 +00002651bool tryLatency(GenericSchedulerBase::SchedCandidate &TryCand,
2652 GenericSchedulerBase::SchedCandidate &Cand,
2653 SchedBoundary &Zone) {
Andrew Trick9e76e1d2013-12-28 21:56:57 +00002654 if (Zone.isTop()) {
2655 if (Cand.SU->getDepth() > Zone.getScheduledLatency()) {
2656 if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2657 TryCand, Cand, GenericSchedulerBase::TopDepthReduce))
2658 return true;
2659 }
2660 if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2661 TryCand, Cand, GenericSchedulerBase::TopPathReduce))
2662 return true;
Matthias Braund3962152016-04-21 01:54:13 +00002663 } else {
Andrew Trick9e76e1d2013-12-28 21:56:57 +00002664 if (Cand.SU->getHeight() > Zone.getScheduledLatency()) {
2665 if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2666 TryCand, Cand, GenericSchedulerBase::BotHeightReduce))
2667 return true;
2668 }
2669 if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2670 TryCand, Cand, GenericSchedulerBase::BotPathReduce))
2671 return true;
2672 }
2673 return false;
2674}
Jonas Paulssona83aa7c2018-04-12 07:21:39 +00002675} // end namespace llvm
Andrew Trick9e76e1d2013-12-28 21:56:57 +00002676
Matthias Brauna827bf12016-05-27 22:14:26 +00002677static void tracePick(GenericSchedulerBase::CandReason Reason, bool IsTop) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00002678 LLVM_DEBUG(dbgs() << "Pick " << (IsTop ? "Top " : "Bot ")
2679 << GenericSchedulerBase::getReasonStr(Reason) << '\n');
Matthias Brauna827bf12016-05-27 22:14:26 +00002680}
2681
Matthias Braunf011e372016-06-25 00:23:00 +00002682static void tracePick(const GenericSchedulerBase::SchedCandidate &Cand) {
2683 tracePick(Cand.Reason, Cand.AtTop);
Andrew Trick9e76e1d2013-12-28 21:56:57 +00002684}
2685
Andrew Trickdcddd712013-12-07 05:59:44 +00002686void GenericScheduler::initialize(ScheduleDAGMI *dag) {
Andrew Tricka38b0de2013-12-28 21:56:47 +00002687 assert(dag->hasVRegLiveness() &&
2688 "(PreRA)GenericScheduler needs vreg liveness");
2689 DAG = static_cast<ScheduleDAGMILive*>(dag);
Andrew Trickdcddd712013-12-07 05:59:44 +00002690 SchedModel = DAG->getSchedModel();
2691 TRI = DAG->TRI;
2692
2693 Rem.init(DAG, SchedModel);
2694 Top.init(DAG, SchedModel, &Rem);
2695 Bot.init(DAG, SchedModel, &Rem);
2696
2697 // Initialize resource counts.
2698
2699 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
2700 // are disabled, then these HazardRecs will be disabled.
2701 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
Andrew Trickdcddd712013-12-07 05:59:44 +00002702 if (!Top.HazardRec) {
2703 Top.HazardRec =
Eric Christophercd694812014-10-14 06:56:25 +00002704 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
Eric Christopher9f85dcc2014-08-04 21:25:23 +00002705 Itin, DAG);
Andrew Trickdcddd712013-12-07 05:59:44 +00002706 }
2707 if (!Bot.HazardRec) {
2708 Bot.HazardRec =
Eric Christophercd694812014-10-14 06:56:25 +00002709 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
Eric Christopher9f85dcc2014-08-04 21:25:23 +00002710 Itin, DAG);
Andrew Trickdcddd712013-12-07 05:59:44 +00002711 }
Matthias Braun2feb69e2016-06-25 02:03:36 +00002712 TopCand.SU = nullptr;
2713 BotCand.SU = nullptr;
Andrew Trickdcddd712013-12-07 05:59:44 +00002714}
2715
2716/// Initialize the per-region scheduling policy.
2717void GenericScheduler::initPolicy(MachineBasicBlock::iterator Begin,
2718 MachineBasicBlock::iterator End,
2719 unsigned NumRegionInstrs) {
Justin Bogner1842f4a2017-10-10 23:50:49 +00002720 const MachineFunction &MF = *Begin->getMF();
Eric Christophercd694812014-10-14 06:56:25 +00002721 const TargetLowering *TLI = MF.getSubtarget().getTargetLowering();
Andrew Trickdcddd712013-12-07 05:59:44 +00002722
2723 // Avoid setting up the register pressure tracker for small regions to save
2724 // compile time. As a rough heuristic, only track pressure when the number of
2725 // schedulable instructions exceeds half the integer register file.
Andrew Trick10afb022014-01-21 21:27:37 +00002726 RegionPolicy.ShouldTrackPressure = true;
Andrew Trick0c1b9ec2014-01-22 03:38:55 +00002727 for (unsigned VT = MVT::i32; VT > (unsigned)MVT::i1; --VT) {
2728 MVT::SimpleValueType LegalIntVT = (MVT::SimpleValueType)VT;
2729 if (TLI->isTypeLegal(LegalIntVT)) {
Andrew Trick10afb022014-01-21 21:27:37 +00002730 unsigned NIntRegs = Context->RegClassInfo->getNumAllocatableRegs(
Andrew Trick0c1b9ec2014-01-22 03:38:55 +00002731 TLI->getRegClassFor(LegalIntVT));
Andrew Trick10afb022014-01-21 21:27:37 +00002732 RegionPolicy.ShouldTrackPressure = NumRegionInstrs > (NIntRegs / 2);
2733 }
2734 }
Andrew Trickdcddd712013-12-07 05:59:44 +00002735
2736 // For generic targets, we default to bottom-up, because it's simpler and more
2737 // compile-time optimizations have been implemented in that direction.
2738 RegionPolicy.OnlyBottomUp = true;
2739
2740 // Allow the subtarget to override default policy.
Duncan P. N. Exon Smitha354e212016-07-01 00:23:27 +00002741 MF.getSubtarget().overrideSchedPolicy(RegionPolicy, NumRegionInstrs);
Andrew Trickdcddd712013-12-07 05:59:44 +00002742
2743 // After subtarget overrides, apply command line options.
2744 if (!EnableRegPressure)
2745 RegionPolicy.ShouldTrackPressure = false;
2746
2747 // Check -misched-topdown/bottomup can force or unforce scheduling direction.
2748 // e.g. -misched-bottomup=false allows scheduling in both directions.
2749 assert((!ForceTopDown || !ForceBottomUp) &&
2750 "-misched-topdown incompatible with -misched-bottomup");
2751 if (ForceBottomUp.getNumOccurrences() > 0) {
2752 RegionPolicy.OnlyBottomUp = ForceBottomUp;
2753 if (RegionPolicy.OnlyBottomUp)
2754 RegionPolicy.OnlyTopDown = false;
2755 }
2756 if (ForceTopDown.getNumOccurrences() > 0) {
2757 RegionPolicy.OnlyTopDown = ForceTopDown;
2758 if (RegionPolicy.OnlyTopDown)
2759 RegionPolicy.OnlyBottomUp = false;
2760 }
2761}
2762
Sam Cleggb2092062017-06-21 22:19:17 +00002763void GenericScheduler::dumpPolicy() const {
Matthias Braun88d20752017-01-28 02:02:38 +00002764 // Cannot completely remove virtual function even in release mode.
Aaron Ballman1d03d382017-10-15 14:32:27 +00002765#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
James Y Knightdc18fbb2015-09-18 18:52:20 +00002766 dbgs() << "GenericScheduler RegionPolicy: "
2767 << " ShouldTrackPressure=" << RegionPolicy.ShouldTrackPressure
2768 << " OnlyTopDown=" << RegionPolicy.OnlyTopDown
2769 << " OnlyBottomUp=" << RegionPolicy.OnlyBottomUp
2770 << "\n";
Matthias Braun88d20752017-01-28 02:02:38 +00002771#endif
James Y Knightdc18fbb2015-09-18 18:52:20 +00002772}
2773
Andrew Trickdcddd712013-12-07 05:59:44 +00002774/// Set IsAcyclicLatencyLimited if the acyclic path is longer than the cyclic
2775/// critical path by more cycles than it takes to drain the instruction buffer.
2776/// We estimate an upper bounds on in-flight instructions as:
2777///
2778/// CyclesPerIteration = max( CyclicPath, Loop-Resource-Height )
2779/// InFlightIterations = AcyclicPath / CyclesPerIteration
2780/// InFlightResources = InFlightIterations * LoopResources
2781///
2782/// TODO: Check execution resources in addition to IssueCount.
2783void GenericScheduler::checkAcyclicLatency() {
2784 if (Rem.CyclicCritPath == 0 || Rem.CyclicCritPath >= Rem.CriticalPath)
2785 return;
2786
2787 // Scaled number of cycles per loop iteration.
2788 unsigned IterCount =
2789 std::max(Rem.CyclicCritPath * SchedModel->getLatencyFactor(),
2790 Rem.RemIssueCount);
2791 // Scaled acyclic critical path.
2792 unsigned AcyclicCount = Rem.CriticalPath * SchedModel->getLatencyFactor();
2793 // InFlightCount = (AcyclicPath / IterCycles) * InstrPerLoop
2794 unsigned InFlightCount =
2795 (AcyclicCount * Rem.RemIssueCount + IterCount-1) / IterCount;
2796 unsigned BufferLimit =
2797 SchedModel->getMicroOpBufferSize() * SchedModel->getMicroOpFactor();
2798
2799 Rem.IsAcyclicLatencyLimited = InFlightCount > BufferLimit;
2800
Nicola Zaghen0818e782018-05-14 12:53:11 +00002801 LLVM_DEBUG(
2802 dbgs() << "IssueCycles="
2803 << Rem.RemIssueCount / SchedModel->getLatencyFactor() << "c "
2804 << "IterCycles=" << IterCount / SchedModel->getLatencyFactor()
2805 << "c NumIters=" << (AcyclicCount + IterCount - 1) / IterCount
2806 << " InFlight=" << InFlightCount / SchedModel->getMicroOpFactor()
2807 << "m BufferLim=" << SchedModel->getMicroOpBufferSize() << "m\n";
2808 if (Rem.IsAcyclicLatencyLimited) dbgs() << " ACYCLIC LATENCY LIMIT\n");
Andrew Trickdcddd712013-12-07 05:59:44 +00002809}
2810
2811void GenericScheduler::registerRoots() {
2812 Rem.CriticalPath = DAG->ExitSU.getDepth();
2813
2814 // Some roots may not feed into ExitSU. Check all of them in case.
Javed Absar829442a2017-06-21 09:10:10 +00002815 for (const SUnit *SU : Bot.Available) {
2816 if (SU->getDepth() > Rem.CriticalPath)
2817 Rem.CriticalPath = SU->getDepth();
Andrew Trickdcddd712013-12-07 05:59:44 +00002818 }
Nicola Zaghen0818e782018-05-14 12:53:11 +00002819 LLVM_DEBUG(dbgs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << '\n');
Gerolf Hoflehner9fbb0122014-08-07 21:49:44 +00002820 if (DumpCriticalPathLength) {
2821 errs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << " \n";
2822 }
Andrew Trickdcddd712013-12-07 05:59:44 +00002823
Matthias Braun6b814342017-04-12 18:09:05 +00002824 if (EnableCyclicPath && SchedModel->getMicroOpBufferSize() > 0) {
Andrew Trickdcddd712013-12-07 05:59:44 +00002825 Rem.CyclicCritPath = DAG->computeCyclicCriticalPath();
2826 checkAcyclicLatency();
2827 }
2828}
2829
Jonas Paulssona83aa7c2018-04-12 07:21:39 +00002830namespace llvm {
2831bool tryPressure(const PressureChange &TryP,
2832 const PressureChange &CandP,
2833 GenericSchedulerBase::SchedCandidate &TryCand,
2834 GenericSchedulerBase::SchedCandidate &Cand,
2835 GenericSchedulerBase::CandReason Reason,
2836 const TargetRegisterInfo *TRI,
2837 const MachineFunction &MF) {
Andrew Trickda6fc152013-08-30 04:27:29 +00002838 // If one candidate decreases and the other increases, go with it.
2839 // Invalid candidates have UnitInc==0.
Hal Finkeld3aa46a2014-10-10 17:06:20 +00002840 if (tryGreater(TryP.getUnitInc() < 0, CandP.getUnitInc() < 0, TryCand, Cand,
2841 Reason)) {
Andrew Trickda6fc152013-08-30 04:27:29 +00002842 return true;
2843 }
Matthias Braunf011e372016-06-25 00:23:00 +00002844 // Do not compare the magnitude of pressure changes between top and bottom
2845 // boundary.
2846 if (Cand.AtTop != TryCand.AtTop)
2847 return false;
2848
2849 // If both candidates affect the same set in the same boundary, go with the
2850 // smallest increase.
2851 unsigned TryPSet = TryP.getPSetOrMax();
2852 unsigned CandPSet = CandP.getPSetOrMax();
2853 if (TryPSet == CandPSet) {
2854 return tryLess(TryP.getUnitInc(), CandP.getUnitInc(), TryCand, Cand,
2855 Reason);
2856 }
Tom Stellard8b135102015-12-16 18:31:01 +00002857
2858 int TryRank = TryP.isValid() ? TRI->getRegPressureSetScore(MF, TryPSet) :
2859 std::numeric_limits<int>::max();
2860
2861 int CandRank = CandP.isValid() ? TRI->getRegPressureSetScore(MF, CandPSet) :
2862 std::numeric_limits<int>::max();
2863
Andrew Trick13372882013-07-25 07:26:35 +00002864 // If the candidates are decreasing pressure, reverse priority.
Andrew Trick4c60b8a2013-08-30 03:49:48 +00002865 if (TryP.getUnitInc() < 0)
Andrew Trick13372882013-07-25 07:26:35 +00002866 std::swap(TryRank, CandRank);
2867 return tryGreater(TryRank, CandRank, TryCand, Cand, Reason);
2868}
2869
Jonas Paulssona83aa7c2018-04-12 07:21:39 +00002870unsigned getWeakLeft(const SUnit *SU, bool isTop) {
Andrew Trick9b5caaa2012-11-12 19:40:10 +00002871 return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
2872}
2873
Andrew Trick4392f0f2013-04-13 06:07:40 +00002874/// Minimize physical register live ranges. Regalloc wants them adjacent to
2875/// their physreg def/use.
2876///
2877/// FIXME: This is an unnecessary check on the critical path. Most are root/leaf
2878/// copies which can be prescheduled. The rest (e.g. x86 MUL) could be bundled
2879/// with the operation that produces or consumes the physreg. We'll do this when
2880/// regalloc has support for parallel copies.
Nirav Davec8c80b02018-11-14 21:11:53 +00002881int biasPhysReg(const SUnit *SU, bool isTop) {
Andrew Trick4392f0f2013-04-13 06:07:40 +00002882 const MachineInstr *MI = SU->getInstr();
Andrew Trick4392f0f2013-04-13 06:07:40 +00002883
Nirav Davec8c80b02018-11-14 21:11:53 +00002884 if (MI->isCopy()) {
2885 unsigned ScheduledOper = isTop ? 1 : 0;
2886 unsigned UnscheduledOper = isTop ? 0 : 1;
2887 // If we have already scheduled the physreg produce/consumer, immediately
2888 // schedule the copy.
2889 if (TargetRegisterInfo::isPhysicalRegister(
2890 MI->getOperand(ScheduledOper).getReg()))
2891 return 1;
2892 // If the physreg is at the boundary, defer it. Otherwise schedule it
2893 // immediately to free the dependent. We can hoist the copy later.
2894 bool AtBoundary = isTop ? !SU->NumSuccsLeft : !SU->NumPredsLeft;
2895 if (TargetRegisterInfo::isPhysicalRegister(
2896 MI->getOperand(UnscheduledOper).getReg()))
2897 return AtBoundary ? -1 : 1;
2898 }
2899
2900 if (MI->isMoveImmediate()) {
2901 // If we have a move immediate and all successors have been assigned, bias
2902 // towards scheduling this later. Make sure all register defs are to
2903 // physical registers.
2904 bool DoBias = true;
2905 for (const MachineOperand &Op : MI->defs()) {
2906 if (Op.isReg() && !TargetRegisterInfo::isPhysicalRegister(Op.getReg())) {
2907 DoBias = false;
2908 break;
2909 }
2910 }
2911
2912 if (DoBias)
2913 return isTop ? -1 : 1;
2914 }
2915
Andrew Trick4392f0f2013-04-13 06:07:40 +00002916 return 0;
2917}
Jonas Paulssona83aa7c2018-04-12 07:21:39 +00002918} // end namespace llvm
Andrew Trick4392f0f2013-04-13 06:07:40 +00002919
Matthias Braunbc2216c2016-04-22 19:10:15 +00002920void GenericScheduler::initCandidate(SchedCandidate &Cand, SUnit *SU,
2921 bool AtTop,
2922 const RegPressureTracker &RPTracker,
2923 RegPressureTracker &TempTracker) {
2924 Cand.SU = SU;
Matthias Braunf011e372016-06-25 00:23:00 +00002925 Cand.AtTop = AtTop;
Matthias Braunbc2216c2016-04-22 19:10:15 +00002926 if (DAG->isTrackingPressure()) {
2927 if (AtTop) {
2928 TempTracker.getMaxDownwardPressureDelta(
2929 Cand.SU->getInstr(),
2930 Cand.RPDelta,
2931 DAG->getRegionCriticalPSets(),
2932 DAG->getRegPressure().MaxSetPressure);
2933 } else {
2934 if (VerifyScheduling) {
2935 TempTracker.getMaxUpwardPressureDelta(
2936 Cand.SU->getInstr(),
2937 &DAG->getPressureDiff(Cand.SU),
2938 Cand.RPDelta,
2939 DAG->getRegionCriticalPSets(),
2940 DAG->getRegPressure().MaxSetPressure);
2941 } else {
2942 RPTracker.getUpwardPressureDelta(
2943 Cand.SU->getInstr(),
2944 DAG->getPressureDiff(Cand.SU),
2945 Cand.RPDelta,
2946 DAG->getRegionCriticalPSets(),
2947 DAG->getRegPressure().MaxSetPressure);
2948 }
2949 }
2950 }
Nicola Zaghen0818e782018-05-14 12:53:11 +00002951 LLVM_DEBUG(if (Cand.RPDelta.Excess.isValid()) dbgs()
2952 << " Try SU(" << Cand.SU->NodeNum << ") "
2953 << TRI->getRegPressureSetName(Cand.RPDelta.Excess.getPSet()) << ":"
2954 << Cand.RPDelta.Excess.getUnitInc() << "\n");
Matthias Braunbc2216c2016-04-22 19:10:15 +00002955}
2956
Hiroshi Inoue73d058a2018-06-20 05:29:26 +00002957/// Apply a set of heuristics to a new candidate. Heuristics are currently
Andrew Trick3b87f622012-11-07 07:05:09 +00002958/// hierarchical. This may be more efficient than a graduated cost model because
2959/// we don't need to evaluate all aspects of the model for each node in the
2960/// queue. But it's really done to make the heuristics easier to debug and
2961/// statistically analyze.
2962///
2963/// \param Cand provides the policy and current best candidate.
2964/// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
Matthias Braunf011e372016-06-25 00:23:00 +00002965/// \param Zone describes the scheduled zone that we are extending, or nullptr
2966// if Cand is from a different zone than TryCand.
Andrew Trick70e0b042013-09-19 23:10:59 +00002967void GenericScheduler::tryCandidate(SchedCandidate &Cand,
Andrew Trick0591e2a2013-12-05 17:55:47 +00002968 SchedCandidate &TryCand,
Jonas Paulssona83aa7c2018-04-12 07:21:39 +00002969 SchedBoundary *Zone) const {
Andrew Trick3b87f622012-11-07 07:05:09 +00002970 // Initialize the candidate if needed.
2971 if (!Cand.isValid()) {
2972 TryCand.Reason = NodeOrder;
2973 return;
2974 }
Andrew Trick4392f0f2013-04-13 06:07:40 +00002975
Nirav Davec8c80b02018-11-14 21:11:53 +00002976 // Bias PhysReg Defs and copies to their uses and defined respectively.
2977 if (tryGreater(biasPhysReg(TryCand.SU, TryCand.AtTop),
2978 biasPhysReg(Cand.SU, Cand.AtTop), TryCand, Cand, PhysReg))
Andrew Trick4392f0f2013-04-13 06:07:40 +00002979 return;
2980
Andrew Trickeddedaa2015-05-17 23:40:27 +00002981 // Avoid exceeding the target's limit.
Andrew Trick16bb45c2013-09-04 21:00:11 +00002982 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.Excess,
2983 Cand.RPDelta.Excess,
Tom Stellard8b135102015-12-16 18:31:01 +00002984 TryCand, Cand, RegExcess, TRI,
2985 DAG->MF))
Andrew Trick3b87f622012-11-07 07:05:09 +00002986 return;
Andrew Trick3b87f622012-11-07 07:05:09 +00002987
2988 // Avoid increasing the max critical pressure in the scheduled region.
Andrew Trick16bb45c2013-09-04 21:00:11 +00002989 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CriticalMax,
2990 Cand.RPDelta.CriticalMax,
Tom Stellard8b135102015-12-16 18:31:01 +00002991 TryCand, Cand, RegCritical, TRI,
2992 DAG->MF))
Andrew Trick3b87f622012-11-07 07:05:09 +00002993 return;
Andrew Trick3b87f622012-11-07 07:05:09 +00002994
Matthias Braunf011e372016-06-25 00:23:00 +00002995 // We only compare a subset of features when comparing nodes between
2996 // Top and Bottom boundary. Some properties are simply incomparable, in many
2997 // other instances we should only override the other boundary if something
2998 // is a clear good pick on one boundary. Skip heuristics that are more
2999 // "tie-breaking" in nature.
3000 bool SameBoundary = Zone != nullptr;
3001 if (SameBoundary) {
3002 // For loops that are acyclic path limited, aggressively schedule for
Jonas Paulsson1228c392016-11-04 08:31:14 +00003003 // latency. Within an single cycle, whenever CurrMOps > 0, allow normal
3004 // heuristics to take precedence.
Matthias Braunf011e372016-06-25 00:23:00 +00003005 if (Rem.IsAcyclicLatencyLimited && !Zone->getCurrMOps() &&
3006 tryLatency(TryCand, Cand, *Zone))
3007 return;
Andrew Trickf9c2fa82013-09-06 17:32:36 +00003008
Matthias Braunf011e372016-06-25 00:23:00 +00003009 // Prioritize instructions that read unbuffered resources by stall cycles.
3010 if (tryLess(Zone->getLatencyStallCycles(TryCand.SU),
3011 Zone->getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
3012 return;
3013 }
Andrew Trick57393132013-12-05 17:55:58 +00003014
Andrew Trick9b5caaa2012-11-12 19:40:10 +00003015 // Keep clustered nodes together to encourage downstream peephole
3016 // optimizations which may reduce resource requirements.
3017 //
3018 // This is a best effort to set things up for a post-RA pass. Optimizations
3019 // like generating loads of multiple registers should ideally be done within
3020 // the scheduler pass by combining the loads during DAG postprocessing.
Matthias Braunf011e372016-06-25 00:23:00 +00003021 const SUnit *CandNextClusterSU =
3022 Cand.AtTop ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
3023 const SUnit *TryCandNextClusterSU =
3024 TryCand.AtTop ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
3025 if (tryGreater(TryCand.SU == TryCandNextClusterSU,
3026 Cand.SU == CandNextClusterSU,
Andrew Trick9b5caaa2012-11-12 19:40:10 +00003027 TryCand, Cand, Cluster))
3028 return;
Andrew Tricke38afe12013-04-24 15:54:43 +00003029
Matthias Braunf011e372016-06-25 00:23:00 +00003030 if (SameBoundary) {
3031 // Weak edges are for clustering and other constraints.
3032 if (tryLess(getWeakLeft(TryCand.SU, TryCand.AtTop),
3033 getWeakLeft(Cand.SU, Cand.AtTop),
3034 TryCand, Cand, Weak))
3035 return;
Andrew Trick9b5caaa2012-11-12 19:40:10 +00003036 }
Matthias Braunf011e372016-06-25 00:23:00 +00003037
Andrew Tricka626f502013-06-17 21:45:13 +00003038 // Avoid increasing the max pressure of the entire region.
Andrew Trick16bb45c2013-09-04 21:00:11 +00003039 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CurrentMax,
3040 Cand.RPDelta.CurrentMax,
Tom Stellard8b135102015-12-16 18:31:01 +00003041 TryCand, Cand, RegMax, TRI,
3042 DAG->MF))
Andrew Tricka626f502013-06-17 21:45:13 +00003043 return;
3044
Matthias Braunf011e372016-06-25 00:23:00 +00003045 if (SameBoundary) {
3046 // Avoid critical resource consumption and balance the schedule.
3047 TryCand.initResourceDelta(DAG, SchedModel);
3048 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
3049 TryCand, Cand, ResourceReduce))
3050 return;
3051 if (tryGreater(TryCand.ResDelta.DemandedResources,
3052 Cand.ResDelta.DemandedResources,
3053 TryCand, Cand, ResourceDemand))
3054 return;
Andrew Trick3b87f622012-11-07 07:05:09 +00003055
Matthias Braunf011e372016-06-25 00:23:00 +00003056 // Avoid serializing long latency dependence chains.
3057 // For acyclic path limited loops, latency was already checked above.
3058 if (!RegionPolicy.DisableLatencyHeuristic && TryCand.Policy.ReduceLatency &&
3059 !Rem.IsAcyclicLatencyLimited && tryLatency(TryCand, Cand, *Zone))
3060 return;
Andrew Trick3b87f622012-11-07 07:05:09 +00003061
Matthias Braunf011e372016-06-25 00:23:00 +00003062 // Fall through to original instruction order.
3063 if ((Zone->isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
3064 || (!Zone->isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
3065 TryCand.Reason = NodeOrder;
3066 }
Andrew Trick3b87f622012-11-07 07:05:09 +00003067 }
3068}
Andrew Trick28ebc892012-05-10 21:06:19 +00003069
Andrew Trick6bf0c6c2013-09-06 17:32:44 +00003070/// Pick the best candidate from the queue.
Andrew Trick7196a8f2012-05-10 21:06:16 +00003071///
3072/// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
3073/// DAG building. To adjust for the current scheduling location we need to
3074/// maintain the number of vreg uses remaining to be top-scheduled.
Andrew Trick70e0b042013-09-19 23:10:59 +00003075void GenericScheduler::pickNodeFromQueue(SchedBoundary &Zone,
Matthias Braunf011e372016-06-25 00:23:00 +00003076 const CandPolicy &ZonePolicy,
Andrew Trick0591e2a2013-12-05 17:55:47 +00003077 const RegPressureTracker &RPTracker,
3078 SchedCandidate &Cand) {
Andrew Trick7196a8f2012-05-10 21:06:16 +00003079 // getMaxPressureDelta temporarily modifies the tracker.
3080 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
3081
Matthias Braun680b0dd2016-06-23 21:27:38 +00003082 ReadyQueue &Q = Zone.Available;
Javed Absar829442a2017-06-21 09:10:10 +00003083 for (SUnit *SU : Q) {
Andrew Trick7196a8f2012-05-10 21:06:16 +00003084
Matthias Braunf011e372016-06-25 00:23:00 +00003085 SchedCandidate TryCand(ZonePolicy);
Javed Absar829442a2017-06-21 09:10:10 +00003086 initCandidate(TryCand, SU, Zone.isTop(), RPTracker, TempTracker);
Matthias Braunf011e372016-06-25 00:23:00 +00003087 // Pass SchedBoundary only when comparing nodes from the same boundary.
3088 SchedBoundary *ZoneArg = Cand.AtTop == TryCand.AtTop ? &Zone : nullptr;
3089 tryCandidate(Cand, TryCand, ZoneArg);
Andrew Trick3b87f622012-11-07 07:05:09 +00003090 if (TryCand.Reason != NoCand) {
3091 // Initialize resource delta if needed in case future heuristics query it.
3092 if (TryCand.ResDelta == SchedResourceDelta())
3093 TryCand.initResourceDelta(DAG, SchedModel);
3094 Cand.setBest(TryCand);
Nicola Zaghen0818e782018-05-14 12:53:11 +00003095 LLVM_DEBUG(traceCandidate(Cand));
Andrew Trick73a0d8e2012-05-17 18:35:10 +00003096 }
Andrew Trick7196a8f2012-05-10 21:06:16 +00003097 }
Andrew Trick3b87f622012-11-07 07:05:09 +00003098}
3099
Andrew Trick73a0d8e2012-05-17 18:35:10 +00003100/// Pick the best candidate node from either the top or bottom queue.
Andrew Trick70e0b042013-09-19 23:10:59 +00003101SUnit *GenericScheduler::pickNodeBidirectional(bool &IsTopNode) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00003102 // Schedule as far as possible in the direction of no choice. This is most
3103 // efficient, but also provides the best heuristics for CriticalPSets.
Andrew Trick0a39d4e2012-05-24 22:11:09 +00003104 if (SUnit *SU = Bot.pickOnlyChoice()) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00003105 IsTopNode = false;
Matthias Brauna827bf12016-05-27 22:14:26 +00003106 tracePick(Only1, false);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00003107 return SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00003108 }
Andrew Trick0a39d4e2012-05-24 22:11:09 +00003109 if (SUnit *SU = Top.pickOnlyChoice()) {
Andrew Trick73a0d8e2012-05-17 18:35:10 +00003110 IsTopNode = true;
Matthias Brauna827bf12016-05-27 22:14:26 +00003111 tracePick(Only1, true);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00003112 return SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00003113 }
Andrew Trickdcddd712013-12-07 05:59:44 +00003114 // Set the bottom-up policy based on the state of the current bottom zone and
3115 // the instructions outside the zone, including the top zone.
Matthias Braunf011e372016-06-25 00:23:00 +00003116 CandPolicy BotPolicy;
3117 setPolicy(BotPolicy, /*IsPostRA=*/false, Bot, &Top);
Andrew Trickdcddd712013-12-07 05:59:44 +00003118 // Set the top-down policy based on the state of the current top zone and
3119 // the instructions outside the zone, including the bottom zone.
Matthias Braunf011e372016-06-25 00:23:00 +00003120 CandPolicy TopPolicy;
3121 setPolicy(TopPolicy, /*IsPostRA=*/false, Top, &Bot);
Andrew Trick3b87f622012-11-07 07:05:09 +00003122
Matthias Braun2feb69e2016-06-25 02:03:36 +00003123 // See if BotCand is still valid (because we previously scheduled from Top).
Nicola Zaghen0818e782018-05-14 12:53:11 +00003124 LLVM_DEBUG(dbgs() << "Picking from Bot:\n");
Matthias Braun2feb69e2016-06-25 02:03:36 +00003125 if (!BotCand.isValid() || BotCand.SU->isScheduled ||
3126 BotCand.Policy != BotPolicy) {
3127 BotCand.reset(CandPolicy());
3128 pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), BotCand);
3129 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
3130 } else {
Nicola Zaghen0818e782018-05-14 12:53:11 +00003131 LLVM_DEBUG(traceCandidate(BotCand));
Matthias Braun2feb69e2016-06-25 02:03:36 +00003132#ifndef NDEBUG
3133 if (VerifyScheduling) {
3134 SchedCandidate TCand;
3135 TCand.reset(CandPolicy());
3136 pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), TCand);
3137 assert(TCand.SU == BotCand.SU &&
3138 "Last pick result should correspond to re-picking right now");
3139 }
3140#endif
3141 }
Andrew Trick73a0d8e2012-05-17 18:35:10 +00003142
Andrew Trick73a0d8e2012-05-17 18:35:10 +00003143 // Check if the top Q has a better candidate.
Nicola Zaghen0818e782018-05-14 12:53:11 +00003144 LLVM_DEBUG(dbgs() << "Picking from Top:\n");
Matthias Braun2feb69e2016-06-25 02:03:36 +00003145 if (!TopCand.isValid() || TopCand.SU->isScheduled ||
3146 TopCand.Policy != TopPolicy) {
3147 TopCand.reset(CandPolicy());
3148 pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TopCand);
3149 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
3150 } else {
Nicola Zaghen0818e782018-05-14 12:53:11 +00003151 LLVM_DEBUG(traceCandidate(TopCand));
Matthias Braun2feb69e2016-06-25 02:03:36 +00003152#ifndef NDEBUG
3153 if (VerifyScheduling) {
3154 SchedCandidate TCand;
3155 TCand.reset(CandPolicy());
3156 pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TCand);
3157 assert(TCand.SU == TopCand.SU &&
3158 "Last pick result should correspond to re-picking right now");
3159 }
3160#endif
3161 }
3162
3163 // Pick best from BotCand and TopCand.
3164 assert(BotCand.isValid());
3165 assert(TopCand.isValid());
3166 SchedCandidate Cand = BotCand;
3167 TopCand.Reason = NoCand;
3168 tryCandidate(Cand, TopCand, nullptr);
3169 if (TopCand.Reason != NoCand) {
3170 Cand.setBest(TopCand);
Nicola Zaghen0818e782018-05-14 12:53:11 +00003171 LLVM_DEBUG(traceCandidate(Cand));
Matthias Braun2feb69e2016-06-25 02:03:36 +00003172 }
Andrew Trick73a0d8e2012-05-17 18:35:10 +00003173
Matthias Braunf011e372016-06-25 00:23:00 +00003174 IsTopNode = Cand.AtTop;
3175 tracePick(Cand);
3176 return Cand.SU;
Andrew Trick73a0d8e2012-05-17 18:35:10 +00003177}
3178
3179/// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
Andrew Trick70e0b042013-09-19 23:10:59 +00003180SUnit *GenericScheduler::pickNode(bool &IsTopNode) {
Andrew Trick7196a8f2012-05-10 21:06:16 +00003181 if (DAG->top() == DAG->bottom()) {
Andrew Trick0a39d4e2012-05-24 22:11:09 +00003182 assert(Top.Available.empty() && Top.Pending.empty() &&
3183 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
Craig Topper4ba84432014-04-14 00:51:57 +00003184 return nullptr;
Andrew Trick7196a8f2012-05-10 21:06:16 +00003185 }
Andrew Trick7196a8f2012-05-10 21:06:16 +00003186 SUnit *SU;
Andrew Trick30c6ec22012-10-08 18:53:53 +00003187 do {
Andrew Trick38e61122013-09-06 17:32:34 +00003188 if (RegionPolicy.OnlyTopDown) {
Andrew Trick30c6ec22012-10-08 18:53:53 +00003189 SU = Top.pickOnlyChoice();
3190 if (!SU) {
Andrew Trick3b87f622012-11-07 07:05:09 +00003191 CandPolicy NoPolicy;
Matthias Braun2feb69e2016-06-25 02:03:36 +00003192 TopCand.reset(NoPolicy);
Matthias Braunf011e372016-06-25 00:23:00 +00003193 pickNodeFromQueue(Top, NoPolicy, DAG->getTopRPTracker(), TopCand);
Andrew Trick85d7f0b2013-09-04 21:00:13 +00003194 assert(TopCand.Reason != NoCand && "failed to find a candidate");
Matthias Braunf011e372016-06-25 00:23:00 +00003195 tracePick(TopCand);
Andrew Trick30c6ec22012-10-08 18:53:53 +00003196 SU = TopCand.SU;
3197 }
3198 IsTopNode = true;
Matthias Braund3962152016-04-21 01:54:13 +00003199 } else if (RegionPolicy.OnlyBottomUp) {
Andrew Trick30c6ec22012-10-08 18:53:53 +00003200 SU = Bot.pickOnlyChoice();
3201 if (!SU) {
Andrew Trick3b87f622012-11-07 07:05:09 +00003202 CandPolicy NoPolicy;
Matthias Braun2feb69e2016-06-25 02:03:36 +00003203 BotCand.reset(NoPolicy);
Matthias Braunf011e372016-06-25 00:23:00 +00003204 pickNodeFromQueue(Bot, NoPolicy, DAG->getBotRPTracker(), BotCand);
Andrew Trick85d7f0b2013-09-04 21:00:13 +00003205 assert(BotCand.Reason != NoCand && "failed to find a candidate");
Matthias Braunf011e372016-06-25 00:23:00 +00003206 tracePick(BotCand);
Andrew Trick30c6ec22012-10-08 18:53:53 +00003207 SU = BotCand.SU;
3208 }
3209 IsTopNode = false;
Matthias Braund3962152016-04-21 01:54:13 +00003210 } else {
Andrew Trick3b87f622012-11-07 07:05:09 +00003211 SU = pickNodeBidirectional(IsTopNode);
Andrew Trick30c6ec22012-10-08 18:53:53 +00003212 }
3213 } while (SU->isScheduled);
3214
Andrew Trick0a39d4e2012-05-24 22:11:09 +00003215 if (SU->isTopReady())
3216 Top.removeReady(SU);
3217 if (SU->isBottomReady())
3218 Bot.removeReady(SU);
Andrew Trickc7a098f2012-05-25 02:02:39 +00003219
Nicola Zaghen0818e782018-05-14 12:53:11 +00003220 LLVM_DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") "
3221 << *SU->getInstr());
Andrew Trick7196a8f2012-05-10 21:06:16 +00003222 return SU;
3223}
3224
Nirav Davec8c80b02018-11-14 21:11:53 +00003225void GenericScheduler::reschedulePhysReg(SUnit *SU, bool isTop) {
Andrew Trick4392f0f2013-04-13 06:07:40 +00003226 MachineBasicBlock::iterator InsertPos = SU->getInstr();
3227 if (!isTop)
3228 ++InsertPos;
3229 SmallVectorImpl<SDep> &Deps = isTop ? SU->Preds : SU->Succs;
3230
3231 // Find already scheduled copies with a single physreg dependence and move
3232 // them just above the scheduled instruction.
Javed Absar829442a2017-06-21 09:10:10 +00003233 for (SDep &Dep : Deps) {
3234 if (Dep.getKind() != SDep::Data || !TRI->isPhysicalRegister(Dep.getReg()))
Andrew Trick4392f0f2013-04-13 06:07:40 +00003235 continue;
Javed Absar829442a2017-06-21 09:10:10 +00003236 SUnit *DepSU = Dep.getSUnit();
Andrew Trick4392f0f2013-04-13 06:07:40 +00003237 if (isTop ? DepSU->Succs.size() > 1 : DepSU->Preds.size() > 1)
3238 continue;
3239 MachineInstr *Copy = DepSU->getInstr();
Nirav Davec8c80b02018-11-14 21:11:53 +00003240 if (!Copy->isCopy() && !Copy->isMoveImmediate())
Andrew Trick4392f0f2013-04-13 06:07:40 +00003241 continue;
Nicola Zaghen0818e782018-05-14 12:53:11 +00003242 LLVM_DEBUG(dbgs() << " Rescheduling physreg copy ";
Matthias Braunb064c242018-09-19 00:23:35 +00003243 DAG->dumpNode(*Dep.getSUnit()));
Andrew Trick4392f0f2013-04-13 06:07:40 +00003244 DAG->moveInstruction(Copy, InsertPos);
3245 }
3246}
3247
Andrew Trick0a39d4e2012-05-24 22:11:09 +00003248/// Update the scheduler's state after scheduling a node. This is the same node
Andrew Trick9e76e1d2013-12-28 21:56:57 +00003249/// that was just returned by pickNode(). However, ScheduleDAGMILive needs to
3250/// update it's state based on the current cycle before MachineSchedStrategy
3251/// does.
Andrew Trick4392f0f2013-04-13 06:07:40 +00003252///
3253/// FIXME: Eventually, we may bundle physreg copies rather than rescheduling
Nirav Davec8c80b02018-11-14 21:11:53 +00003254/// them here. See comments in biasPhysReg.
Andrew Trick70e0b042013-09-19 23:10:59 +00003255void GenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
Andrew Trickb7e02892012-06-05 21:11:27 +00003256 if (IsTopNode) {
Andrew Trickdcddd712013-12-07 05:59:44 +00003257 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
Andrew Trick7f8c74c2012-06-29 03:23:22 +00003258 Top.bumpNode(SU);
Andrew Trick4392f0f2013-04-13 06:07:40 +00003259 if (SU->hasPhysRegUses)
Nirav Davec8c80b02018-11-14 21:11:53 +00003260 reschedulePhysReg(SU, true);
Matthias Braund3962152016-04-21 01:54:13 +00003261 } else {
Andrew Trickdcddd712013-12-07 05:59:44 +00003262 SU->BotReadyCycle = std::max(SU->BotReadyCycle, Bot.getCurrCycle());
Andrew Trick7f8c74c2012-06-29 03:23:22 +00003263 Bot.bumpNode(SU);
Andrew Trick4392f0f2013-04-13 06:07:40 +00003264 if (SU->hasPhysRegDefs)
Nirav Davec8c80b02018-11-14 21:11:53 +00003265 reschedulePhysReg(SU, false);
Andrew Trick0a39d4e2012-05-24 22:11:09 +00003266 }
3267}
3268
Andrew Trick17d35e52012-03-14 04:00:41 +00003269/// Create the standard converging machine scheduler. This will be used as the
3270/// default scheduler if the target does not set a default.
Matthias Braun05bdd2e2016-11-28 20:11:54 +00003271ScheduleDAGMILive *llvm::createGenericSchedLive(MachineSchedContext *C) {
Eugene Zelenko096e40d2017-02-22 22:32:51 +00003272 ScheduleDAGMILive *DAG =
3273 new ScheduleDAGMILive(C, llvm::make_unique<GenericScheduler>(C));
Andrew Trick9b5caaa2012-11-12 19:40:10 +00003274 // Register DAG post-processors.
Andrew Tricke38afe12013-04-24 15:54:43 +00003275 //
3276 // FIXME: extend the mutation API to allow earlier mutations to instantiate
3277 // data and pass it to later mutations. Have a single mutation that gathers
3278 // the interesting nodes in one pass.
Tom Stellard9163bca2016-08-19 19:59:18 +00003279 DAG->addMutation(createCopyConstrainDAGMutation(DAG->TII, DAG->TRI));
Andrew Trick9b5caaa2012-11-12 19:40:10 +00003280 return DAG;
Andrew Trick42b7a712012-01-17 06:55:03 +00003281}
Andrew Trick9e76e1d2013-12-28 21:56:57 +00003282
Matthias Braun05bdd2e2016-11-28 20:11:54 +00003283static ScheduleDAGInstrs *createConveringSched(MachineSchedContext *C) {
3284 return createGenericSchedLive(C);
3285}
3286
Andrew Trick42b7a712012-01-17 06:55:03 +00003287static MachineSchedRegistry
Andrew Trick70e0b042013-09-19 23:10:59 +00003288GenericSchedRegistry("converge", "Standard converging scheduler.",
Matthias Braun05bdd2e2016-11-28 20:11:54 +00003289 createConveringSched);
Andrew Trick9e76e1d2013-12-28 21:56:57 +00003290
3291//===----------------------------------------------------------------------===//
3292// PostGenericScheduler - Generic PostRA implementation of MachineSchedStrategy.
3293//===----------------------------------------------------------------------===//
3294
Andrew Trick0c834242014-06-04 07:06:18 +00003295void PostGenericScheduler::initialize(ScheduleDAGMI *Dag) {
3296 DAG = Dag;
3297 SchedModel = DAG->getSchedModel();
3298 TRI = DAG->TRI;
Andrew Trick9e76e1d2013-12-28 21:56:57 +00003299
Andrew Trick0c834242014-06-04 07:06:18 +00003300 Rem.init(DAG, SchedModel);
3301 Top.init(DAG, SchedModel, &Rem);
3302 BotRoots.clear();
Andrew Trick9e76e1d2013-12-28 21:56:57 +00003303
Andrew Trick0c834242014-06-04 07:06:18 +00003304 // Initialize the HazardRecognizers. If itineraries don't exist, are empty,
3305 // or are disabled, then these HazardRecs will be disabled.
3306 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
Andrew Trick0c834242014-06-04 07:06:18 +00003307 if (!Top.HazardRec) {
3308 Top.HazardRec =
Eric Christophercd694812014-10-14 06:56:25 +00003309 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
Eric Christopher9f85dcc2014-08-04 21:25:23 +00003310 Itin, DAG);
Andrew Trick9e76e1d2013-12-28 21:56:57 +00003311 }
Andrew Trick0c834242014-06-04 07:06:18 +00003312}
Andrew Trick9e76e1d2013-12-28 21:56:57 +00003313
Andrew Trick9e76e1d2013-12-28 21:56:57 +00003314void PostGenericScheduler::registerRoots() {
3315 Rem.CriticalPath = DAG->ExitSU.getDepth();
3316
3317 // Some roots may not feed into ExitSU. Check all of them in case.
Javed Absar829442a2017-06-21 09:10:10 +00003318 for (const SUnit *SU : BotRoots) {
3319 if (SU->getDepth() > Rem.CriticalPath)
3320 Rem.CriticalPath = SU->getDepth();
Andrew Trick9e76e1d2013-12-28 21:56:57 +00003321 }
Nicola Zaghen0818e782018-05-14 12:53:11 +00003322 LLVM_DEBUG(dbgs() << "Critical Path: (PGS-RR) " << Rem.CriticalPath << '\n');
Gerolf Hoflehner9fbb0122014-08-07 21:49:44 +00003323 if (DumpCriticalPathLength) {
3324 errs() << "Critical Path(PGS-RR ): " << Rem.CriticalPath << " \n";
3325 }
Andrew Trick9e76e1d2013-12-28 21:56:57 +00003326}
3327
Hiroshi Inoue73d058a2018-06-20 05:29:26 +00003328/// Apply a set of heuristics to a new candidate for PostRA scheduling.
Andrew Trick9e76e1d2013-12-28 21:56:57 +00003329///
3330/// \param Cand provides the policy and current best candidate.
3331/// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
3332void PostGenericScheduler::tryCandidate(SchedCandidate &Cand,
3333 SchedCandidate &TryCand) {
Andrew Trick9e76e1d2013-12-28 21:56:57 +00003334 // Initialize the candidate if needed.
3335 if (!Cand.isValid()) {
3336 TryCand.Reason = NodeOrder;
3337 return;
3338 }
3339
3340 // Prioritize instructions that read unbuffered resources by stall cycles.
3341 if (tryLess(Top.getLatencyStallCycles(TryCand.SU),
3342 Top.getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
3343 return;
3344
Florian Hahn4cdd2e62017-05-23 09:33:34 +00003345 // Keep clustered nodes together.
3346 if (tryGreater(TryCand.SU == DAG->getNextClusterSucc(),
3347 Cand.SU == DAG->getNextClusterSucc(),
3348 TryCand, Cand, Cluster))
3349 return;
3350
Andrew Trick9e76e1d2013-12-28 21:56:57 +00003351 // Avoid critical resource consumption and balance the schedule.
3352 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
3353 TryCand, Cand, ResourceReduce))
3354 return;
3355 if (tryGreater(TryCand.ResDelta.DemandedResources,
3356 Cand.ResDelta.DemandedResources,
3357 TryCand, Cand, ResourceDemand))
3358 return;
3359
3360 // Avoid serializing long latency dependence chains.
3361 if (Cand.Policy.ReduceLatency && tryLatency(TryCand, Cand, Top)) {
3362 return;
3363 }
3364
3365 // Fall through to original instruction order.
3366 if (TryCand.SU->NodeNum < Cand.SU->NodeNum)
3367 TryCand.Reason = NodeOrder;
3368}
3369
3370void PostGenericScheduler::pickNodeFromQueue(SchedCandidate &Cand) {
3371 ReadyQueue &Q = Top.Available;
Javed Absar829442a2017-06-21 09:10:10 +00003372 for (SUnit *SU : Q) {
Andrew Trick9e76e1d2013-12-28 21:56:57 +00003373 SchedCandidate TryCand(Cand.Policy);
Javed Absar829442a2017-06-21 09:10:10 +00003374 TryCand.SU = SU;
Matthias Braunf011e372016-06-25 00:23:00 +00003375 TryCand.AtTop = true;
Andrew Trick9e76e1d2013-12-28 21:56:57 +00003376 TryCand.initResourceDelta(DAG, SchedModel);
3377 tryCandidate(Cand, TryCand);
3378 if (TryCand.Reason != NoCand) {
3379 Cand.setBest(TryCand);
Nicola Zaghen0818e782018-05-14 12:53:11 +00003380 LLVM_DEBUG(traceCandidate(Cand));
Andrew Trick9e76e1d2013-12-28 21:56:57 +00003381 }
3382 }
3383}
3384
3385/// Pick the next node to schedule.
3386SUnit *PostGenericScheduler::pickNode(bool &IsTopNode) {
3387 if (DAG->top() == DAG->bottom()) {
3388 assert(Top.Available.empty() && Top.Pending.empty() && "ReadyQ garbage");
Craig Topper4ba84432014-04-14 00:51:57 +00003389 return nullptr;
Andrew Trick9e76e1d2013-12-28 21:56:57 +00003390 }
3391 SUnit *SU;
3392 do {
3393 SU = Top.pickOnlyChoice();
Matthias Brauna827bf12016-05-27 22:14:26 +00003394 if (SU) {
3395 tracePick(Only1, true);
3396 } else {
Andrew Trick9e76e1d2013-12-28 21:56:57 +00003397 CandPolicy NoPolicy;
3398 SchedCandidate TopCand(NoPolicy);
3399 // Set the top-down policy based on the state of the current top zone and
3400 // the instructions outside the zone, including the bottom zone.
Craig Topper4ba84432014-04-14 00:51:57 +00003401 setPolicy(TopCand.Policy, /*IsPostRA=*/true, Top, nullptr);
Andrew Trick9e76e1d2013-12-28 21:56:57 +00003402 pickNodeFromQueue(TopCand);
3403 assert(TopCand.Reason != NoCand && "failed to find a candidate");
Matthias Braunf011e372016-06-25 00:23:00 +00003404 tracePick(TopCand);
Andrew Trick9e76e1d2013-12-28 21:56:57 +00003405 SU = TopCand.SU;
3406 }
3407 } while (SU->isScheduled);
3408
3409 IsTopNode = true;
3410 Top.removeReady(SU);
3411
Nicola Zaghen0818e782018-05-14 12:53:11 +00003412 LLVM_DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") "
3413 << *SU->getInstr());
Andrew Trick9e76e1d2013-12-28 21:56:57 +00003414 return SU;
3415}
3416
3417/// Called after ScheduleDAGMI has scheduled an instruction and updated
3418/// scheduled/remaining flags in the DAG nodes.
3419void PostGenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
3420 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
3421 Top.bumpNode(SU);
3422}
3423
Matthias Braun05bdd2e2016-11-28 20:11:54 +00003424ScheduleDAGMI *llvm::createGenericSchedPostRA(MachineSchedContext *C) {
Eugene Zelenko096e40d2017-02-22 22:32:51 +00003425 return new ScheduleDAGMI(C, llvm::make_unique<PostGenericScheduler>(C),
Jonas Paulssone9ba8f32016-11-09 09:59:27 +00003426 /*RemoveKillFlags=*/true);
Andrew Trick9e76e1d2013-12-28 21:56:57 +00003427}
Andrew Trick42b7a712012-01-17 06:55:03 +00003428
3429//===----------------------------------------------------------------------===//
Andrew Trick1e94e982012-10-15 18:02:27 +00003430// ILP Scheduler. Currently for experimental analysis of heuristics.
3431//===----------------------------------------------------------------------===//
3432
3433namespace {
Eugene Zelenko096e40d2017-02-22 22:32:51 +00003434
Adrian Prantl26b584c2018-05-01 15:54:18 +00003435/// Order nodes by the ILP metric.
Andrew Trick1e94e982012-10-15 18:02:27 +00003436struct ILPOrder {
Eugene Zelenko096e40d2017-02-22 22:32:51 +00003437 const SchedDFSResult *DFSResult = nullptr;
3438 const BitVector *ScheduledTrees = nullptr;
Andrew Trick1e94e982012-10-15 18:02:27 +00003439 bool MaximizeILP;
3440
Eugene Zelenko096e40d2017-02-22 22:32:51 +00003441 ILPOrder(bool MaxILP) : MaximizeILP(MaxILP) {}
Andrew Trick1e94e982012-10-15 18:02:27 +00003442
Adrian Prantl26b584c2018-05-01 15:54:18 +00003443 /// Apply a less-than relation on node priority.
Andrew Trick8b1496c2012-11-28 05:13:28 +00003444 ///
3445 /// (Return true if A comes after B in the Q.)
Andrew Trick1e94e982012-10-15 18:02:27 +00003446 bool operator()(const SUnit *A, const SUnit *B) const {
Andrew Trick8b1496c2012-11-28 05:13:28 +00003447 unsigned SchedTreeA = DFSResult->getSubtreeID(A);
3448 unsigned SchedTreeB = DFSResult->getSubtreeID(B);
3449 if (SchedTreeA != SchedTreeB) {
3450 // Unscheduled trees have lower priority.
3451 if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
3452 return ScheduledTrees->test(SchedTreeB);
3453
3454 // Trees with shallower connections have have lower priority.
3455 if (DFSResult->getSubtreeLevel(SchedTreeA)
3456 != DFSResult->getSubtreeLevel(SchedTreeB)) {
3457 return DFSResult->getSubtreeLevel(SchedTreeA)
3458 < DFSResult->getSubtreeLevel(SchedTreeB);
3459 }
3460 }
Andrew Trick1e94e982012-10-15 18:02:27 +00003461 if (MaximizeILP)
Andrew Trick8b1496c2012-11-28 05:13:28 +00003462 return DFSResult->getILP(A) < DFSResult->getILP(B);
Andrew Trick1e94e982012-10-15 18:02:27 +00003463 else
Andrew Trick8b1496c2012-11-28 05:13:28 +00003464 return DFSResult->getILP(A) > DFSResult->getILP(B);
Andrew Trick1e94e982012-10-15 18:02:27 +00003465 }
3466};
3467
Adrian Prantl26b584c2018-05-01 15:54:18 +00003468/// Schedule based on the ILP metric.
Andrew Trick1e94e982012-10-15 18:02:27 +00003469class ILPScheduler : public MachineSchedStrategy {
Eugene Zelenko096e40d2017-02-22 22:32:51 +00003470 ScheduleDAGMILive *DAG = nullptr;
Andrew Trick1e94e982012-10-15 18:02:27 +00003471 ILPOrder Cmp;
3472
3473 std::vector<SUnit*> ReadyQ;
Eugene Zelenko096e40d2017-02-22 22:32:51 +00003474
Andrew Trick1e94e982012-10-15 18:02:27 +00003475public:
Eugene Zelenko096e40d2017-02-22 22:32:51 +00003476 ILPScheduler(bool MaximizeILP) : Cmp(MaximizeILP) {}
Andrew Trick1e94e982012-10-15 18:02:27 +00003477
Craig Topper9f998de2014-03-07 09:26:03 +00003478 void initialize(ScheduleDAGMI *dag) override {
Andrew Tricka38b0de2013-12-28 21:56:47 +00003479 assert(dag->hasVRegLiveness() && "ILPScheduler needs vreg liveness");
3480 DAG = static_cast<ScheduleDAGMILive*>(dag);
Andrew Trick4e1fb182013-01-25 06:33:57 +00003481 DAG->computeDFSResult();
Andrew Trick178f7d02013-01-25 04:01:04 +00003482 Cmp.DFSResult = DAG->getDFSResult();
3483 Cmp.ScheduledTrees = &DAG->getScheduledTrees();
Andrew Trick1e94e982012-10-15 18:02:27 +00003484 ReadyQ.clear();
Andrew Trick1e94e982012-10-15 18:02:27 +00003485 }
3486
Craig Topper9f998de2014-03-07 09:26:03 +00003487 void registerRoots() override {
Benjamin Kramer5175fd92012-11-29 14:36:26 +00003488 // Restore the heap in ReadyQ with the updated DFS results.
3489 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
Andrew Trick1e94e982012-10-15 18:02:27 +00003490 }
3491
3492 /// Implement MachineSchedStrategy interface.
3493 /// -----------------------------------------
3494
Andrew Trick8b1496c2012-11-28 05:13:28 +00003495 /// Callback to select the highest priority node from the ready Q.
Craig Topper9f998de2014-03-07 09:26:03 +00003496 SUnit *pickNode(bool &IsTopNode) override {
Craig Topper4ba84432014-04-14 00:51:57 +00003497 if (ReadyQ.empty()) return nullptr;
Matt Arsenault26c417b2013-03-21 00:57:21 +00003498 std::pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
Andrew Trick1e94e982012-10-15 18:02:27 +00003499 SUnit *SU = ReadyQ.back();
3500 ReadyQ.pop_back();
3501 IsTopNode = false;
Nicola Zaghen0818e782018-05-14 12:53:11 +00003502 LLVM_DEBUG(dbgs() << "Pick node "
3503 << "SU(" << SU->NodeNum << ") "
3504 << " ILP: " << DAG->getDFSResult()->getILP(SU)
3505 << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU)
3506 << " @"
3507 << DAG->getDFSResult()->getSubtreeLevel(
3508 DAG->getDFSResult()->getSubtreeID(SU))
3509 << '\n'
3510 << "Scheduling " << *SU->getInstr());
Andrew Trick1e94e982012-10-15 18:02:27 +00003511 return SU;
3512 }
3513
Adrian Prantl26b584c2018-05-01 15:54:18 +00003514 /// Scheduler callback to notify that a new subtree is scheduled.
Craig Topper9f998de2014-03-07 09:26:03 +00003515 void scheduleTree(unsigned SubtreeID) override {
Andrew Trick178f7d02013-01-25 04:01:04 +00003516 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3517 }
3518
Andrew Trick8b1496c2012-11-28 05:13:28 +00003519 /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
3520 /// DFSResults, and resort the priority Q.
Craig Topper9f998de2014-03-07 09:26:03 +00003521 void schedNode(SUnit *SU, bool IsTopNode) override {
Andrew Trick8b1496c2012-11-28 05:13:28 +00003522 assert(!IsTopNode && "SchedDFSResult needs bottom-up");
Andrew Trick8b1496c2012-11-28 05:13:28 +00003523 }
Andrew Trick1e94e982012-10-15 18:02:27 +00003524
Craig Topper9f998de2014-03-07 09:26:03 +00003525 void releaseTopNode(SUnit *) override { /*only called for top roots*/ }
Andrew Trick1e94e982012-10-15 18:02:27 +00003526
Craig Topper9f998de2014-03-07 09:26:03 +00003527 void releaseBottomNode(SUnit *SU) override {
Andrew Trick1e94e982012-10-15 18:02:27 +00003528 ReadyQ.push_back(SU);
3529 std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3530 }
3531};
Eugene Zelenko096e40d2017-02-22 22:32:51 +00003532
3533} // end anonymous namespace
Andrew Trick1e94e982012-10-15 18:02:27 +00003534
3535static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
Eugene Zelenko096e40d2017-02-22 22:32:51 +00003536 return new ScheduleDAGMILive(C, llvm::make_unique<ILPScheduler>(true));
Andrew Trick1e94e982012-10-15 18:02:27 +00003537}
3538static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
Eugene Zelenko096e40d2017-02-22 22:32:51 +00003539 return new ScheduleDAGMILive(C, llvm::make_unique<ILPScheduler>(false));
Andrew Trick1e94e982012-10-15 18:02:27 +00003540}
Eugene Zelenko096e40d2017-02-22 22:32:51 +00003541
Andrew Trick1e94e982012-10-15 18:02:27 +00003542static MachineSchedRegistry ILPMaxRegistry(
3543 "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
3544static MachineSchedRegistry ILPMinRegistry(
3545 "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
3546
3547//===----------------------------------------------------------------------===//
Andrew Trick5edf2f02012-01-14 02:17:06 +00003548// Machine Instruction Shuffler for Correctness Testing
3549//===----------------------------------------------------------------------===//
3550
Andrew Trick96f678f2012-01-13 06:30:30 +00003551#ifndef NDEBUG
3552namespace {
Eugene Zelenko096e40d2017-02-22 22:32:51 +00003553
Andrew Trick17d35e52012-03-14 04:00:41 +00003554/// Apply a less-than relation on the node order, which corresponds to the
3555/// instruction order prior to scheduling. IsReverse implements greater-than.
3556template<bool IsReverse>
3557struct SUnitOrder {
Andrew Trickc6cf11b2012-01-17 06:55:07 +00003558 bool operator()(SUnit *A, SUnit *B) const {
Andrew Trick17d35e52012-03-14 04:00:41 +00003559 if (IsReverse)
3560 return A->NodeNum > B->NodeNum;
3561 else
3562 return A->NodeNum < B->NodeNum;
Andrew Trickc6cf11b2012-01-17 06:55:07 +00003563 }
3564};
3565
Andrew Trick96f678f2012-01-13 06:30:30 +00003566/// Reorder instructions as much as possible.
Andrew Trick17d35e52012-03-14 04:00:41 +00003567class InstructionShuffler : public MachineSchedStrategy {
3568 bool IsAlternating;
3569 bool IsTopDown;
3570
3571 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
3572 // gives nodes with a higher number higher priority causing the latest
3573 // instructions to be scheduled first.
Eugene Zelenko096e40d2017-02-22 22:32:51 +00003574 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false>>
Andrew Trick17d35e52012-03-14 04:00:41 +00003575 TopQ;
Eugene Zelenko8fd05042017-09-11 23:00:48 +00003576
Andrew Trick17d35e52012-03-14 04:00:41 +00003577 // When scheduling bottom-up, use greater-than as the queue priority.
Eugene Zelenko096e40d2017-02-22 22:32:51 +00003578 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true>>
Andrew Trick17d35e52012-03-14 04:00:41 +00003579 BottomQ;
Eugene Zelenko096e40d2017-02-22 22:32:51 +00003580
Andrew Trick96f678f2012-01-13 06:30:30 +00003581public:
Andrew Trick17d35e52012-03-14 04:00:41 +00003582 InstructionShuffler(bool alternate, bool topdown)
3583 : IsAlternating(alternate), IsTopDown(topdown) {}
Andrew Trick96f678f2012-01-13 06:30:30 +00003584
Craig Toppereda7f442014-04-29 07:58:41 +00003585 void initialize(ScheduleDAGMI*) override {
Andrew Trick17d35e52012-03-14 04:00:41 +00003586 TopQ.clear();
3587 BottomQ.clear();
3588 }
Andrew Trickc6cf11b2012-01-17 06:55:07 +00003589
Andrew Trick17d35e52012-03-14 04:00:41 +00003590 /// Implement MachineSchedStrategy interface.
3591 /// -----------------------------------------
3592
Craig Toppereda7f442014-04-29 07:58:41 +00003593 SUnit *pickNode(bool &IsTopNode) override {
Andrew Trick17d35e52012-03-14 04:00:41 +00003594 SUnit *SU;
3595 if (IsTopDown) {
3596 do {
Craig Topper4ba84432014-04-14 00:51:57 +00003597 if (TopQ.empty()) return nullptr;
Andrew Trick17d35e52012-03-14 04:00:41 +00003598 SU = TopQ.top();
3599 TopQ.pop();
3600 } while (SU->isScheduled);
3601 IsTopNode = true;
Matthias Braund3962152016-04-21 01:54:13 +00003602 } else {
Andrew Trick17d35e52012-03-14 04:00:41 +00003603 do {
Craig Topper4ba84432014-04-14 00:51:57 +00003604 if (BottomQ.empty()) return nullptr;
Andrew Trick17d35e52012-03-14 04:00:41 +00003605 SU = BottomQ.top();
3606 BottomQ.pop();
3607 } while (SU->isScheduled);
3608 IsTopNode = false;
3609 }
3610 if (IsAlternating)
3611 IsTopDown = !IsTopDown;
Andrew Trickc6cf11b2012-01-17 06:55:07 +00003612 return SU;
3613 }
3614
Craig Toppereda7f442014-04-29 07:58:41 +00003615 void schedNode(SUnit *SU, bool IsTopNode) override {}
Andrew Trick0a39d4e2012-05-24 22:11:09 +00003616
Craig Toppereda7f442014-04-29 07:58:41 +00003617 void releaseTopNode(SUnit *SU) override {
Andrew Trick17d35e52012-03-14 04:00:41 +00003618 TopQ.push(SU);
3619 }
Craig Toppereda7f442014-04-29 07:58:41 +00003620 void releaseBottomNode(SUnit *SU) override {
Andrew Trick17d35e52012-03-14 04:00:41 +00003621 BottomQ.push(SU);
Andrew Trick96f678f2012-01-13 06:30:30 +00003622 }
3623};
Eugene Zelenko096e40d2017-02-22 22:32:51 +00003624
3625} // end anonymous namespace
Andrew Trick96f678f2012-01-13 06:30:30 +00003626
Andrew Trickc174eaf2012-03-08 01:41:12 +00003627static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
Andrew Trick17d35e52012-03-14 04:00:41 +00003628 bool Alternate = !ForceTopDown && !ForceBottomUp;
3629 bool TopDown = !ForceBottomUp;
Benjamin Kramer689e0b42012-03-14 11:26:37 +00003630 assert((TopDown || !ForceTopDown) &&
Andrew Trick17d35e52012-03-14 04:00:41 +00003631 "-misched-topdown incompatible with -misched-bottomup");
Eugene Zelenko096e40d2017-02-22 22:32:51 +00003632 return new ScheduleDAGMILive(
3633 C, llvm::make_unique<InstructionShuffler>(Alternate, TopDown));
Andrew Trick96f678f2012-01-13 06:30:30 +00003634}
Eugene Zelenko096e40d2017-02-22 22:32:51 +00003635
Andrew Trick17d35e52012-03-14 04:00:41 +00003636static MachineSchedRegistry ShufflerRegistry(
3637 "shuffle", "Shuffle machine instructions alternating directions",
3638 createInstructionShuffler);
Andrew Trick96f678f2012-01-13 06:30:30 +00003639#endif // !NDEBUG
Andrew Trick30849792013-01-25 07:45:29 +00003640
3641//===----------------------------------------------------------------------===//
Andrew Tricka38b0de2013-12-28 21:56:47 +00003642// GraphWriter support for ScheduleDAGMILive.
Andrew Trick30849792013-01-25 07:45:29 +00003643//===----------------------------------------------------------------------===//
3644
3645#ifndef NDEBUG
3646namespace llvm {
3647
3648template<> struct GraphTraits<
3649 ScheduleDAGMI*> : public GraphTraits<ScheduleDAG*> {};
3650
3651template<>
3652struct DOTGraphTraits<ScheduleDAGMI*> : public DefaultDOTGraphTraits {
Eugene Zelenko096e40d2017-02-22 22:32:51 +00003653 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
Andrew Trick30849792013-01-25 07:45:29 +00003654
3655 static std::string getGraphName(const ScheduleDAG *G) {
3656 return G->MF.getName();
3657 }
3658
3659 static bool renderGraphFromBottomUp() {
3660 return true;
3661 }
3662
3663 static bool isNodeHidden(const SUnit *Node) {
Matthias Braun4bdc7f82015-09-17 21:09:59 +00003664 if (ViewMISchedCutoff == 0)
3665 return false;
3666 return (Node->Preds.size() > ViewMISchedCutoff
3667 || Node->Succs.size() > ViewMISchedCutoff);
Andrew Trick30849792013-01-25 07:45:29 +00003668 }
3669
Andrew Trick30849792013-01-25 07:45:29 +00003670 /// If you want to override the dot attributes printed for a particular
3671 /// edge, override this method.
3672 static std::string getEdgeAttributes(const SUnit *Node,
3673 SUnitIterator EI,
3674 const ScheduleDAG *Graph) {
3675 if (EI.isArtificialDep())
3676 return "color=cyan,style=dashed";
3677 if (EI.isCtrlDep())
3678 return "color=blue,style=dashed";
3679 return "";
3680 }
3681
3682 static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) {
Alp Toker8dd8d5c2014-06-26 22:52:05 +00003683 std::string Str;
3684 raw_string_ostream SS(Str);
Andrew Tricka38b0de2013-12-28 21:56:47 +00003685 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3686 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
Craig Topper4ba84432014-04-14 00:51:57 +00003687 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
Andrew Trickfd303122013-09-06 17:32:42 +00003688 SS << "SU:" << SU->NodeNum;
3689 if (DFS)
3690 SS << " I:" << DFS->getNumInstrs(SU);
Andrew Trick30849792013-01-25 07:45:29 +00003691 return SS.str();
3692 }
Eugene Zelenko8fd05042017-09-11 23:00:48 +00003693
Andrew Trick30849792013-01-25 07:45:29 +00003694 static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G) {
3695 return G->getGraphNodeLabel(SU);
3696 }
3697
Andrew Tricka38b0de2013-12-28 21:56:47 +00003698 static std::string getNodeAttributes(const SUnit *N, const ScheduleDAG *G) {
Andrew Trick30849792013-01-25 07:45:29 +00003699 std::string Str("shape=Mrecord");
Andrew Tricka38b0de2013-12-28 21:56:47 +00003700 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3701 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
Craig Topper4ba84432014-04-14 00:51:57 +00003702 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
Andrew Trick30849792013-01-25 07:45:29 +00003703 if (DFS) {
3704 Str += ",style=filled,fillcolor=\"#";
3705 Str += DOT::getColorString(DFS->getSubtreeID(N));
3706 Str += '"';
3707 }
3708 return Str;
3709 }
3710};
Eugene Zelenko096e40d2017-02-22 22:32:51 +00003711
3712} // end namespace llvm
Andrew Trick30849792013-01-25 07:45:29 +00003713#endif // NDEBUG
3714
3715/// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
3716/// rendered using 'dot'.
Andrew Trick30849792013-01-25 07:45:29 +00003717void ScheduleDAGMI::viewGraph(const Twine &Name, const Twine &Title) {
3718#ifndef NDEBUG
3719 ViewGraph(this, Name, false, Title);
3720#else
3721 errs() << "ScheduleDAGMI::viewGraph is only available in debug builds on "
3722 << "systems with Graphviz or gv!\n";
3723#endif // NDEBUG
3724}
3725
3726/// Out-of-line implementation with no arguments is handy for gdb.
3727void ScheduleDAGMI::viewGraph() {
3728 viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName());
3729}