blob: c2c0d347f5ebade4066dc5e328453bf868f49821 [file] [log] [blame]
Andrew Trick6a50baa2012-05-17 22:37:09 +00001//===- MachineScheduler.cpp - Machine Instruction Scheduler ---------------===//
Andrew Tricke77e84e2012-01-13 06:30:30 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// MachineScheduler schedules machine instructions after phi elimination. It
11// preserves LiveIntervals so it can be invoked before register allocation.
12//
13//===----------------------------------------------------------------------===//
14
Chandler Carruth6bda14b2017-06-06 11:49:48 +000015#include "llvm/CodeGen/MachineScheduler.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000016#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/BitVector.h"
18#include "llvm/ADT/DenseMap.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/ADT/PriorityQueue.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000020#include "llvm/ADT/STLExtras.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000021#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/iterator_range.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/Analysis/AliasAnalysis.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000024#include "llvm/CodeGen/LiveInterval.h"
Matthias Braunf8422972017-12-13 02:51:04 +000025#include "llvm/CodeGen/LiveIntervals.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000026#include "llvm/CodeGen/MachineBasicBlock.h"
Jakub Staszakdf17ddd2013-03-10 13:11:23 +000027#include "llvm/CodeGen/MachineDominators.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000028#include "llvm/CodeGen/MachineFunction.h"
29#include "llvm/CodeGen/MachineFunctionPass.h"
30#include "llvm/CodeGen/MachineInstr.h"
Jakub Staszakdf17ddd2013-03-10 13:11:23 +000031#include "llvm/CodeGen/MachineLoopInfo.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000032#include "llvm/CodeGen/MachineOperand.h"
33#include "llvm/CodeGen/MachinePassRegistry.h"
Andrew Trick736dd9a2013-06-21 18:32:58 +000034#include "llvm/CodeGen/MachineRegisterInfo.h"
Andrew Tricke77e84e2012-01-13 06:30:30 +000035#include "llvm/CodeGen/Passes.h"
Andrew Trick05ff4662012-06-06 20:29:31 +000036#include "llvm/CodeGen/RegisterClassInfo.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000037#include "llvm/CodeGen/RegisterPressure.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000038#include "llvm/CodeGen/ScheduleDAG.h"
39#include "llvm/CodeGen/ScheduleDAGInstrs.h"
40#include "llvm/CodeGen/ScheduleDAGMutation.h"
Andrew Trickcd1c2f92012-11-28 05:13:24 +000041#include "llvm/CodeGen/ScheduleDFS.h"
Andrew Trick61f1a272012-05-24 22:11:09 +000042#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000043#include "llvm/CodeGen/SlotIndexes.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000044#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000045#include "llvm/CodeGen/TargetLowering.h"
Matthias Braun31d19d42016-05-10 03:21:59 +000046#include "llvm/CodeGen/TargetPassConfig.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000047#include "llvm/CodeGen/TargetRegisterInfo.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000048#include "llvm/CodeGen/TargetSchedule.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000049#include "llvm/CodeGen/TargetSubtargetInfo.h"
Nico Weber432a3882018-04-30 14:59:11 +000050#include "llvm/Config/llvm-config.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000051#include "llvm/MC/LaneBitmask.h"
52#include "llvm/Pass.h"
Andrew Tricke77e84e2012-01-13 06:30:30 +000053#include "llvm/Support/CommandLine.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000054#include "llvm/Support/Compiler.h"
Andrew Tricke77e84e2012-01-13 06:30:30 +000055#include "llvm/Support/Debug.h"
56#include "llvm/Support/ErrorHandling.h"
Andrew Trickea9fd952013-01-25 07:45:29 +000057#include "llvm/Support/GraphWriter.h"
David Blaikie13e77db2018-03-23 23:58:25 +000058#include "llvm/Support/MachineValueType.h"
Andrew Tricke77e84e2012-01-13 06:30:30 +000059#include "llvm/Support/raw_ostream.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000060#include <algorithm>
61#include <cassert>
62#include <cstdint>
63#include <iterator>
64#include <limits>
65#include <memory>
66#include <string>
67#include <tuple>
68#include <utility>
69#include <vector>
Andrew Trick7ccdc5c2012-01-17 06:55:07 +000070
Andrew Tricke77e84e2012-01-13 06:30:30 +000071using namespace llvm;
72
Matthias Braun1527baa2017-05-25 21:26:32 +000073#define DEBUG_TYPE "machine-scheduler"
Chandler Carruth1b9dde02014-04-22 02:02:50 +000074
Andrew Trick7a8e1002012-09-11 00:39:15 +000075namespace llvm {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000076
Andrew Trick7a8e1002012-09-11 00:39:15 +000077cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
78 cl::desc("Force top-down list scheduling"));
79cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
80 cl::desc("Force bottom-up list scheduling"));
Gerolf Hoflehnerb5220dc2014-08-07 21:49:44 +000081cl::opt<bool>
82DumpCriticalPathLength("misched-dcpl", cl::Hidden,
83 cl::desc("Print critical path length to stdout"));
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000084
85} // end namespace llvm
Andrew Trick8823dec2012-03-14 04:00:41 +000086
Andrew Tricka5f19562012-03-07 00:18:25 +000087#ifndef NDEBUG
88static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
89 cl::desc("Pop up a window to show MISched dags after they are processed"));
Lang Hamesdd98c492012-03-19 18:38:38 +000090
Matthias Braund78ee542015-09-17 21:09:59 +000091/// In some situations a few uninteresting nodes depend on nearly all other
92/// nodes in the graph, provide a cutoff to hide them.
93static cl::opt<unsigned> ViewMISchedCutoff("view-misched-cutoff", cl::Hidden,
94 cl::desc("Hide nodes with more predecessor/successor than cutoff"));
95
Lang Hamesdd98c492012-03-19 18:38:38 +000096static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
97 cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
Andrew Trick33e05d72013-12-28 21:57:02 +000098
99static cl::opt<std::string> SchedOnlyFunc("misched-only-func", cl::Hidden,
100 cl::desc("Only schedule this function"));
101static cl::opt<unsigned> SchedOnlyBlock("misched-only-block", cl::Hidden,
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000102 cl::desc("Only schedule this MBB#"));
Andrew Tricka5f19562012-03-07 00:18:25 +0000103#else
104static bool ViewMISchedDAGs = false;
105#endif // NDEBUG
106
Matthias Braun6493bc22016-04-22 19:09:17 +0000107/// Avoid quadratic complexity in unusually large basic blocks by limiting the
108/// size of the ready lists.
109static cl::opt<unsigned> ReadyListLimit("misched-limit", cl::Hidden,
110 cl::desc("Limit ready list to N instructions"), cl::init(256));
111
Andrew Trickb6e74712013-09-04 20:59:59 +0000112static cl::opt<bool> EnableRegPressure("misched-regpressure", cl::Hidden,
113 cl::desc("Enable register pressure scheduling."), cl::init(true));
114
Andrew Trickc01b0042013-08-23 17:48:43 +0000115static cl::opt<bool> EnableCyclicPath("misched-cyclicpath", cl::Hidden,
Andrew Trick6c88b352013-09-09 23:31:14 +0000116 cl::desc("Enable cyclic critical path analysis."), cl::init(true));
Andrew Trickc01b0042013-08-23 17:48:43 +0000117
Jun Bum Lim4c5bd582016-04-15 14:58:38 +0000118static cl::opt<bool> EnableMemOpCluster("misched-cluster", cl::Hidden,
119 cl::desc("Enable memop clustering."),
120 cl::init(true));
Andrew Tricka7714a02012-11-12 19:40:10 +0000121
Andrew Trick48f2a722013-03-08 05:40:34 +0000122static cl::opt<bool> VerifyScheduling("verify-misched", cl::Hidden,
123 cl::desc("Verify machine instrs before and after machine scheduling"));
124
Andrew Trick44f750a2013-01-25 04:01:04 +0000125// DAG subtrees must have at least this many nodes.
126static const unsigned MinSubtreeSize = 8;
127
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +0000128// Pin the vtables to this file.
129void MachineSchedStrategy::anchor() {}
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +0000130
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +0000131void ScheduleDAGMutation::anchor() {}
132
Andrew Trick63440872012-01-14 02:17:06 +0000133//===----------------------------------------------------------------------===//
134// Machine Instruction Scheduling Pass and Registry
135//===----------------------------------------------------------------------===//
136
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +0000137MachineSchedContext::MachineSchedContext() {
Andrew Trick4d4b5462012-04-24 20:36:19 +0000138 RegClassInfo = new RegisterClassInfo();
139}
140
141MachineSchedContext::~MachineSchedContext() {
142 delete RegClassInfo;
143}
144
Andrew Tricke77e84e2012-01-13 06:30:30 +0000145namespace {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +0000146
Andrew Trickd7f890e2013-12-28 21:56:47 +0000147/// Base class for a machine scheduler class that can run at any point.
148class MachineSchedulerBase : public MachineSchedContext,
149 public MachineFunctionPass {
150public:
151 MachineSchedulerBase(char &ID): MachineFunctionPass(ID) {}
152
Craig Topperc0196b12014-04-14 00:51:57 +0000153 void print(raw_ostream &O, const Module* = nullptr) const override;
Andrew Trickd7f890e2013-12-28 21:56:47 +0000154
155protected:
Matthias Braun93563e72015-11-03 01:53:29 +0000156 void scheduleRegions(ScheduleDAGInstrs &Scheduler, bool FixKillFlags);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000157};
158
Andrew Tricke1c034f2012-01-17 06:55:03 +0000159/// MachineScheduler runs after coalescing and before register allocation.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000160class MachineScheduler : public MachineSchedulerBase {
Andrew Tricke77e84e2012-01-13 06:30:30 +0000161public:
Andrew Tricke1c034f2012-01-17 06:55:03 +0000162 MachineScheduler();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000163
Craig Topper4584cd52014-03-07 09:26:03 +0000164 void getAnalysisUsage(AnalysisUsage &AU) const override;
Andrew Tricke77e84e2012-01-13 06:30:30 +0000165
Craig Topper4584cd52014-03-07 09:26:03 +0000166 bool runOnMachineFunction(MachineFunction&) override;
Andrew Tricke77e84e2012-01-13 06:30:30 +0000167
Andrew Tricke77e84e2012-01-13 06:30:30 +0000168 static char ID; // Class identification, replacement for typeinfo
Andrew Trick978674b2013-09-20 05:14:41 +0000169
170protected:
171 ScheduleDAGInstrs *createMachineScheduler();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000172};
Andrew Trick17080b92013-12-28 21:56:51 +0000173
174/// PostMachineScheduler runs after shortly before code emission.
175class PostMachineScheduler : public MachineSchedulerBase {
176public:
177 PostMachineScheduler();
178
Craig Topper4584cd52014-03-07 09:26:03 +0000179 void getAnalysisUsage(AnalysisUsage &AU) const override;
Andrew Trick17080b92013-12-28 21:56:51 +0000180
Craig Topper4584cd52014-03-07 09:26:03 +0000181 bool runOnMachineFunction(MachineFunction&) override;
Andrew Trick17080b92013-12-28 21:56:51 +0000182
183 static char ID; // Class identification, replacement for typeinfo
184
185protected:
186 ScheduleDAGInstrs *createPostMachineScheduler();
187};
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +0000188
189} // end anonymous namespace
Andrew Tricke77e84e2012-01-13 06:30:30 +0000190
Andrew Tricke1c034f2012-01-17 06:55:03 +0000191char MachineScheduler::ID = 0;
Andrew Tricke77e84e2012-01-13 06:30:30 +0000192
Andrew Tricke1c034f2012-01-17 06:55:03 +0000193char &llvm::MachineSchedulerID = MachineScheduler::ID;
Andrew Tricke77e84e2012-01-13 06:30:30 +0000194
Matthias Braun1527baa2017-05-25 21:26:32 +0000195INITIALIZE_PASS_BEGIN(MachineScheduler, DEBUG_TYPE,
Andrew Tricke77e84e2012-01-13 06:30:30 +0000196 "Machine Instruction Scheduler", false, false)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000197INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Davide Italiano6a1209e2017-03-24 20:52:56 +0000198INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
Andrew Tricke77e84e2012-01-13 06:30:30 +0000199INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
200INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
Matthias Braun1527baa2017-05-25 21:26:32 +0000201INITIALIZE_PASS_END(MachineScheduler, DEBUG_TYPE,
Andrew Tricke77e84e2012-01-13 06:30:30 +0000202 "Machine Instruction Scheduler", false, false)
203
Eugene Zelenko32a40562017-09-11 23:00:48 +0000204MachineScheduler::MachineScheduler() : MachineSchedulerBase(ID) {
Andrew Tricke1c034f2012-01-17 06:55:03 +0000205 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Andrew Tricke77e84e2012-01-13 06:30:30 +0000206}
207
Andrew Tricke1c034f2012-01-17 06:55:03 +0000208void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
Andrew Tricke77e84e2012-01-13 06:30:30 +0000209 AU.setPreservesCFG();
210 AU.addRequiredID(MachineDominatorsID);
211 AU.addRequired<MachineLoopInfo>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000212 AU.addRequired<AAResultsWrapperPass>();
Andrew Trick45300682012-03-09 00:52:20 +0000213 AU.addRequired<TargetPassConfig>();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000214 AU.addRequired<SlotIndexes>();
215 AU.addPreserved<SlotIndexes>();
216 AU.addRequired<LiveIntervals>();
217 AU.addPreserved<LiveIntervals>();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000218 MachineFunctionPass::getAnalysisUsage(AU);
219}
220
Andrew Trick17080b92013-12-28 21:56:51 +0000221char PostMachineScheduler::ID = 0;
222
223char &llvm::PostMachineSchedulerID = PostMachineScheduler::ID;
224
225INITIALIZE_PASS(PostMachineScheduler, "postmisched",
Saleem Abdulrasool7230b372013-12-28 22:47:55 +0000226 "PostRA Machine Instruction Scheduler", false, false)
Andrew Trick17080b92013-12-28 21:56:51 +0000227
Eugene Zelenko32a40562017-09-11 23:00:48 +0000228PostMachineScheduler::PostMachineScheduler() : MachineSchedulerBase(ID) {
Andrew Trick17080b92013-12-28 21:56:51 +0000229 initializePostMachineSchedulerPass(*PassRegistry::getPassRegistry());
230}
231
232void PostMachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
233 AU.setPreservesCFG();
234 AU.addRequiredID(MachineDominatorsID);
235 AU.addRequired<MachineLoopInfo>();
236 AU.addRequired<TargetPassConfig>();
237 MachineFunctionPass::getAnalysisUsage(AU);
238}
239
Andrew Tricke77e84e2012-01-13 06:30:30 +0000240MachinePassRegistry MachineSchedRegistry::Registry;
241
Andrew Trick45300682012-03-09 00:52:20 +0000242/// A dummy default scheduler factory indicates whether the scheduler
243/// is overridden on the command line.
244static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
Craig Topperc0196b12014-04-14 00:51:57 +0000245 return nullptr;
Andrew Trick45300682012-03-09 00:52:20 +0000246}
Andrew Tricke77e84e2012-01-13 06:30:30 +0000247
248/// MachineSchedOpt allows command line selection of the scheduler.
249static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +0000250 RegisterPassParser<MachineSchedRegistry>>
Andrew Tricke77e84e2012-01-13 06:30:30 +0000251MachineSchedOpt("misched",
Andrew Trick45300682012-03-09 00:52:20 +0000252 cl::init(&useDefaultMachineSched), cl::Hidden,
Andrew Tricke77e84e2012-01-13 06:30:30 +0000253 cl::desc("Machine instruction scheduler to use"));
254
Andrew Trick45300682012-03-09 00:52:20 +0000255static MachineSchedRegistry
Andrew Trick8823dec2012-03-14 04:00:41 +0000256DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
Andrew Trick45300682012-03-09 00:52:20 +0000257 useDefaultMachineSched);
258
Eric Christopher5f141b02015-03-11 22:56:10 +0000259static cl::opt<bool> EnableMachineSched(
260 "enable-misched",
261 cl::desc("Enable the machine instruction scheduling pass."), cl::init(true),
262 cl::Hidden);
263
Chad Rosier816a1ab2016-01-20 23:08:32 +0000264static cl::opt<bool> EnablePostRAMachineSched(
265 "enable-post-misched",
266 cl::desc("Enable the post-ra machine instruction scheduling pass."),
267 cl::init(true), cl::Hidden);
268
Andrew Trickcc45a282012-04-24 18:04:34 +0000269/// Decrement this iterator until reaching the top or a non-debug instr.
Andrew Trick2bc74c22013-08-30 04:36:57 +0000270static MachineBasicBlock::const_iterator
271priorNonDebug(MachineBasicBlock::const_iterator I,
272 MachineBasicBlock::const_iterator Beg) {
Andrew Trickcc45a282012-04-24 18:04:34 +0000273 assert(I != Beg && "reached the top of the region, cannot decrement");
274 while (--I != Beg) {
Shiva Chen801bf7e2018-05-09 02:42:00 +0000275 if (!I->isDebugInstr())
Andrew Trickcc45a282012-04-24 18:04:34 +0000276 break;
277 }
278 return I;
279}
280
Andrew Trick2bc74c22013-08-30 04:36:57 +0000281/// Non-const version.
282static MachineBasicBlock::iterator
283priorNonDebug(MachineBasicBlock::iterator I,
284 MachineBasicBlock::const_iterator Beg) {
Duncan P. N. Exon Smithdcbce9c2016-08-16 23:34:07 +0000285 return priorNonDebug(MachineBasicBlock::const_iterator(I), Beg)
286 .getNonConstIterator();
Andrew Trick2bc74c22013-08-30 04:36:57 +0000287}
288
Andrew Trickcc45a282012-04-24 18:04:34 +0000289/// If this iterator is a debug value, increment until reaching the End or a
290/// non-debug instruction.
Andrew Trick2c4f8b72013-08-31 05:17:58 +0000291static MachineBasicBlock::const_iterator
292nextIfDebug(MachineBasicBlock::const_iterator I,
293 MachineBasicBlock::const_iterator End) {
Andrew Trick463b2f12012-05-17 18:35:03 +0000294 for(; I != End; ++I) {
Shiva Chen801bf7e2018-05-09 02:42:00 +0000295 if (!I->isDebugInstr())
Andrew Trickcc45a282012-04-24 18:04:34 +0000296 break;
297 }
298 return I;
299}
300
Andrew Trick2c4f8b72013-08-31 05:17:58 +0000301/// Non-const version.
302static MachineBasicBlock::iterator
303nextIfDebug(MachineBasicBlock::iterator I,
304 MachineBasicBlock::const_iterator End) {
Duncan P. N. Exon Smithdcbce9c2016-08-16 23:34:07 +0000305 return nextIfDebug(MachineBasicBlock::const_iterator(I), End)
306 .getNonConstIterator();
Andrew Trick2c4f8b72013-08-31 05:17:58 +0000307}
308
Andrew Trickdc4c1ad2013-09-24 17:11:19 +0000309/// Instantiate a ScheduleDAGInstrs that will be owned by the caller.
Andrew Trick978674b2013-09-20 05:14:41 +0000310ScheduleDAGInstrs *MachineScheduler::createMachineScheduler() {
311 // Select the scheduler, or set the default.
312 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
313 if (Ctor != useDefaultMachineSched)
314 return Ctor(this);
315
316 // Get the default scheduler set by the target for this function.
317 ScheduleDAGInstrs *Scheduler = PassConfig->createMachineScheduler(this);
318 if (Scheduler)
319 return Scheduler;
320
321 // Default to GenericScheduler.
Andrew Trickd14d7c22013-12-28 21:56:57 +0000322 return createGenericSchedLive(this);
Andrew Trick978674b2013-09-20 05:14:41 +0000323}
324
Andrew Trick17080b92013-12-28 21:56:51 +0000325/// Instantiate a ScheduleDAGInstrs for PostRA scheduling that will be owned by
326/// the caller. We don't have a command line option to override the postRA
327/// scheduler. The Target must configure it.
328ScheduleDAGInstrs *PostMachineScheduler::createPostMachineScheduler() {
329 // Get the postRA scheduler set by the target for this function.
330 ScheduleDAGInstrs *Scheduler = PassConfig->createPostMachineScheduler(this);
331 if (Scheduler)
332 return Scheduler;
333
334 // Default to GenericScheduler.
Andrew Trickd14d7c22013-12-28 21:56:57 +0000335 return createGenericSchedPostRA(this);
Andrew Trick17080b92013-12-28 21:56:51 +0000336}
337
Andrew Trick72515be2012-03-14 04:00:38 +0000338/// Top-level MachineScheduler pass driver.
339///
340/// Visit blocks in function order. Divide each block into scheduling regions
Andrew Trick8823dec2012-03-14 04:00:41 +0000341/// and visit them bottom-up. Visiting regions bottom-up is not required, but is
342/// consistent with the DAG builder, which traverses the interior of the
343/// scheduling regions bottom-up.
Andrew Trick72515be2012-03-14 04:00:38 +0000344///
345/// This design avoids exposing scheduling boundaries to the DAG builder,
Andrew Trick8823dec2012-03-14 04:00:41 +0000346/// simplifying the DAG builder's support for "special" target instructions.
347/// At the same time the design allows target schedulers to operate across
Andrew Trick72515be2012-03-14 04:00:38 +0000348/// scheduling boundaries, for example to bundle the boudary instructions
349/// without reordering them. This creates complexity, because the target
350/// scheduler must update the RegionBegin and RegionEnd positions cached by
351/// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
352/// design would be to split blocks at scheduling boundaries, but LLVM has a
353/// general bias against block splitting purely for implementation simplicity.
Andrew Tricke1c034f2012-01-17 06:55:03 +0000354bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
Matthias Braunf1caa282017-12-15 22:22:58 +0000355 if (skipFunction(mf.getFunction()))
Chad Rosier6338d7c2016-01-20 22:38:25 +0000356 return false;
357
Eric Christopher5f141b02015-03-11 22:56:10 +0000358 if (EnableMachineSched.getNumOccurrences()) {
359 if (!EnableMachineSched)
360 return false;
361 } else if (!mf.getSubtarget().enableMachineScheduler())
362 return false;
363
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000364 LLVM_DEBUG(dbgs() << "Before MISched:\n"; mf.print(dbgs()));
Andrew Trickc5d70082012-05-10 21:06:21 +0000365
Andrew Tricke77e84e2012-01-13 06:30:30 +0000366 // Initialize the context of the pass.
367 MF = &mf;
368 MLI = &getAnalysis<MachineLoopInfo>();
369 MDT = &getAnalysis<MachineDominatorTree>();
Andrew Trick45300682012-03-09 00:52:20 +0000370 PassConfig = &getAnalysis<TargetPassConfig>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000371 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Andrew Trick02a80da2012-03-08 01:41:12 +0000372
Lang Hamesad33d5a2012-01-27 22:36:19 +0000373 LIS = &getAnalysis<LiveIntervals>();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000374
Andrew Trick48f2a722013-03-08 05:40:34 +0000375 if (VerifyScheduling) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000376 LLVM_DEBUG(LIS->dump());
Andrew Trick48f2a722013-03-08 05:40:34 +0000377 MF->verify(this, "Before machine scheduling.");
378 }
Andrew Trick4d4b5462012-04-24 20:36:19 +0000379 RegClassInfo->runOnMachineFunction(*MF);
Andrew Trick88639922012-04-24 17:56:43 +0000380
Andrew Trick978674b2013-09-20 05:14:41 +0000381 // Instantiate the selected scheduler for this target, function, and
382 // optimization level.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000383 std::unique_ptr<ScheduleDAGInstrs> Scheduler(createMachineScheduler());
Matthias Braun93563e72015-11-03 01:53:29 +0000384 scheduleRegions(*Scheduler, false);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000385
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000386 LLVM_DEBUG(LIS->dump());
Andrew Trickd7f890e2013-12-28 21:56:47 +0000387 if (VerifyScheduling)
388 MF->verify(this, "After machine scheduling.");
389 return true;
390}
391
Andrew Trick17080b92013-12-28 21:56:51 +0000392bool PostMachineScheduler::runOnMachineFunction(MachineFunction &mf) {
Matthias Braunf1caa282017-12-15 22:22:58 +0000393 if (skipFunction(mf.getFunction()))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000394 return false;
395
Chad Rosier816a1ab2016-01-20 23:08:32 +0000396 if (EnablePostRAMachineSched.getNumOccurrences()) {
397 if (!EnablePostRAMachineSched)
398 return false;
399 } else if (!mf.getSubtarget().enablePostRAScheduler()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000400 LLVM_DEBUG(dbgs() << "Subtarget disables post-MI-sched.\n");
Andrew Trick8d2ee372014-06-04 07:06:27 +0000401 return false;
402 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000403 LLVM_DEBUG(dbgs() << "Before post-MI-sched:\n"; mf.print(dbgs()));
Andrew Trick17080b92013-12-28 21:56:51 +0000404
405 // Initialize the context of the pass.
406 MF = &mf;
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000407 MLI = &getAnalysis<MachineLoopInfo>();
Andrew Trick17080b92013-12-28 21:56:51 +0000408 PassConfig = &getAnalysis<TargetPassConfig>();
409
410 if (VerifyScheduling)
411 MF->verify(this, "Before post machine scheduling.");
412
413 // Instantiate the selected scheduler for this target, function, and
414 // optimization level.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000415 std::unique_ptr<ScheduleDAGInstrs> Scheduler(createPostMachineScheduler());
Matthias Braun93563e72015-11-03 01:53:29 +0000416 scheduleRegions(*Scheduler, true);
Andrew Trick17080b92013-12-28 21:56:51 +0000417
418 if (VerifyScheduling)
419 MF->verify(this, "After post machine scheduling.");
420 return true;
421}
422
Andrew Trickd14d7c22013-12-28 21:56:57 +0000423/// Return true of the given instruction should not be included in a scheduling
424/// region.
425///
426/// MachineScheduler does not currently support scheduling across calls. To
427/// handle calls, the DAG builder needs to be modified to create register
428/// anti/output dependencies on the registers clobbered by the call's regmask
429/// operand. In PreRA scheduling, the stack pointer adjustment already prevents
430/// scheduling across calls. In PostRA scheduling, we need the isCall to enforce
431/// the boundary, but there would be no benefit to postRA scheduling across
432/// calls this late anyway.
433static bool isSchedBoundary(MachineBasicBlock::iterator MI,
434 MachineBasicBlock *MBB,
435 MachineFunction *MF,
Matthias Braun93563e72015-11-03 01:53:29 +0000436 const TargetInstrInfo *TII) {
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000437 return MI->isCall() || TII->isSchedulingBoundary(*MI, MBB, *MF);
Andrew Trickd14d7c22013-12-28 21:56:57 +0000438}
439
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000440/// A region of an MBB for scheduling.
Mikael Holmen4eb2a962017-09-13 14:07:47 +0000441namespace {
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000442struct SchedRegion {
443 /// RegionBegin is the first instruction in the scheduling region, and
444 /// RegionEnd is either MBB->end() or the scheduling boundary after the
445 /// last instruction in the scheduling region. These iterators cannot refer
446 /// to instructions outside of the identified scheduling region because
447 /// those may be reordered before scheduling this region.
448 MachineBasicBlock::iterator RegionBegin;
449 MachineBasicBlock::iterator RegionEnd;
450 unsigned NumRegionInstrs;
Eugene Zelenko32a40562017-09-11 23:00:48 +0000451
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000452 SchedRegion(MachineBasicBlock::iterator B, MachineBasicBlock::iterator E,
453 unsigned N) :
454 RegionBegin(B), RegionEnd(E), NumRegionInstrs(N) {}
455};
Mikael Holmen4eb2a962017-09-13 14:07:47 +0000456} // end anonymous namespace
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000457
Eugene Zelenko32a40562017-09-11 23:00:48 +0000458using MBBRegionsVector = SmallVector<SchedRegion, 16>;
459
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000460static void
461getSchedRegions(MachineBasicBlock *MBB,
462 MBBRegionsVector &Regions,
463 bool RegionsTopDown) {
464 MachineFunction *MF = MBB->getParent();
465 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
466
467 MachineBasicBlock::iterator I = nullptr;
468 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
469 RegionEnd != MBB->begin(); RegionEnd = I) {
470
471 // Avoid decrementing RegionEnd for blocks with no terminator.
472 if (RegionEnd != MBB->end() ||
473 isSchedBoundary(&*std::prev(RegionEnd), &*MBB, MF, TII)) {
474 --RegionEnd;
475 }
476
477 // The next region starts above the previous region. Look backward in the
478 // instruction stream until we find the nearest boundary.
479 unsigned NumRegionInstrs = 0;
480 I = RegionEnd;
481 for (;I != MBB->begin(); --I) {
482 MachineInstr &MI = *std::prev(I);
483 if (isSchedBoundary(&MI, &*MBB, MF, TII))
484 break;
Shiva Chen801bf7e2018-05-09 02:42:00 +0000485 if (!MI.isDebugInstr())
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000486 // MBB::size() uses instr_iterator to count. Here we need a bundle to
487 // count as a single instruction.
488 ++NumRegionInstrs;
489 }
490
491 Regions.push_back(SchedRegion(I, RegionEnd, NumRegionInstrs));
492 }
493
494 if (RegionsTopDown)
495 std::reverse(Regions.begin(), Regions.end());
496}
497
Andrew Trickd7f890e2013-12-28 21:56:47 +0000498/// Main driver for both MachineScheduler and PostMachineScheduler.
Matthias Braun93563e72015-11-03 01:53:29 +0000499void MachineSchedulerBase::scheduleRegions(ScheduleDAGInstrs &Scheduler,
500 bool FixKillFlags) {
Andrew Tricke77e84e2012-01-13 06:30:30 +0000501 // Visit all machine basic blocks.
Andrew Trick88639922012-04-24 17:56:43 +0000502 //
503 // TODO: Visit blocks in global postorder or postorder within the bottom-up
504 // loop tree. Then we can optionally compute global RegPressure.
Andrew Tricke77e84e2012-01-13 06:30:30 +0000505 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
506 MBB != MBBEnd; ++MBB) {
507
Duncan P. N. Exon Smith5ec15682015-10-09 19:40:45 +0000508 Scheduler.startBlock(&*MBB);
Andrew Trickedfe2ec2012-03-09 08:02:51 +0000509
Andrew Trick33e05d72013-12-28 21:57:02 +0000510#ifndef NDEBUG
511 if (SchedOnlyFunc.getNumOccurrences() && SchedOnlyFunc != MF->getName())
512 continue;
513 if (SchedOnlyBlock.getNumOccurrences()
514 && (int)SchedOnlyBlock != MBB->getNumber())
515 continue;
516#endif
517
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000518 // Break the block into scheduling regions [I, RegionEnd). RegionEnd
519 // points to the scheduling boundary at the bottom of the region. The DAG
520 // does not include RegionEnd, but the region does (i.e. the next
521 // RegionEnd is above the previous RegionBegin). If the current block has
522 // no terminator then RegionEnd == MBB->end() for the bottom region.
523 //
524 // All the regions of MBB are first found and stored in MBBRegions, which
525 // will be processed (MBB) top-down if initialized with true.
Andrew Trickaf1bee72012-03-09 22:34:56 +0000526 //
527 // The Scheduler may insert instructions during either schedule() or
528 // exitRegion(), even for empty regions. So the local iterators 'I' and
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000529 // 'RegionEnd' are invalid across these calls. Instructions must not be
530 // added to other regions than the current one without updating MBBRegions.
Andrew Trick88639922012-04-24 17:56:43 +0000531
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000532 MBBRegionsVector MBBRegions;
533 getSchedRegions(&*MBB, MBBRegions, Scheduler.doMBBSchedRegionsTopDown());
534 for (MBBRegionsVector::iterator R = MBBRegions.begin();
535 R != MBBRegions.end(); ++R) {
536 MachineBasicBlock::iterator I = R->RegionBegin;
537 MachineBasicBlock::iterator RegionEnd = R->RegionEnd;
538 unsigned NumRegionInstrs = R->NumRegionInstrs;
Andrew Trickedfe2ec2012-03-09 08:02:51 +0000539
Andrew Trick60cf03e2012-03-07 05:21:52 +0000540 // Notify the scheduler of the region, even if we may skip scheduling
541 // it. Perhaps it still needs to be bundled.
Duncan P. N. Exon Smith5ec15682015-10-09 19:40:45 +0000542 Scheduler.enterRegion(&*MBB, I, RegionEnd, NumRegionInstrs);
Andrew Trick60cf03e2012-03-07 05:21:52 +0000543
544 // Skip empty scheduling regions (0 or 1 schedulable instructions).
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000545 if (I == RegionEnd || I == std::prev(RegionEnd)) {
Andrew Trick60cf03e2012-03-07 05:21:52 +0000546 // Close the current region. Bundle the terminator if needed.
Andrew Trickaf1bee72012-03-09 22:34:56 +0000547 // This invalidates 'RegionEnd' and 'I'.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000548 Scheduler.exitRegion();
Andrew Trick7ccdc5c2012-01-17 06:55:07 +0000549 continue;
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000550 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000551 LLVM_DEBUG(dbgs() << "********** MI Scheduling **********\n");
552 LLVM_DEBUG(dbgs() << MF->getName() << ":" << printMBBReference(*MBB)
553 << " " << MBB->getName() << "\n From: " << *I
554 << " To: ";
555 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
556 else dbgs() << "End";
557 dbgs() << " RegionInstrs: " << NumRegionInstrs << '\n');
Gerolf Hoflehnerb5220dc2014-08-07 21:49:44 +0000558 if (DumpCriticalPathLength) {
559 errs() << MF->getName();
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000560 errs() << ":%bb. " << MBB->getNumber();
Gerolf Hoflehnerb5220dc2014-08-07 21:49:44 +0000561 errs() << " " << MBB->getName() << " \n";
562 }
Andrew Trick7ccdc5c2012-01-17 06:55:07 +0000563
Andrew Trick1c0ec452012-03-09 03:46:42 +0000564 // Schedule a region: possibly reorder instructions.
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000565 // This invalidates the original region iterators.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000566 Scheduler.schedule();
Andrew Trick1c0ec452012-03-09 03:46:42 +0000567
568 // Close the current region.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000569 Scheduler.exitRegion();
Andrew Trick7e120f42012-01-14 02:17:09 +0000570 }
Andrew Trickd7f890e2013-12-28 21:56:47 +0000571 Scheduler.finishBlock();
Matthias Braun93563e72015-11-03 01:53:29 +0000572 // FIXME: Ideally, no further passes should rely on kill flags. However,
573 // thumb2 size reduction is currently an exception, so the PostMIScheduler
574 // needs to do this.
575 if (FixKillFlags)
Matthias Braun868bbd42017-05-27 02:50:50 +0000576 Scheduler.fixupKills(*MBB);
Andrew Tricke77e84e2012-01-13 06:30:30 +0000577 }
Andrew Trickd7f890e2013-12-28 21:56:47 +0000578 Scheduler.finalizeSchedule();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000579}
580
Andrew Trickd7f890e2013-12-28 21:56:47 +0000581void MachineSchedulerBase::print(raw_ostream &O, const Module* m) const {
Andrew Tricke77e84e2012-01-13 06:30:30 +0000582 // unimplemented
583}
584
Aaron Ballman615eb472017-10-15 14:32:27 +0000585#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Sam Clegg705f7982017-06-21 22:19:17 +0000586LLVM_DUMP_METHOD void ReadyQueue::dump() const {
James Y Knighte72b0db2015-09-18 18:52:20 +0000587 dbgs() << "Queue " << Name << ": ";
Javed Absare3a0cc22017-06-21 09:10:10 +0000588 for (const SUnit *SU : Queue)
589 dbgs() << SU->NodeNum << " ";
Andrew Trick7a8e1002012-09-11 00:39:15 +0000590 dbgs() << "\n";
591}
Matthias Braun8c209aa2017-01-28 02:02:38 +0000592#endif
Andrew Trick8823dec2012-03-14 04:00:41 +0000593
594//===----------------------------------------------------------------------===//
Andrew Trickd7f890e2013-12-28 21:56:47 +0000595// ScheduleDAGMI - Basic machine instruction scheduling. This is
596// independent of PreRA/PostRA scheduling and involves no extra book-keeping for
597// virtual registers.
598// ===----------------------------------------------------------------------===/
Andrew Trick8823dec2012-03-14 04:00:41 +0000599
David Blaikie422b93d2014-04-21 20:32:32 +0000600// Provide a vtable anchor.
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +0000601ScheduleDAGMI::~ScheduleDAGMI() = default;
Andrew Trick44f750a2013-01-25 04:01:04 +0000602
Andrew Trick85a1d4c2013-04-24 15:54:43 +0000603bool ScheduleDAGMI::canAddEdge(SUnit *SuccSU, SUnit *PredSU) {
604 return SuccSU == &ExitSU || !Topo.IsReachable(PredSU, SuccSU);
605}
606
Andrew Tricka7714a02012-11-12 19:40:10 +0000607bool ScheduleDAGMI::addEdge(SUnit *SuccSU, const SDep &PredDep) {
Andrew Trick263280242012-11-12 19:52:20 +0000608 if (SuccSU != &ExitSU) {
609 // Do not use WillCreateCycle, it assumes SD scheduling.
610 // If Pred is reachable from Succ, then the edge creates a cycle.
611 if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
612 return false;
613 Topo.AddPred(SuccSU, PredDep.getSUnit());
614 }
Andrew Tricka7714a02012-11-12 19:40:10 +0000615 SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
616 // Return true regardless of whether a new edge needed to be inserted.
617 return true;
618}
619
Andrew Trick02a80da2012-03-08 01:41:12 +0000620/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
621/// NumPredsLeft reaches zero, release the successor node.
Andrew Trick61f1a272012-05-24 22:11:09 +0000622///
623/// FIXME: Adjust SuccSU height based on MinLatency.
Andrew Trick8823dec2012-03-14 04:00:41 +0000624void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
Andrew Trick02a80da2012-03-08 01:41:12 +0000625 SUnit *SuccSU = SuccEdge->getSUnit();
626
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000627 if (SuccEdge->isWeak()) {
628 --SuccSU->WeakPredsLeft;
Andrew Tricka7714a02012-11-12 19:40:10 +0000629 if (SuccEdge->isCluster())
630 NextClusterSucc = SuccSU;
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000631 return;
632 }
Andrew Trick02a80da2012-03-08 01:41:12 +0000633#ifndef NDEBUG
634 if (SuccSU->NumPredsLeft == 0) {
635 dbgs() << "*** Scheduling failed! ***\n";
636 SuccSU->dump(this);
637 dbgs() << " has been released too many times!\n";
Craig Topperc0196b12014-04-14 00:51:57 +0000638 llvm_unreachable(nullptr);
Andrew Trick02a80da2012-03-08 01:41:12 +0000639 }
640#endif
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000641 // SU->TopReadyCycle was set to CurrCycle when it was scheduled. However,
642 // CurrCycle may have advanced since then.
643 if (SuccSU->TopReadyCycle < SU->TopReadyCycle + SuccEdge->getLatency())
644 SuccSU->TopReadyCycle = SU->TopReadyCycle + SuccEdge->getLatency();
645
Andrew Trick02a80da2012-03-08 01:41:12 +0000646 --SuccSU->NumPredsLeft;
647 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
Andrew Trick8823dec2012-03-14 04:00:41 +0000648 SchedImpl->releaseTopNode(SuccSU);
Andrew Trick02a80da2012-03-08 01:41:12 +0000649}
650
651/// releaseSuccessors - Call releaseSucc on each of SU's successors.
Andrew Trick8823dec2012-03-14 04:00:41 +0000652void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
Javed Absare3a0cc22017-06-21 09:10:10 +0000653 for (SDep &Succ : SU->Succs)
654 releaseSucc(SU, &Succ);
Andrew Trick02a80da2012-03-08 01:41:12 +0000655}
656
Andrew Trick8823dec2012-03-14 04:00:41 +0000657/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
658/// NumSuccsLeft reaches zero, release the predecessor node.
Andrew Trick61f1a272012-05-24 22:11:09 +0000659///
660/// FIXME: Adjust PredSU height based on MinLatency.
Andrew Trick8823dec2012-03-14 04:00:41 +0000661void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
662 SUnit *PredSU = PredEdge->getSUnit();
663
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000664 if (PredEdge->isWeak()) {
665 --PredSU->WeakSuccsLeft;
Andrew Tricka7714a02012-11-12 19:40:10 +0000666 if (PredEdge->isCluster())
667 NextClusterPred = PredSU;
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000668 return;
669 }
Andrew Trick8823dec2012-03-14 04:00:41 +0000670#ifndef NDEBUG
671 if (PredSU->NumSuccsLeft == 0) {
672 dbgs() << "*** Scheduling failed! ***\n";
673 PredSU->dump(this);
674 dbgs() << " has been released too many times!\n";
Craig Topperc0196b12014-04-14 00:51:57 +0000675 llvm_unreachable(nullptr);
Andrew Trick8823dec2012-03-14 04:00:41 +0000676 }
677#endif
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000678 // SU->BotReadyCycle was set to CurrCycle when it was scheduled. However,
679 // CurrCycle may have advanced since then.
680 if (PredSU->BotReadyCycle < SU->BotReadyCycle + PredEdge->getLatency())
681 PredSU->BotReadyCycle = SU->BotReadyCycle + PredEdge->getLatency();
682
Andrew Trick8823dec2012-03-14 04:00:41 +0000683 --PredSU->NumSuccsLeft;
684 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
685 SchedImpl->releaseBottomNode(PredSU);
686}
687
688/// releasePredecessors - Call releasePred on each of SU's predecessors.
689void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
Javed Absare3a0cc22017-06-21 09:10:10 +0000690 for (SDep &Pred : SU->Preds)
691 releasePred(SU, &Pred);
Andrew Trick8823dec2012-03-14 04:00:41 +0000692}
693
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000694void ScheduleDAGMI::startBlock(MachineBasicBlock *bb) {
695 ScheduleDAGInstrs::startBlock(bb);
696 SchedImpl->enterMBB(bb);
697}
698
699void ScheduleDAGMI::finishBlock() {
700 SchedImpl->leaveMBB();
701 ScheduleDAGInstrs::finishBlock();
702}
703
Andrew Trickd7f890e2013-12-28 21:56:47 +0000704/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
705/// crossing a scheduling boundary. [begin, end) includes all instructions in
706/// the region, including the boundary itself and single-instruction regions
707/// that don't get scheduled.
708void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
709 MachineBasicBlock::iterator begin,
710 MachineBasicBlock::iterator end,
711 unsigned regioninstrs)
712{
713 ScheduleDAGInstrs::enterRegion(bb, begin, end, regioninstrs);
714
715 SchedImpl->initPolicy(begin, end, regioninstrs);
716}
717
Andrew Tricke833e1c2013-04-13 06:07:40 +0000718/// This is normally called from the main scheduler loop but may also be invoked
719/// by the scheduling strategy to perform additional code motion.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000720void ScheduleDAGMI::moveInstruction(
721 MachineInstr *MI, MachineBasicBlock::iterator InsertPos) {
Andrew Trick463b2f12012-05-17 18:35:03 +0000722 // Advance RegionBegin if the first instruction moves down.
Andrew Trick54f7def2012-03-21 04:12:10 +0000723 if (&*RegionBegin == MI)
Andrew Trick463b2f12012-05-17 18:35:03 +0000724 ++RegionBegin;
725
726 // Update the instruction stream.
Andrew Trick8823dec2012-03-14 04:00:41 +0000727 BB->splice(InsertPos, BB, MI);
Andrew Trick463b2f12012-05-17 18:35:03 +0000728
729 // Update LiveIntervals
Andrew Trickd7f890e2013-12-28 21:56:47 +0000730 if (LIS)
Duncan P. N. Exon Smithbe8f8c42016-02-27 20:14:29 +0000731 LIS->handleMove(*MI, /*UpdateFlags=*/true);
Andrew Trick463b2f12012-05-17 18:35:03 +0000732
733 // Recede RegionBegin if an instruction moves above the first.
Andrew Trick8823dec2012-03-14 04:00:41 +0000734 if (RegionBegin == InsertPos)
735 RegionBegin = MI;
736}
737
Andrew Trickde670c02012-03-21 04:12:07 +0000738bool ScheduleDAGMI::checkSchedLimit() {
739#ifndef NDEBUG
740 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
741 CurrentTop = CurrentBottom;
742 return false;
743 }
744 ++NumInstrsScheduled;
745#endif
746 return true;
747}
748
Andrew Trickd7f890e2013-12-28 21:56:47 +0000749/// Per-region scheduling driver, called back from
750/// MachineScheduler::runOnMachineFunction. This is a simplified driver that
751/// does not consider liveness or register pressure. It is useful for PostRA
752/// scheduling and potentially other custom schedulers.
753void ScheduleDAGMI::schedule() {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000754 LLVM_DEBUG(dbgs() << "ScheduleDAGMI::schedule starting\n");
755 LLVM_DEBUG(SchedImpl->dumpPolicy());
James Y Knighte72b0db2015-09-18 18:52:20 +0000756
Andrew Trickd7f890e2013-12-28 21:56:47 +0000757 // Build the DAG.
758 buildSchedGraph(AA);
759
760 Topo.InitDAGTopologicalSorting();
761
762 postprocessDAG();
763
764 SmallVector<SUnit*, 8> TopRoots, BotRoots;
765 findRootsAndBiasEdges(TopRoots, BotRoots);
766
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000767 LLVM_DEBUG(if (EntrySU.getInstr() != nullptr) EntrySU.dumpAll(this);
768 for (const SUnit &SU
769 : SUnits) SU.dumpAll(this);
770 if (ExitSU.getInstr() != nullptr) ExitSU.dumpAll(this););
Andrew Trickd7f890e2013-12-28 21:56:47 +0000771 if (ViewMISchedDAGs) viewGraph();
772
Jonas Paulssonbc32f7d2018-03-05 16:31:49 +0000773 // Initialize the strategy before modifying the DAG.
774 // This may initialize a DFSResult to be used for queue priority.
775 SchedImpl->initialize(this);
776
Andrew Trickd7f890e2013-12-28 21:56:47 +0000777 // Initialize ready queues now that the DAG and priority data are finalized.
778 initQueues(TopRoots, BotRoots);
779
780 bool IsTopNode = false;
James Y Knighte72b0db2015-09-18 18:52:20 +0000781 while (true) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000782 LLVM_DEBUG(dbgs() << "** ScheduleDAGMI::schedule picking next node\n");
James Y Knighte72b0db2015-09-18 18:52:20 +0000783 SUnit *SU = SchedImpl->pickNode(IsTopNode);
784 if (!SU) break;
785
Andrew Trickd7f890e2013-12-28 21:56:47 +0000786 assert(!SU->isScheduled && "Node already scheduled");
787 if (!checkSchedLimit())
788 break;
789
790 MachineInstr *MI = SU->getInstr();
791 if (IsTopNode) {
792 assert(SU->isTopReady() && "node still has unscheduled dependencies");
793 if (&*CurrentTop == MI)
794 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
795 else
796 moveInstruction(MI, CurrentTop);
Matthias Braunb550b762016-04-21 01:54:13 +0000797 } else {
Andrew Trickd7f890e2013-12-28 21:56:47 +0000798 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
799 MachineBasicBlock::iterator priorII =
800 priorNonDebug(CurrentBottom, CurrentTop);
801 if (&*priorII == MI)
802 CurrentBottom = priorII;
803 else {
804 if (&*CurrentTop == MI)
805 CurrentTop = nextIfDebug(++CurrentTop, priorII);
806 moveInstruction(MI, CurrentBottom);
807 CurrentBottom = MI;
808 }
809 }
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000810 // Notify the scheduling strategy before updating the DAG.
Andrew Trick491e34a2014-06-12 22:36:28 +0000811 // This sets the scheduled node's ReadyCycle to CurrCycle. When updateQueues
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000812 // runs, it can then use the accurate ReadyCycle time to determine whether
813 // newly released nodes can move to the readyQ.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000814 SchedImpl->schedNode(SU, IsTopNode);
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000815
816 updateQueues(SU, IsTopNode);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000817 }
818 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
819
820 placeDebugValues();
821
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000822 LLVM_DEBUG({
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000823 dbgs() << "*** Final schedule for "
824 << printMBBReference(*begin()->getParent()) << " ***\n";
825 dumpSchedule();
826 dbgs() << '\n';
827 });
Andrew Trickd7f890e2013-12-28 21:56:47 +0000828}
829
830/// Apply each ScheduleDAGMutation step in order.
831void ScheduleDAGMI::postprocessDAG() {
Javed Absare3a0cc22017-06-21 09:10:10 +0000832 for (auto &m : Mutations)
833 m->apply(this);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000834}
835
836void ScheduleDAGMI::
837findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
838 SmallVectorImpl<SUnit*> &BotRoots) {
Javed Absare3a0cc22017-06-21 09:10:10 +0000839 for (SUnit &SU : SUnits) {
840 assert(!SU.isBoundaryNode() && "Boundary node should not be in SUnits");
Andrew Trickd7f890e2013-12-28 21:56:47 +0000841
842 // Order predecessors so DFSResult follows the critical path.
Javed Absare3a0cc22017-06-21 09:10:10 +0000843 SU.biasCriticalPath();
Andrew Trickd7f890e2013-12-28 21:56:47 +0000844
845 // A SUnit is ready to top schedule if it has no predecessors.
Javed Absare3a0cc22017-06-21 09:10:10 +0000846 if (!SU.NumPredsLeft)
847 TopRoots.push_back(&SU);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000848 // A SUnit is ready to bottom schedule if it has no successors.
Javed Absare3a0cc22017-06-21 09:10:10 +0000849 if (!SU.NumSuccsLeft)
850 BotRoots.push_back(&SU);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000851 }
852 ExitSU.biasCriticalPath();
853}
854
855/// Identify DAG roots and setup scheduler queues.
856void ScheduleDAGMI::initQueues(ArrayRef<SUnit*> TopRoots,
857 ArrayRef<SUnit*> BotRoots) {
Craig Topperc0196b12014-04-14 00:51:57 +0000858 NextClusterSucc = nullptr;
859 NextClusterPred = nullptr;
Andrew Trickd7f890e2013-12-28 21:56:47 +0000860
861 // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
862 //
863 // Nodes with unreleased weak edges can still be roots.
864 // Release top roots in forward order.
Javed Absare3a0cc22017-06-21 09:10:10 +0000865 for (SUnit *SU : TopRoots)
866 SchedImpl->releaseTopNode(SU);
867
Andrew Trickd7f890e2013-12-28 21:56:47 +0000868 // Release bottom roots in reverse order so the higher priority nodes appear
869 // first. This is more natural and slightly more efficient.
870 for (SmallVectorImpl<SUnit*>::const_reverse_iterator
871 I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I) {
872 SchedImpl->releaseBottomNode(*I);
873 }
874
875 releaseSuccessors(&EntrySU);
876 releasePredecessors(&ExitSU);
877
878 SchedImpl->registerRoots();
879
880 // Advance past initial DebugValues.
881 CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
882 CurrentBottom = RegionEnd;
883}
884
885/// Update scheduler queues after scheduling an instruction.
886void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
887 // Release dependent instructions for scheduling.
888 if (IsTopNode)
889 releaseSuccessors(SU);
890 else
891 releasePredecessors(SU);
892
893 SU->isScheduled = true;
894}
895
896/// Reinsert any remaining debug_values, just like the PostRA scheduler.
897void ScheduleDAGMI::placeDebugValues() {
898 // If first instruction was a DBG_VALUE then put it back.
899 if (FirstDbgValue) {
900 BB->splice(RegionBegin, BB, FirstDbgValue);
901 RegionBegin = FirstDbgValue;
902 }
903
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +0000904 for (std::vector<std::pair<MachineInstr *, MachineInstr *>>::iterator
Andrew Trickd7f890e2013-12-28 21:56:47 +0000905 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000906 std::pair<MachineInstr *, MachineInstr *> P = *std::prev(DI);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000907 MachineInstr *DbgValue = P.first;
908 MachineBasicBlock::iterator OrigPrevMI = P.second;
909 if (&*RegionBegin == DbgValue)
910 ++RegionBegin;
911 BB->splice(++OrigPrevMI, BB, DbgValue);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000912 if (OrigPrevMI == std::prev(RegionEnd))
Andrew Trickd7f890e2013-12-28 21:56:47 +0000913 RegionEnd = DbgValue;
914 }
915 DbgValues.clear();
Craig Topperc0196b12014-04-14 00:51:57 +0000916 FirstDbgValue = nullptr;
Andrew Trickd7f890e2013-12-28 21:56:47 +0000917}
918
Aaron Ballman615eb472017-10-15 14:32:27 +0000919#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Matthias Braun8c209aa2017-01-28 02:02:38 +0000920LLVM_DUMP_METHOD void ScheduleDAGMI::dumpSchedule() const {
Andrew Trickd7f890e2013-12-28 21:56:47 +0000921 for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
922 if (SUnit *SU = getSUnit(&(*MI)))
923 SU->dump(this);
924 else
925 dbgs() << "Missing SUnit\n";
926 }
927}
928#endif
929
930//===----------------------------------------------------------------------===//
931// ScheduleDAGMILive - Base class for MachineInstr scheduling with LiveIntervals
932// preservation.
933//===----------------------------------------------------------------------===//
934
935ScheduleDAGMILive::~ScheduleDAGMILive() {
936 delete DFSResult;
937}
938
Matthias Braun40639882016-11-11 22:37:31 +0000939void ScheduleDAGMILive::collectVRegUses(SUnit &SU) {
940 const MachineInstr &MI = *SU.getInstr();
941 for (const MachineOperand &MO : MI.operands()) {
942 if (!MO.isReg())
943 continue;
944 if (!MO.readsReg())
945 continue;
946 if (TrackLaneMasks && !MO.isUse())
947 continue;
948
949 unsigned Reg = MO.getReg();
950 if (!TargetRegisterInfo::isVirtualRegister(Reg))
951 continue;
952
953 // Ignore re-defs.
954 if (TrackLaneMasks) {
955 bool FoundDef = false;
956 for (const MachineOperand &MO2 : MI.operands()) {
957 if (MO2.isReg() && MO2.isDef() && MO2.getReg() == Reg && !MO2.isDead()) {
958 FoundDef = true;
959 break;
960 }
961 }
962 if (FoundDef)
963 continue;
964 }
965
966 // Record this local VReg use.
967 VReg2SUnitMultiMap::iterator UI = VRegUses.find(Reg);
968 for (; UI != VRegUses.end(); ++UI) {
969 if (UI->SU == &SU)
970 break;
971 }
972 if (UI == VRegUses.end())
Krzysztof Parzyszek91b5cf82016-12-15 14:36:06 +0000973 VRegUses.insert(VReg2SUnit(Reg, LaneBitmask::getNone(), &SU));
Matthias Braun40639882016-11-11 22:37:31 +0000974 }
975}
976
Andrew Trick88639922012-04-24 17:56:43 +0000977/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
978/// crossing a scheduling boundary. [begin, end) includes all instructions in
979/// the region, including the boundary itself and single-instruction regions
980/// that don't get scheduled.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000981void ScheduleDAGMILive::enterRegion(MachineBasicBlock *bb,
Andrew Trick88639922012-04-24 17:56:43 +0000982 MachineBasicBlock::iterator begin,
983 MachineBasicBlock::iterator end,
Andrew Tricka53e1012013-08-23 17:48:33 +0000984 unsigned regioninstrs)
Andrew Trick88639922012-04-24 17:56:43 +0000985{
Andrew Trickd7f890e2013-12-28 21:56:47 +0000986 // ScheduleDAGMI initializes SchedImpl's per-region policy.
987 ScheduleDAGMI::enterRegion(bb, begin, end, regioninstrs);
Andrew Trick4add42f2012-05-10 21:06:10 +0000988
989 // For convenience remember the end of the liveness region.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000990 LiveRegionEnd = (RegionEnd == bb->end()) ? RegionEnd : std::next(RegionEnd);
Andrew Trick75e411c2013-09-06 17:32:34 +0000991
Andrew Trickb248b4a2013-09-06 17:32:47 +0000992 SUPressureDiffs.clear();
993
Andrew Trick75e411c2013-09-06 17:32:34 +0000994 ShouldTrackPressure = SchedImpl->shouldTrackPressure();
Matthias Braund4f64092016-01-20 00:23:32 +0000995 ShouldTrackLaneMasks = SchedImpl->shouldTrackLaneMasks();
996
Matthias Braunf9acaca2016-05-31 22:38:06 +0000997 assert((!ShouldTrackLaneMasks || ShouldTrackPressure) &&
998 "ShouldTrackLaneMasks requires ShouldTrackPressure");
Andrew Trick4add42f2012-05-10 21:06:10 +0000999}
1000
1001// Setup the register pressure trackers for the top scheduled top and bottom
1002// scheduled regions.
Andrew Trickd7f890e2013-12-28 21:56:47 +00001003void ScheduleDAGMILive::initRegPressure() {
Matthias Braun40639882016-11-11 22:37:31 +00001004 VRegUses.clear();
1005 VRegUses.setUniverse(MRI.getNumVirtRegs());
1006 for (SUnit &SU : SUnits)
1007 collectVRegUses(SU);
1008
Matthias Braund4f64092016-01-20 00:23:32 +00001009 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin,
1010 ShouldTrackLaneMasks, false);
1011 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
1012 ShouldTrackLaneMasks, false);
Andrew Trick4add42f2012-05-10 21:06:10 +00001013
1014 // Close the RPTracker to finalize live ins.
1015 RPTracker.closeRegion();
1016
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001017 LLVM_DEBUG(RPTracker.dump());
Andrew Trick79d3eec2012-05-24 22:11:14 +00001018
Andrew Trick4add42f2012-05-10 21:06:10 +00001019 // Initialize the live ins and live outs.
Matthias Braun3e86de12015-09-17 21:12:24 +00001020 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
1021 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
Andrew Trick4add42f2012-05-10 21:06:10 +00001022
1023 // Close one end of the tracker so we can call
1024 // getMaxUpward/DownwardPressureDelta before advancing across any
1025 // instructions. This converts currently live regs into live ins/outs.
1026 TopRPTracker.closeTop();
1027 BotRPTracker.closeBottom();
1028
Andrew Trick9c17eab2013-07-30 19:59:12 +00001029 BotRPTracker.initLiveThru(RPTracker);
1030 if (!BotRPTracker.getLiveThru().empty()) {
1031 TopRPTracker.initLiveThru(BotRPTracker.getLiveThru());
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001032 LLVM_DEBUG(dbgs() << "Live Thru: ";
1033 dumpRegSetPressure(BotRPTracker.getLiveThru(), TRI));
Andrew Trick9c17eab2013-07-30 19:59:12 +00001034 };
1035
Andrew Trick2bc74c22013-08-30 04:36:57 +00001036 // For each live out vreg reduce the pressure change associated with other
1037 // uses of the same vreg below the live-out reaching def.
Matthias Braun3e86de12015-09-17 21:12:24 +00001038 updatePressureDiffs(RPTracker.getPressure().LiveOutRegs);
Andrew Trick2bc74c22013-08-30 04:36:57 +00001039
Andrew Trick4add42f2012-05-10 21:06:10 +00001040 // Account for liveness generated by the region boundary.
Andrew Trick2bc74c22013-08-30 04:36:57 +00001041 if (LiveRegionEnd != RegionEnd) {
Matthias Braun5d458612016-01-20 00:23:26 +00001042 SmallVector<RegisterMaskPair, 8> LiveUses;
Andrew Trick2bc74c22013-08-30 04:36:57 +00001043 BotRPTracker.recede(&LiveUses);
1044 updatePressureDiffs(LiveUses);
1045 }
Andrew Trick4add42f2012-05-10 21:06:10 +00001046
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001047 LLVM_DEBUG(dbgs() << "Top Pressure:\n";
1048 dumpRegSetPressure(TopRPTracker.getRegSetPressureAtPos(), TRI);
1049 dbgs() << "Bottom Pressure:\n";
1050 dumpRegSetPressure(BotRPTracker.getRegSetPressureAtPos(), TRI););
Matthias Braune6edd482015-11-13 22:30:31 +00001051
Yaxun Liuc41e2f62017-12-15 03:56:57 +00001052 assert((BotRPTracker.getPos() == RegionEnd ||
Shiva Chen801bf7e2018-05-09 02:42:00 +00001053 (RegionEnd->isDebugInstr() &&
Yaxun Liuc41e2f62017-12-15 03:56:57 +00001054 BotRPTracker.getPos() == priorNonDebug(RegionEnd, RegionBegin))) &&
1055 "Can't find the region bottom");
Andrew Trick22025772012-05-17 18:35:10 +00001056
1057 // Cache the list of excess pressure sets in this region. This will also track
1058 // the max pressure in the scheduled code for these sets.
1059 RegionCriticalPSets.clear();
Jakub Staszakc641ada2013-01-25 21:44:27 +00001060 const std::vector<unsigned> &RegionPressure =
1061 RPTracker.getPressure().MaxSetPressure;
Andrew Trick22025772012-05-17 18:35:10 +00001062 for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
Andrew Trick736dd9a2013-06-21 18:32:58 +00001063 unsigned Limit = RegClassInfo->getRegPressureSetLimit(i);
Andrew Trickb55db582013-06-21 18:33:01 +00001064 if (RegionPressure[i] > Limit) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001065 LLVM_DEBUG(dbgs() << TRI->getRegPressureSetName(i) << " Limit " << Limit
1066 << " Actual " << RegionPressure[i] << "\n");
Andrew Trick1a831342013-08-30 03:49:48 +00001067 RegionCriticalPSets.push_back(PressureChange(i));
Andrew Trickb55db582013-06-21 18:33:01 +00001068 }
Andrew Trick22025772012-05-17 18:35:10 +00001069 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001070 LLVM_DEBUG(dbgs() << "Excess PSets: ";
1071 for (const PressureChange &RCPS
1072 : RegionCriticalPSets) dbgs()
1073 << TRI->getRegPressureSetName(RCPS.getPSet()) << " ";
1074 dbgs() << "\n");
Andrew Trick22025772012-05-17 18:35:10 +00001075}
1076
Andrew Trickd7f890e2013-12-28 21:56:47 +00001077void ScheduleDAGMILive::
Andrew Trickb248b4a2013-09-06 17:32:47 +00001078updateScheduledPressure(const SUnit *SU,
1079 const std::vector<unsigned> &NewMaxPressure) {
1080 const PressureDiff &PDiff = getPressureDiff(SU);
1081 unsigned CritIdx = 0, CritEnd = RegionCriticalPSets.size();
Javed Absare3a0cc22017-06-21 09:10:10 +00001082 for (const PressureChange &PC : PDiff) {
1083 if (!PC.isValid())
Andrew Trickb248b4a2013-09-06 17:32:47 +00001084 break;
Javed Absare3a0cc22017-06-21 09:10:10 +00001085 unsigned ID = PC.getPSet();
Andrew Trickb248b4a2013-09-06 17:32:47 +00001086 while (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() < ID)
1087 ++CritIdx;
1088 if (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() == ID) {
1089 if ((int)NewMaxPressure[ID] > RegionCriticalPSets[CritIdx].getUnitInc()
Simon Pilgrim858d8e62017-02-23 12:00:34 +00001090 && NewMaxPressure[ID] <= (unsigned)std::numeric_limits<int16_t>::max())
Andrew Trickb248b4a2013-09-06 17:32:47 +00001091 RegionCriticalPSets[CritIdx].setUnitInc(NewMaxPressure[ID]);
1092 }
1093 unsigned Limit = RegClassInfo->getRegPressureSetLimit(ID);
1094 if (NewMaxPressure[ID] >= Limit - 2) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001095 LLVM_DEBUG(dbgs() << " " << TRI->getRegPressureSetName(ID) << ": "
1096 << NewMaxPressure[ID]
1097 << ((NewMaxPressure[ID] > Limit) ? " > " : " <= ")
1098 << Limit << "(+ " << BotRPTracker.getLiveThru()[ID]
1099 << " livethru)\n");
Andrew Trickb248b4a2013-09-06 17:32:47 +00001100 }
Andrew Trick22025772012-05-17 18:35:10 +00001101 }
Andrew Trick88639922012-04-24 17:56:43 +00001102}
1103
Andrew Trick2bc74c22013-08-30 04:36:57 +00001104/// Update the PressureDiff array for liveness after scheduling this
1105/// instruction.
Matthias Braun5d458612016-01-20 00:23:26 +00001106void ScheduleDAGMILive::updatePressureDiffs(
1107 ArrayRef<RegisterMaskPair> LiveUses) {
1108 for (const RegisterMaskPair &P : LiveUses) {
Matthias Braun5d458612016-01-20 00:23:26 +00001109 unsigned Reg = P.RegUnit;
Matthias Braund4f64092016-01-20 00:23:32 +00001110 /// FIXME: Currently assuming single-use physregs.
Andrew Trick2bc74c22013-08-30 04:36:57 +00001111 if (!TRI->isVirtualRegister(Reg))
1112 continue;
Andrew Trickffdbefb2013-09-06 17:32:39 +00001113
Matthias Braund4f64092016-01-20 00:23:32 +00001114 if (ShouldTrackLaneMasks) {
1115 // If the register has just become live then other uses won't change
1116 // this fact anymore => decrement pressure.
1117 // If the register has just become dead then other uses make it come
1118 // back to life => increment pressure.
Krzysztof Parzyszekea9f8ce2016-12-16 19:11:56 +00001119 bool Decrement = P.LaneMask.any();
Matthias Braund4f64092016-01-20 00:23:32 +00001120
1121 for (const VReg2SUnit &V2SU
1122 : make_range(VRegUses.find(Reg), VRegUses.end())) {
1123 SUnit &SU = *V2SU.SU;
1124 if (SU.isScheduled || &SU == &ExitSU)
1125 continue;
1126
1127 PressureDiff &PDiff = getPressureDiff(&SU);
Stanislav Mekhanoshin42259cf2017-02-24 21:56:16 +00001128 PDiff.addPressureChange(Reg, Decrement, &MRI);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001129 LLVM_DEBUG(dbgs() << " UpdateRegP: SU(" << SU.NodeNum << ") "
1130 << printReg(Reg, TRI) << ':'
1131 << PrintLaneMask(P.LaneMask) << ' ' << *SU.getInstr();
1132 dbgs() << " to "; PDiff.dump(*TRI););
Matthias Braund4f64092016-01-20 00:23:32 +00001133 }
1134 } else {
Krzysztof Parzyszekea9f8ce2016-12-16 19:11:56 +00001135 assert(P.LaneMask.any());
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001136 LLVM_DEBUG(dbgs() << " LiveReg: " << printVRegOrUnit(Reg, TRI) << "\n");
Matthias Braund4f64092016-01-20 00:23:32 +00001137 // This may be called before CurrentBottom has been initialized. However,
1138 // BotRPTracker must have a valid position. We want the value live into the
1139 // instruction or live out of the block, so ask for the previous
1140 // instruction's live-out.
1141 const LiveInterval &LI = LIS->getInterval(Reg);
1142 VNInfo *VNI;
1143 MachineBasicBlock::const_iterator I =
1144 nextIfDebug(BotRPTracker.getPos(), BB->end());
1145 if (I == BB->end())
1146 VNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
1147 else {
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001148 LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(*I));
Matthias Braund4f64092016-01-20 00:23:32 +00001149 VNI = LRQ.valueIn();
1150 }
1151 // RegisterPressureTracker guarantees that readsReg is true for LiveUses.
1152 assert(VNI && "No live value at use.");
1153 for (const VReg2SUnit &V2SU
1154 : make_range(VRegUses.find(Reg), VRegUses.end())) {
1155 SUnit *SU = V2SU.SU;
1156 // If this use comes before the reaching def, it cannot be a last use,
1157 // so decrease its pressure change.
1158 if (!SU->isScheduled && SU != &ExitSU) {
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001159 LiveQueryResult LRQ =
1160 LI.Query(LIS->getInstructionIndex(*SU->getInstr()));
Matthias Braund4f64092016-01-20 00:23:32 +00001161 if (LRQ.valueIn() == VNI) {
1162 PressureDiff &PDiff = getPressureDiff(SU);
Stanislav Mekhanoshin42259cf2017-02-24 21:56:16 +00001163 PDiff.addPressureChange(Reg, true, &MRI);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001164 LLVM_DEBUG(dbgs() << " UpdateRegP: SU(" << SU->NodeNum << ") "
1165 << *SU->getInstr();
1166 dbgs() << " to "; PDiff.dump(*TRI););
Matthias Braund4f64092016-01-20 00:23:32 +00001167 }
Matthias Braun9198c672015-11-06 20:59:02 +00001168 }
Andrew Trick2bc74c22013-08-30 04:36:57 +00001169 }
1170 }
1171 }
1172}
1173
Andrew Trick8823dec2012-03-14 04:00:41 +00001174/// schedule - Called back from MachineScheduler::runOnMachineFunction
Andrew Trick88639922012-04-24 17:56:43 +00001175/// after setting up the current scheduling region. [RegionBegin, RegionEnd)
1176/// only includes instructions that have DAG nodes, not scheduling boundaries.
Andrew Trick7a8e1002012-09-11 00:39:15 +00001177///
1178/// This is a skeletal driver, with all the functionality pushed into helpers,
Nick Lewycky06b0ea22015-08-18 22:41:58 +00001179/// so that it can be easily extended by experimental schedulers. Generally,
Andrew Trick7a8e1002012-09-11 00:39:15 +00001180/// implementing MachineSchedStrategy should be sufficient to implement a new
1181/// scheduling algorithm. However, if a scheduler further subclasses
Andrew Trickd7f890e2013-12-28 21:56:47 +00001182/// ScheduleDAGMILive then it will want to override this virtual method in order
1183/// to update any specialized state.
1184void ScheduleDAGMILive::schedule() {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001185 LLVM_DEBUG(dbgs() << "ScheduleDAGMILive::schedule starting\n");
1186 LLVM_DEBUG(SchedImpl->dumpPolicy());
Andrew Trick7a8e1002012-09-11 00:39:15 +00001187 buildDAGWithRegPressure();
1188
Andrew Tricka7714a02012-11-12 19:40:10 +00001189 Topo.InitDAGTopologicalSorting();
1190
Andrew Tricka2733e92012-09-14 17:22:42 +00001191 postprocessDAG();
1192
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001193 SmallVector<SUnit*, 8> TopRoots, BotRoots;
1194 findRootsAndBiasEdges(TopRoots, BotRoots);
1195
1196 // Initialize the strategy before modifying the DAG.
1197 // This may initialize a DFSResult to be used for queue priority.
1198 SchedImpl->initialize(this);
1199
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001200 LLVM_DEBUG(if (EntrySU.getInstr() != nullptr) EntrySU.dumpAll(this);
1201 for (const SUnit &SU
1202 : SUnits) {
1203 SU.dumpAll(this);
1204 if (ShouldTrackPressure) {
1205 dbgs() << " Pressure Diff : ";
1206 getPressureDiff(&SU).dump(*TRI);
1207 }
1208 dbgs() << " Single Issue : ";
1209 if (SchedModel.mustBeginGroup(SU.getInstr()) &&
1210 SchedModel.mustEndGroup(SU.getInstr()))
1211 dbgs() << "true;";
1212 else
1213 dbgs() << "false;";
1214 dbgs() << '\n';
1215 } if (ExitSU.getInstr() != nullptr) ExitSU.dumpAll(this););
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001216 if (ViewMISchedDAGs) viewGraph();
Andrew Trick7a8e1002012-09-11 00:39:15 +00001217
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001218 // Initialize ready queues now that the DAG and priority data are finalized.
1219 initQueues(TopRoots, BotRoots);
Andrew Trick7a8e1002012-09-11 00:39:15 +00001220
1221 bool IsTopNode = false;
James Y Knighte72b0db2015-09-18 18:52:20 +00001222 while (true) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001223 LLVM_DEBUG(dbgs() << "** ScheduleDAGMILive::schedule picking next node\n");
James Y Knighte72b0db2015-09-18 18:52:20 +00001224 SUnit *SU = SchedImpl->pickNode(IsTopNode);
1225 if (!SU) break;
1226
Andrew Trick984d98b2012-10-08 18:53:53 +00001227 assert(!SU->isScheduled && "Node already scheduled");
Andrew Trick7a8e1002012-09-11 00:39:15 +00001228 if (!checkSchedLimit())
1229 break;
1230
1231 scheduleMI(SU, IsTopNode);
1232
Andrew Trickd7f890e2013-12-28 21:56:47 +00001233 if (DFSResult) {
1234 unsigned SubtreeID = DFSResult->getSubtreeID(SU);
1235 if (!ScheduledTrees.test(SubtreeID)) {
1236 ScheduledTrees.set(SubtreeID);
1237 DFSResult->scheduleTree(SubtreeID);
1238 SchedImpl->scheduleTree(SubtreeID);
1239 }
1240 }
1241
1242 // Notify the scheduling strategy after updating the DAG.
1243 SchedImpl->schedNode(SU, IsTopNode);
Andrew Trick43adfb32015-03-27 06:10:13 +00001244
1245 updateQueues(SU, IsTopNode);
Andrew Trick7a8e1002012-09-11 00:39:15 +00001246 }
1247 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
1248
1249 placeDebugValues();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001250
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001251 LLVM_DEBUG({
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +00001252 dbgs() << "*** Final schedule for "
1253 << printMBBReference(*begin()->getParent()) << " ***\n";
1254 dumpSchedule();
1255 dbgs() << '\n';
1256 });
Andrew Trick7a8e1002012-09-11 00:39:15 +00001257}
1258
1259/// Build the DAG and setup three register pressure trackers.
Andrew Trickd7f890e2013-12-28 21:56:47 +00001260void ScheduleDAGMILive::buildDAGWithRegPressure() {
Andrew Trickb6e74712013-09-04 20:59:59 +00001261 if (!ShouldTrackPressure) {
1262 RPTracker.reset();
1263 RegionCriticalPSets.clear();
1264 buildSchedGraph(AA);
1265 return;
1266 }
1267
Andrew Trick4add42f2012-05-10 21:06:10 +00001268 // Initialize the register pressure tracker used by buildSchedGraph.
Andrew Trick9c17eab2013-07-30 19:59:12 +00001269 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
Matthias Braund4f64092016-01-20 00:23:32 +00001270 ShouldTrackLaneMasks, /*TrackUntiedDefs=*/true);
Andrew Trick88639922012-04-24 17:56:43 +00001271
Andrew Trick4add42f2012-05-10 21:06:10 +00001272 // Account for liveness generate by the region boundary.
1273 if (LiveRegionEnd != RegionEnd)
1274 RPTracker.recede();
1275
1276 // Build the DAG, and compute current register pressure.
Matthias Braund4f64092016-01-20 00:23:32 +00001277 buildSchedGraph(AA, &RPTracker, &SUPressureDiffs, LIS, ShouldTrackLaneMasks);
Andrew Trick02a80da2012-03-08 01:41:12 +00001278
Andrew Trick4add42f2012-05-10 21:06:10 +00001279 // Initialize top/bottom trackers after computing region pressure.
1280 initRegPressure();
Andrew Trick7a8e1002012-09-11 00:39:15 +00001281}
Andrew Trick4add42f2012-05-10 21:06:10 +00001282
Andrew Trickd7f890e2013-12-28 21:56:47 +00001283void ScheduleDAGMILive::computeDFSResult() {
Andrew Trick44f750a2013-01-25 04:01:04 +00001284 if (!DFSResult)
1285 DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize);
1286 DFSResult->clear();
Andrew Trick44f750a2013-01-25 04:01:04 +00001287 ScheduledTrees.clear();
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001288 DFSResult->resize(SUnits.size());
1289 DFSResult->compute(SUnits);
Andrew Trick44f750a2013-01-25 04:01:04 +00001290 ScheduledTrees.resize(DFSResult->getNumSubtrees());
1291}
1292
Andrew Trick483f4192013-08-29 18:04:49 +00001293/// Compute the max cyclic critical path through the DAG. The scheduling DAG
1294/// only provides the critical path for single block loops. To handle loops that
1295/// span blocks, we could use the vreg path latencies provided by
1296/// MachineTraceMetrics instead. However, MachineTraceMetrics is not currently
1297/// available for use in the scheduler.
1298///
1299/// The cyclic path estimation identifies a def-use pair that crosses the back
Andrew Trickef80f502013-08-30 02:02:12 +00001300/// edge and considers the depth and height of the nodes. For example, consider
Andrew Trick483f4192013-08-29 18:04:49 +00001301/// the following instruction sequence where each instruction has unit latency
1302/// and defines an epomymous virtual register:
1303///
1304/// a->b(a,c)->c(b)->d(c)->exit
1305///
1306/// The cyclic critical path is a two cycles: b->c->b
1307/// The acyclic critical path is four cycles: a->b->c->d->exit
1308/// LiveOutHeight = height(c) = len(c->d->exit) = 2
1309/// LiveOutDepth = depth(c) + 1 = len(a->b->c) + 1 = 3
1310/// LiveInHeight = height(b) + 1 = len(b->c->d->exit) + 1 = 4
1311/// LiveInDepth = depth(b) = len(a->b) = 1
1312///
1313/// LiveOutDepth - LiveInDepth = 3 - 1 = 2
1314/// LiveInHeight - LiveOutHeight = 4 - 2 = 2
1315/// CyclicCriticalPath = min(2, 2) = 2
Andrew Trickd7f890e2013-12-28 21:56:47 +00001316///
1317/// This could be relevant to PostRA scheduling, but is currently implemented
1318/// assuming LiveIntervals.
1319unsigned ScheduleDAGMILive::computeCyclicCriticalPath() {
Andrew Trick483f4192013-08-29 18:04:49 +00001320 // This only applies to single block loop.
1321 if (!BB->isSuccessor(BB))
1322 return 0;
1323
1324 unsigned MaxCyclicLatency = 0;
1325 // Visit each live out vreg def to find def/use pairs that cross iterations.
Matthias Braun5d458612016-01-20 00:23:26 +00001326 for (const RegisterMaskPair &P : RPTracker.getPressure().LiveOutRegs) {
1327 unsigned Reg = P.RegUnit;
Andrew Trick483f4192013-08-29 18:04:49 +00001328 if (!TRI->isVirtualRegister(Reg))
1329 continue;
1330 const LiveInterval &LI = LIS->getInterval(Reg);
1331 const VNInfo *DefVNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
1332 if (!DefVNI)
1333 continue;
1334
1335 MachineInstr *DefMI = LIS->getInstructionFromIndex(DefVNI->def);
1336 const SUnit *DefSU = getSUnit(DefMI);
1337 if (!DefSU)
1338 continue;
1339
1340 unsigned LiveOutHeight = DefSU->getHeight();
1341 unsigned LiveOutDepth = DefSU->getDepth() + DefSU->Latency;
1342 // Visit all local users of the vreg def.
Matthias Braunb0c437b2015-10-29 03:57:17 +00001343 for (const VReg2SUnit &V2SU
1344 : make_range(VRegUses.find(Reg), VRegUses.end())) {
1345 SUnit *SU = V2SU.SU;
1346 if (SU == &ExitSU)
Andrew Trick483f4192013-08-29 18:04:49 +00001347 continue;
1348
1349 // Only consider uses of the phi.
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001350 LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(*SU->getInstr()));
Andrew Trick483f4192013-08-29 18:04:49 +00001351 if (!LRQ.valueIn()->isPHIDef())
1352 continue;
1353
1354 // Assume that a path spanning two iterations is a cycle, which could
1355 // overestimate in strange cases. This allows cyclic latency to be
1356 // estimated as the minimum slack of the vreg's depth or height.
1357 unsigned CyclicLatency = 0;
Matthias Braunb0c437b2015-10-29 03:57:17 +00001358 if (LiveOutDepth > SU->getDepth())
1359 CyclicLatency = LiveOutDepth - SU->getDepth();
Andrew Trick483f4192013-08-29 18:04:49 +00001360
Matthias Braunb0c437b2015-10-29 03:57:17 +00001361 unsigned LiveInHeight = SU->getHeight() + DefSU->Latency;
Andrew Trick483f4192013-08-29 18:04:49 +00001362 if (LiveInHeight > LiveOutHeight) {
1363 if (LiveInHeight - LiveOutHeight < CyclicLatency)
1364 CyclicLatency = LiveInHeight - LiveOutHeight;
Matthias Braunb550b762016-04-21 01:54:13 +00001365 } else
Andrew Trick483f4192013-08-29 18:04:49 +00001366 CyclicLatency = 0;
1367
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001368 LLVM_DEBUG(dbgs() << "Cyclic Path: SU(" << DefSU->NodeNum << ") -> SU("
1369 << SU->NodeNum << ") = " << CyclicLatency << "c\n");
Andrew Trick483f4192013-08-29 18:04:49 +00001370 if (CyclicLatency > MaxCyclicLatency)
1371 MaxCyclicLatency = CyclicLatency;
1372 }
1373 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001374 LLVM_DEBUG(dbgs() << "Cyclic Critical Path: " << MaxCyclicLatency << "c\n");
Andrew Trick483f4192013-08-29 18:04:49 +00001375 return MaxCyclicLatency;
1376}
1377
Krzysztof Parzyszek7ea9a522016-04-28 19:17:44 +00001378/// Release ExitSU predecessors and setup scheduler queues. Re-position
1379/// the Top RP tracker in case the region beginning has changed.
1380void ScheduleDAGMILive::initQueues(ArrayRef<SUnit*> TopRoots,
1381 ArrayRef<SUnit*> BotRoots) {
1382 ScheduleDAGMI::initQueues(TopRoots, BotRoots);
1383 if (ShouldTrackPressure) {
1384 assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
1385 TopRPTracker.setPos(CurrentTop);
1386 }
1387}
1388
Andrew Trick7a8e1002012-09-11 00:39:15 +00001389/// Move an instruction and update register pressure.
Andrew Trickd7f890e2013-12-28 21:56:47 +00001390void ScheduleDAGMILive::scheduleMI(SUnit *SU, bool IsTopNode) {
Andrew Trick7a8e1002012-09-11 00:39:15 +00001391 // Move the instruction to its new location in the instruction stream.
1392 MachineInstr *MI = SU->getInstr();
Andrew Trick02a80da2012-03-08 01:41:12 +00001393
Andrew Trick7a8e1002012-09-11 00:39:15 +00001394 if (IsTopNode) {
1395 assert(SU->isTopReady() && "node still has unscheduled dependencies");
1396 if (&*CurrentTop == MI)
1397 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
Andrew Trick8823dec2012-03-14 04:00:41 +00001398 else {
Andrew Trick7a8e1002012-09-11 00:39:15 +00001399 moveInstruction(MI, CurrentTop);
1400 TopRPTracker.setPos(MI);
Andrew Trick8823dec2012-03-14 04:00:41 +00001401 }
Andrew Trickc3ea0052012-04-24 18:04:37 +00001402
Andrew Trickb6e74712013-09-04 20:59:59 +00001403 if (ShouldTrackPressure) {
1404 // Update top scheduled pressure.
Matthias Braund4f64092016-01-20 00:23:32 +00001405 RegisterOperands RegOpers;
1406 RegOpers.collect(*MI, *TRI, MRI, ShouldTrackLaneMasks, false);
1407 if (ShouldTrackLaneMasks) {
1408 // Adjust liveness and add missing dead+read-undef flags.
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001409 SlotIndex SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot();
Matthias Braund4f64092016-01-20 00:23:32 +00001410 RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx, MI);
1411 } else {
1412 // Adjust for missing dead-def flags.
1413 RegOpers.detectDeadDefs(*MI, *LIS);
1414 }
1415
1416 TopRPTracker.advance(RegOpers);
Andrew Trickb6e74712013-09-04 20:59:59 +00001417 assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001418 LLVM_DEBUG(dbgs() << "Top Pressure:\n"; dumpRegSetPressure(
1419 TopRPTracker.getRegSetPressureAtPos(), TRI););
Matthias Braun9198c672015-11-06 20:59:02 +00001420
Andrew Trickb248b4a2013-09-06 17:32:47 +00001421 updateScheduledPressure(SU, TopRPTracker.getPressure().MaxSetPressure);
Andrew Trickb6e74712013-09-04 20:59:59 +00001422 }
Matthias Braunb550b762016-04-21 01:54:13 +00001423 } else {
Andrew Trick7a8e1002012-09-11 00:39:15 +00001424 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
1425 MachineBasicBlock::iterator priorII =
1426 priorNonDebug(CurrentBottom, CurrentTop);
1427 if (&*priorII == MI)
1428 CurrentBottom = priorII;
1429 else {
1430 if (&*CurrentTop == MI) {
1431 CurrentTop = nextIfDebug(++CurrentTop, priorII);
1432 TopRPTracker.setPos(CurrentTop);
1433 }
1434 moveInstruction(MI, CurrentBottom);
1435 CurrentBottom = MI;
Yaxun Liu8b7454a2018-01-23 16:04:53 +00001436 BotRPTracker.setPos(CurrentBottom);
Andrew Trick7a8e1002012-09-11 00:39:15 +00001437 }
Andrew Trickb6e74712013-09-04 20:59:59 +00001438 if (ShouldTrackPressure) {
Matthias Braund4f64092016-01-20 00:23:32 +00001439 RegisterOperands RegOpers;
1440 RegOpers.collect(*MI, *TRI, MRI, ShouldTrackLaneMasks, false);
1441 if (ShouldTrackLaneMasks) {
1442 // Adjust liveness and add missing dead+read-undef flags.
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001443 SlotIndex SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot();
Matthias Braund4f64092016-01-20 00:23:32 +00001444 RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx, MI);
1445 } else {
1446 // Adjust for missing dead-def flags.
1447 RegOpers.detectDeadDefs(*MI, *LIS);
1448 }
1449
Yaxun Liuc41e2f62017-12-15 03:56:57 +00001450 if (BotRPTracker.getPos() != CurrentBottom)
1451 BotRPTracker.recedeSkipDebugValues();
Matthias Braun5d458612016-01-20 00:23:26 +00001452 SmallVector<RegisterMaskPair, 8> LiveUses;
Matthias Braund4f64092016-01-20 00:23:32 +00001453 BotRPTracker.recede(RegOpers, &LiveUses);
Andrew Trickb6e74712013-09-04 20:59:59 +00001454 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001455 LLVM_DEBUG(dbgs() << "Bottom Pressure:\n"; dumpRegSetPressure(
1456 BotRPTracker.getRegSetPressureAtPos(), TRI););
Matthias Braun9198c672015-11-06 20:59:02 +00001457
Andrew Trickb248b4a2013-09-06 17:32:47 +00001458 updateScheduledPressure(SU, BotRPTracker.getPressure().MaxSetPressure);
Andrew Trickb6e74712013-09-04 20:59:59 +00001459 updatePressureDiffs(LiveUses);
Andrew Trickb6e74712013-09-04 20:59:59 +00001460 }
Andrew Trick7a8e1002012-09-11 00:39:15 +00001461 }
1462}
1463
Andrew Trick263280242012-11-12 19:52:20 +00001464//===----------------------------------------------------------------------===//
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001465// BaseMemOpClusterMutation - DAG post-processing to cluster loads or stores.
Andrew Trick263280242012-11-12 19:52:20 +00001466//===----------------------------------------------------------------------===//
1467
Andrew Tricka7714a02012-11-12 19:40:10 +00001468namespace {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001469
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001470/// Post-process the DAG to create cluster edges between neighboring
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001471/// loads or between neighboring stores.
1472class BaseMemOpClusterMutation : public ScheduleDAGMutation {
1473 struct MemOpInfo {
Andrew Tricka7714a02012-11-12 19:40:10 +00001474 SUnit *SU;
1475 unsigned BaseReg;
Chad Rosierc27a18f2016-03-09 16:00:35 +00001476 int64_t Offset;
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001477
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001478 MemOpInfo(SUnit *su, unsigned reg, int64_t ofs)
1479 : SU(su), BaseReg(reg), Offset(ofs) {}
Benjamin Kramerb0f74b22014-03-07 21:35:39 +00001480
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001481 bool operator<(const MemOpInfo&RHS) const {
Mandeep Singh Grange82678a2016-10-18 00:11:19 +00001482 return std::tie(BaseReg, Offset, SU->NodeNum) <
1483 std::tie(RHS.BaseReg, RHS.Offset, RHS.SU->NodeNum);
Benjamin Kramerb0f74b22014-03-07 21:35:39 +00001484 }
Andrew Tricka7714a02012-11-12 19:40:10 +00001485 };
Andrew Tricka7714a02012-11-12 19:40:10 +00001486
1487 const TargetInstrInfo *TII;
1488 const TargetRegisterInfo *TRI;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001489 bool IsLoad;
1490
Andrew Tricka7714a02012-11-12 19:40:10 +00001491public:
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001492 BaseMemOpClusterMutation(const TargetInstrInfo *tii,
1493 const TargetRegisterInfo *tri, bool IsLoad)
1494 : TII(tii), TRI(tri), IsLoad(IsLoad) {}
Andrew Tricka7714a02012-11-12 19:40:10 +00001495
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001496 void apply(ScheduleDAGInstrs *DAGInstrs) override;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001497
Andrew Tricka7714a02012-11-12 19:40:10 +00001498protected:
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001499 void clusterNeighboringMemOps(ArrayRef<SUnit *> MemOps, ScheduleDAGMI *DAG);
1500};
1501
1502class StoreClusterMutation : public BaseMemOpClusterMutation {
1503public:
1504 StoreClusterMutation(const TargetInstrInfo *tii,
1505 const TargetRegisterInfo *tri)
1506 : BaseMemOpClusterMutation(tii, tri, false) {}
1507};
1508
1509class LoadClusterMutation : public BaseMemOpClusterMutation {
1510public:
1511 LoadClusterMutation(const TargetInstrInfo *tii, const TargetRegisterInfo *tri)
1512 : BaseMemOpClusterMutation(tii, tri, true) {}
Andrew Tricka7714a02012-11-12 19:40:10 +00001513};
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001514
1515} // end anonymous namespace
Andrew Tricka7714a02012-11-12 19:40:10 +00001516
Tom Stellard68726a52016-08-19 19:59:18 +00001517namespace llvm {
1518
1519std::unique_ptr<ScheduleDAGMutation>
1520createLoadClusterDAGMutation(const TargetInstrInfo *TII,
1521 const TargetRegisterInfo *TRI) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001522 return EnableMemOpCluster ? llvm::make_unique<LoadClusterMutation>(TII, TRI)
Matthias Braun115efcd2016-11-28 20:11:54 +00001523 : nullptr;
Tom Stellard68726a52016-08-19 19:59:18 +00001524}
1525
1526std::unique_ptr<ScheduleDAGMutation>
1527createStoreClusterDAGMutation(const TargetInstrInfo *TII,
1528 const TargetRegisterInfo *TRI) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001529 return EnableMemOpCluster ? llvm::make_unique<StoreClusterMutation>(TII, TRI)
Matthias Braun115efcd2016-11-28 20:11:54 +00001530 : nullptr;
Tom Stellard68726a52016-08-19 19:59:18 +00001531}
1532
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001533} // end namespace llvm
Tom Stellard68726a52016-08-19 19:59:18 +00001534
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001535void BaseMemOpClusterMutation::clusterNeighboringMemOps(
1536 ArrayRef<SUnit *> MemOps, ScheduleDAGMI *DAG) {
1537 SmallVector<MemOpInfo, 32> MemOpRecords;
Javed Absare3a0cc22017-06-21 09:10:10 +00001538 for (SUnit *SU : MemOps) {
Andrew Tricka7714a02012-11-12 19:40:10 +00001539 unsigned BaseReg;
Chad Rosierc27a18f2016-03-09 16:00:35 +00001540 int64_t Offset;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001541 if (TII->getMemOpBaseRegImmOfs(*SU->getInstr(), BaseReg, Offset, TRI))
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001542 MemOpRecords.push_back(MemOpInfo(SU, BaseReg, Offset));
Andrew Tricka7714a02012-11-12 19:40:10 +00001543 }
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001544 if (MemOpRecords.size() < 2)
Andrew Tricka7714a02012-11-12 19:40:10 +00001545 return;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001546
Mandeep Singh Grange92f0cf2018-04-06 18:08:42 +00001547 llvm::sort(MemOpRecords.begin(), MemOpRecords.end());
Andrew Tricka7714a02012-11-12 19:40:10 +00001548 unsigned ClusterLength = 1;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001549 for (unsigned Idx = 0, End = MemOpRecords.size(); Idx < (End - 1); ++Idx) {
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001550 SUnit *SUa = MemOpRecords[Idx].SU;
1551 SUnit *SUb = MemOpRecords[Idx+1].SU;
Stanislav Mekhanoshin7fe9a5d2017-09-13 22:20:47 +00001552 if (TII->shouldClusterMemOps(*SUa->getInstr(), MemOpRecords[Idx].BaseReg,
1553 *SUb->getInstr(), MemOpRecords[Idx+1].BaseReg,
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001554 ClusterLength) &&
1555 DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001556 LLVM_DEBUG(dbgs() << "Cluster ld/st SU(" << SUa->NodeNum << ") - SU("
1557 << SUb->NodeNum << ")\n");
Andrew Tricka7714a02012-11-12 19:40:10 +00001558 // Copy successor edges from SUa to SUb. Interleaving computation
1559 // dependent on SUa can prevent load combining due to register reuse.
1560 // Predecessor edges do not need to be copied from SUb to SUa since nearby
1561 // loads should have effectively the same inputs.
Javed Absare3a0cc22017-06-21 09:10:10 +00001562 for (const SDep &Succ : SUa->Succs) {
1563 if (Succ.getSUnit() == SUb)
Andrew Tricka7714a02012-11-12 19:40:10 +00001564 continue;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001565 LLVM_DEBUG(dbgs() << " Copy Succ SU(" << Succ.getSUnit()->NodeNum
1566 << ")\n");
Javed Absare3a0cc22017-06-21 09:10:10 +00001567 DAG->addEdge(Succ.getSUnit(), SDep(SUb, SDep::Artificial));
Andrew Tricka7714a02012-11-12 19:40:10 +00001568 }
1569 ++ClusterLength;
Matthias Braunb550b762016-04-21 01:54:13 +00001570 } else
Andrew Tricka7714a02012-11-12 19:40:10 +00001571 ClusterLength = 1;
1572 }
1573}
1574
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001575/// Callback from DAG postProcessing to create cluster edges for loads.
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001576void BaseMemOpClusterMutation::apply(ScheduleDAGInstrs *DAGInstrs) {
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001577 ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs);
1578
Andrew Tricka7714a02012-11-12 19:40:10 +00001579 // Map DAG NodeNum to store chain ID.
1580 DenseMap<unsigned, unsigned> StoreChainIDs;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001581 // Map each store chain to a set of dependent MemOps.
Andrew Tricka7714a02012-11-12 19:40:10 +00001582 SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
Javed Absare3a0cc22017-06-21 09:10:10 +00001583 for (SUnit &SU : DAG->SUnits) {
1584 if ((IsLoad && !SU.getInstr()->mayLoad()) ||
1585 (!IsLoad && !SU.getInstr()->mayStore()))
Andrew Tricka7714a02012-11-12 19:40:10 +00001586 continue;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001587
Andrew Tricka7714a02012-11-12 19:40:10 +00001588 unsigned ChainPredID = DAG->SUnits.size();
Javed Absare3a0cc22017-06-21 09:10:10 +00001589 for (const SDep &Pred : SU.Preds) {
1590 if (Pred.isCtrl()) {
1591 ChainPredID = Pred.getSUnit()->NodeNum;
Andrew Tricka7714a02012-11-12 19:40:10 +00001592 break;
1593 }
1594 }
1595 // Check if this chain-like pred has been seen
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001596 // before. ChainPredID==MaxNodeID at the top of the schedule.
Andrew Tricka7714a02012-11-12 19:40:10 +00001597 unsigned NumChains = StoreChainDependents.size();
1598 std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
1599 StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
1600 if (Result.second)
1601 StoreChainDependents.resize(NumChains + 1);
Javed Absare3a0cc22017-06-21 09:10:10 +00001602 StoreChainDependents[Result.first->second].push_back(&SU);
Andrew Tricka7714a02012-11-12 19:40:10 +00001603 }
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001604
Andrew Tricka7714a02012-11-12 19:40:10 +00001605 // Iterate over the store chains.
Javed Absare3a0cc22017-06-21 09:10:10 +00001606 for (auto &SCD : StoreChainDependents)
1607 clusterNeighboringMemOps(SCD, DAG);
Andrew Tricka7714a02012-11-12 19:40:10 +00001608}
1609
Andrew Trick02a80da2012-03-08 01:41:12 +00001610//===----------------------------------------------------------------------===//
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001611// CopyConstrain - DAG post-processing to encourage copy elimination.
1612//===----------------------------------------------------------------------===//
1613
1614namespace {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001615
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001616/// Post-process the DAG to create weak edges from all uses of a copy to
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001617/// the one use that defines the copy's source vreg, most likely an induction
1618/// variable increment.
1619class CopyConstrain : public ScheduleDAGMutation {
1620 // Transient state.
1621 SlotIndex RegionBeginIdx;
Eugene Zelenko32a40562017-09-11 23:00:48 +00001622
Andrew Trick2e875172013-04-24 23:19:56 +00001623 // RegionEndIdx is the slot index of the last non-debug instruction in the
1624 // scheduling region. So we may have RegionBeginIdx == RegionEndIdx.
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001625 SlotIndex RegionEndIdx;
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001626
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001627public:
1628 CopyConstrain(const TargetInstrInfo *, const TargetRegisterInfo *) {}
1629
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001630 void apply(ScheduleDAGInstrs *DAGInstrs) override;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001631
1632protected:
Andrew Trickd7f890e2013-12-28 21:56:47 +00001633 void constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG);
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001634};
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001635
1636} // end anonymous namespace
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001637
Tom Stellard68726a52016-08-19 19:59:18 +00001638namespace llvm {
1639
1640std::unique_ptr<ScheduleDAGMutation>
1641createCopyConstrainDAGMutation(const TargetInstrInfo *TII,
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001642 const TargetRegisterInfo *TRI) {
1643 return llvm::make_unique<CopyConstrain>(TII, TRI);
Tom Stellard68726a52016-08-19 19:59:18 +00001644}
1645
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001646} // end namespace llvm
Tom Stellard68726a52016-08-19 19:59:18 +00001647
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001648/// constrainLocalCopy handles two possibilities:
1649/// 1) Local src:
1650/// I0: = dst
1651/// I1: src = ...
1652/// I2: = dst
1653/// I3: dst = src (copy)
1654/// (create pred->succ edges I0->I1, I2->I1)
1655///
1656/// 2) Local copy:
1657/// I0: dst = src (copy)
1658/// I1: = dst
1659/// I2: src = ...
1660/// I3: = dst
1661/// (create pred->succ edges I1->I2, I3->I2)
1662///
1663/// Although the MachineScheduler is currently constrained to single blocks,
1664/// this algorithm should handle extended blocks. An EBB is a set of
1665/// contiguously numbered blocks such that the previous block in the EBB is
1666/// always the single predecessor.
Andrew Trickd7f890e2013-12-28 21:56:47 +00001667void CopyConstrain::constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG) {
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001668 LiveIntervals *LIS = DAG->getLIS();
1669 MachineInstr *Copy = CopySU->getInstr();
1670
1671 // Check for pure vreg copies.
Matthias Braun7511abd2016-04-04 21:23:46 +00001672 const MachineOperand &SrcOp = Copy->getOperand(1);
1673 unsigned SrcReg = SrcOp.getReg();
1674 if (!TargetRegisterInfo::isVirtualRegister(SrcReg) || !SrcOp.readsReg())
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001675 return;
1676
Matthias Braun7511abd2016-04-04 21:23:46 +00001677 const MachineOperand &DstOp = Copy->getOperand(0);
1678 unsigned DstReg = DstOp.getReg();
1679 if (!TargetRegisterInfo::isVirtualRegister(DstReg) || DstOp.isDead())
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001680 return;
1681
1682 // Check if either the dest or source is local. If it's live across a back
1683 // edge, it's not local. Note that if both vregs are live across the back
1684 // edge, we cannot successfully contrain the copy without cyclic scheduling.
Michael Kuperstein54c61ed2015-01-19 07:30:47 +00001685 // If both the copy's source and dest are local live intervals, then we
1686 // should treat the dest as the global for the purpose of adding
1687 // constraints. This adds edges from source's other uses to the copy.
1688 unsigned LocalReg = SrcReg;
1689 unsigned GlobalReg = DstReg;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001690 LiveInterval *LocalLI = &LIS->getInterval(LocalReg);
1691 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx)) {
Michael Kuperstein54c61ed2015-01-19 07:30:47 +00001692 LocalReg = DstReg;
1693 GlobalReg = SrcReg;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001694 LocalLI = &LIS->getInterval(LocalReg);
1695 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx))
1696 return;
1697 }
1698 LiveInterval *GlobalLI = &LIS->getInterval(GlobalReg);
1699
1700 // Find the global segment after the start of the local LI.
1701 LiveInterval::iterator GlobalSegment = GlobalLI->find(LocalLI->beginIndex());
1702 // If GlobalLI does not overlap LocalLI->start, then a copy directly feeds a
1703 // local live range. We could create edges from other global uses to the local
1704 // start, but the coalescer should have already eliminated these cases, so
1705 // don't bother dealing with it.
1706 if (GlobalSegment == GlobalLI->end())
1707 return;
1708
1709 // If GlobalSegment is killed at the LocalLI->start, the call to find()
1710 // returned the next global segment. But if GlobalSegment overlaps with
1711 // LocalLI->start, then advance to the next segement. If a hole in GlobalLI
1712 // exists in LocalLI's vicinity, GlobalSegment will be the end of the hole.
1713 if (GlobalSegment->contains(LocalLI->beginIndex()))
1714 ++GlobalSegment;
1715
1716 if (GlobalSegment == GlobalLI->end())
1717 return;
1718
1719 // Check if GlobalLI contains a hole in the vicinity of LocalLI.
1720 if (GlobalSegment != GlobalLI->begin()) {
1721 // Two address defs have no hole.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001722 if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->end,
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001723 GlobalSegment->start)) {
1724 return;
1725 }
Andrew Trickd9761772013-07-30 19:59:08 +00001726 // If the prior global segment may be defined by the same two-address
1727 // instruction that also defines LocalLI, then can't make a hole here.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001728 if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->start,
Andrew Trickd9761772013-07-30 19:59:08 +00001729 LocalLI->beginIndex())) {
1730 return;
1731 }
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001732 // If GlobalLI has a prior segment, it must be live into the EBB. Otherwise
1733 // it would be a disconnected component in the live range.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001734 assert(std::prev(GlobalSegment)->start < LocalLI->beginIndex() &&
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001735 "Disconnected LRG within the scheduling region.");
1736 }
1737 MachineInstr *GlobalDef = LIS->getInstructionFromIndex(GlobalSegment->start);
1738 if (!GlobalDef)
1739 return;
1740
1741 SUnit *GlobalSU = DAG->getSUnit(GlobalDef);
1742 if (!GlobalSU)
1743 return;
1744
1745 // GlobalDef is the bottom of the GlobalLI hole. Open the hole by
1746 // constraining the uses of the last local def to precede GlobalDef.
1747 SmallVector<SUnit*,8> LocalUses;
1748 const VNInfo *LastLocalVN = LocalLI->getVNInfoBefore(LocalLI->endIndex());
1749 MachineInstr *LastLocalDef = LIS->getInstructionFromIndex(LastLocalVN->def);
1750 SUnit *LastLocalSU = DAG->getSUnit(LastLocalDef);
Javed Absare3a0cc22017-06-21 09:10:10 +00001751 for (const SDep &Succ : LastLocalSU->Succs) {
1752 if (Succ.getKind() != SDep::Data || Succ.getReg() != LocalReg)
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001753 continue;
Javed Absare3a0cc22017-06-21 09:10:10 +00001754 if (Succ.getSUnit() == GlobalSU)
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001755 continue;
Javed Absare3a0cc22017-06-21 09:10:10 +00001756 if (!DAG->canAddEdge(GlobalSU, Succ.getSUnit()))
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001757 return;
Javed Absare3a0cc22017-06-21 09:10:10 +00001758 LocalUses.push_back(Succ.getSUnit());
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001759 }
1760 // Open the top of the GlobalLI hole by constraining any earlier global uses
1761 // to precede the start of LocalLI.
1762 SmallVector<SUnit*,8> GlobalUses;
1763 MachineInstr *FirstLocalDef =
1764 LIS->getInstructionFromIndex(LocalLI->beginIndex());
1765 SUnit *FirstLocalSU = DAG->getSUnit(FirstLocalDef);
Javed Absare3a0cc22017-06-21 09:10:10 +00001766 for (const SDep &Pred : GlobalSU->Preds) {
1767 if (Pred.getKind() != SDep::Anti || Pred.getReg() != GlobalReg)
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001768 continue;
Javed Absare3a0cc22017-06-21 09:10:10 +00001769 if (Pred.getSUnit() == FirstLocalSU)
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001770 continue;
Javed Absare3a0cc22017-06-21 09:10:10 +00001771 if (!DAG->canAddEdge(FirstLocalSU, Pred.getSUnit()))
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001772 return;
Javed Absare3a0cc22017-06-21 09:10:10 +00001773 GlobalUses.push_back(Pred.getSUnit());
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001774 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001775 LLVM_DEBUG(dbgs() << "Constraining copy SU(" << CopySU->NodeNum << ")\n");
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001776 // Add the weak edges.
1777 for (SmallVectorImpl<SUnit*>::const_iterator
1778 I = LocalUses.begin(), E = LocalUses.end(); I != E; ++I) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001779 LLVM_DEBUG(dbgs() << " Local use SU(" << (*I)->NodeNum << ") -> SU("
1780 << GlobalSU->NodeNum << ")\n");
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001781 DAG->addEdge(GlobalSU, SDep(*I, SDep::Weak));
1782 }
1783 for (SmallVectorImpl<SUnit*>::const_iterator
1784 I = GlobalUses.begin(), E = GlobalUses.end(); I != E; ++I) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001785 LLVM_DEBUG(dbgs() << " Global use SU(" << (*I)->NodeNum << ") -> SU("
1786 << FirstLocalSU->NodeNum << ")\n");
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001787 DAG->addEdge(FirstLocalSU, SDep(*I, SDep::Weak));
1788 }
1789}
1790
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001791/// Callback from DAG postProcessing to create weak edges to encourage
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001792/// copy elimination.
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001793void CopyConstrain::apply(ScheduleDAGInstrs *DAGInstrs) {
1794 ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs);
Andrew Trickd7f890e2013-12-28 21:56:47 +00001795 assert(DAG->hasVRegLiveness() && "Expect VRegs with LiveIntervals");
1796
Andrew Trick2e875172013-04-24 23:19:56 +00001797 MachineBasicBlock::iterator FirstPos = nextIfDebug(DAG->begin(), DAG->end());
1798 if (FirstPos == DAG->end())
1799 return;
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001800 RegionBeginIdx = DAG->getLIS()->getInstructionIndex(*FirstPos);
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001801 RegionEndIdx = DAG->getLIS()->getInstructionIndex(
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001802 *priorNonDebug(DAG->end(), DAG->begin()));
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001803
Javed Absare3a0cc22017-06-21 09:10:10 +00001804 for (SUnit &SU : DAG->SUnits) {
1805 if (!SU.getInstr()->isCopy())
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001806 continue;
1807
Javed Absare3a0cc22017-06-21 09:10:10 +00001808 constrainLocalCopy(&SU, static_cast<ScheduleDAGMILive*>(DAG));
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001809 }
1810}
1811
1812//===----------------------------------------------------------------------===//
Andrew Trickfc127d12013-12-07 05:59:44 +00001813// MachineSchedStrategy helpers used by GenericScheduler, GenericPostScheduler
1814// and possibly other custom schedulers.
Andrew Trickd14d7c22013-12-28 21:56:57 +00001815//===----------------------------------------------------------------------===//
Andrew Tricke1c034f2012-01-17 06:55:03 +00001816
Andrew Trick5a22df42013-12-05 17:56:02 +00001817static const unsigned InvalidCycle = ~0U;
1818
Andrew Trickfc127d12013-12-07 05:59:44 +00001819SchedBoundary::~SchedBoundary() { delete HazardRec; }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001820
Jonas Paulsson238c14b2017-10-25 08:23:33 +00001821/// Given a Count of resource usage and a Latency value, return true if a
1822/// SchedBoundary becomes resource limited.
1823static bool checkResourceLimit(unsigned LFactor, unsigned Count,
1824 unsigned Latency) {
1825 return (int)(Count - (Latency * LFactor)) > (int)LFactor;
1826}
1827
Andrew Trickfc127d12013-12-07 05:59:44 +00001828void SchedBoundary::reset() {
1829 // A new HazardRec is created for each DAG and owned by SchedBoundary.
1830 // Destroying and reconstructing it is very expensive though. So keep
1831 // invalid, placeholder HazardRecs.
1832 if (HazardRec && HazardRec->isEnabled()) {
1833 delete HazardRec;
Craig Topperc0196b12014-04-14 00:51:57 +00001834 HazardRec = nullptr;
Andrew Trickfc127d12013-12-07 05:59:44 +00001835 }
1836 Available.clear();
1837 Pending.clear();
1838 CheckPending = false;
Andrew Trickfc127d12013-12-07 05:59:44 +00001839 CurrCycle = 0;
1840 CurrMOps = 0;
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001841 MinReadyCycle = std::numeric_limits<unsigned>::max();
Andrew Trickfc127d12013-12-07 05:59:44 +00001842 ExpectedLatency = 0;
1843 DependentLatency = 0;
1844 RetiredMOps = 0;
1845 MaxExecutedResCount = 0;
1846 ZoneCritResIdx = 0;
1847 IsResourceLimited = false;
1848 ReservedCycles.clear();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001849#ifndef NDEBUG
Andrew Trickd14d7c22013-12-28 21:56:57 +00001850 // Track the maximum number of stall cycles that could arise either from the
1851 // latency of a DAG edge or the number of cycles that a processor resource is
1852 // reserved (SchedBoundary::ReservedCycles).
Andrew Trick7f1ebbe2014-06-07 01:48:43 +00001853 MaxObservedStall = 0;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001854#endif
Andrew Trickfc127d12013-12-07 05:59:44 +00001855 // Reserve a zero-count for invalid CritResIdx.
1856 ExecutedResCounts.resize(1);
1857 assert(!ExecutedResCounts[0] && "nonzero count for bad resource");
1858}
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001859
Andrew Trickfc127d12013-12-07 05:59:44 +00001860void SchedRemainder::
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001861init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
1862 reset();
1863 if (!SchedModel->hasInstrSchedModel())
1864 return;
1865 RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
Javed Absare3a0cc22017-06-21 09:10:10 +00001866 for (SUnit &SU : DAG->SUnits) {
1867 const MCSchedClassDesc *SC = DAG->getSchedClass(&SU);
1868 RemIssueCount += SchedModel->getNumMicroOps(SU.getInstr(), SC)
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001869 * SchedModel->getMicroOpFactor();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001870 for (TargetSchedModel::ProcResIter
1871 PI = SchedModel->getWriteProcResBegin(SC),
1872 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1873 unsigned PIdx = PI->ProcResourceIdx;
1874 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1875 RemainingCounts[PIdx] += (Factor * PI->Cycles);
1876 }
1877 }
1878}
1879
Andrew Trickfc127d12013-12-07 05:59:44 +00001880void SchedBoundary::
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001881init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
1882 reset();
1883 DAG = dag;
1884 SchedModel = smodel;
1885 Rem = rem;
Andrew Trick5a22df42013-12-05 17:56:02 +00001886 if (SchedModel->hasInstrSchedModel()) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001887 ExecutedResCounts.resize(SchedModel->getNumProcResourceKinds());
Andrew Trick5a22df42013-12-05 17:56:02 +00001888 ReservedCycles.resize(SchedModel->getNumProcResourceKinds(), InvalidCycle);
1889 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001890}
1891
Andrew Trick880e5732013-12-05 17:55:58 +00001892/// Compute the stall cycles based on this SUnit's ready time. Heuristics treat
1893/// these "soft stalls" differently than the hard stall cycles based on CPU
1894/// resources and computed by checkHazard(). A fully in-order model
1895/// (MicroOpBufferSize==0) will not make use of this since instructions are not
1896/// available for scheduling until they are ready. However, a weaker in-order
1897/// model may use this for heuristics. For example, if a processor has in-order
1898/// behavior when reading certain resources, this may come into play.
Andrew Trickfc127d12013-12-07 05:59:44 +00001899unsigned SchedBoundary::getLatencyStallCycles(SUnit *SU) {
Andrew Trick880e5732013-12-05 17:55:58 +00001900 if (!SU->isUnbuffered)
1901 return 0;
1902
1903 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
1904 if (ReadyCycle > CurrCycle)
1905 return ReadyCycle - CurrCycle;
1906 return 0;
1907}
1908
Andrew Trick5a22df42013-12-05 17:56:02 +00001909/// Compute the next cycle at which the given processor resource can be
1910/// scheduled.
Andrew Trickfc127d12013-12-07 05:59:44 +00001911unsigned SchedBoundary::
Andrew Trick5a22df42013-12-05 17:56:02 +00001912getNextResourceCycle(unsigned PIdx, unsigned Cycles) {
1913 unsigned NextUnreserved = ReservedCycles[PIdx];
1914 // If this resource has never been used, always return cycle zero.
1915 if (NextUnreserved == InvalidCycle)
1916 return 0;
1917 // For bottom-up scheduling add the cycles needed for the current operation.
1918 if (!isTop())
1919 NextUnreserved += Cycles;
1920 return NextUnreserved;
1921}
1922
Andrew Trick8c9e6722012-06-29 03:23:24 +00001923/// Does this SU have a hazard within the current instruction group.
1924///
1925/// The scheduler supports two modes of hazard recognition. The first is the
1926/// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
1927/// supports highly complicated in-order reservation tables
1928/// (ScoreboardHazardRecognizer) and arbitraty target-specific logic.
1929///
1930/// The second is a streamlined mechanism that checks for hazards based on
1931/// simple counters that the scheduler itself maintains. It explicitly checks
1932/// for instruction dispatch limitations, including the number of micro-ops that
1933/// can dispatch per cycle.
1934///
1935/// TODO: Also check whether the SU must start a new group.
Andrew Trickfc127d12013-12-07 05:59:44 +00001936bool SchedBoundary::checkHazard(SUnit *SU) {
Andrew Trickd14d7c22013-12-28 21:56:57 +00001937 if (HazardRec->isEnabled()
1938 && HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard) {
1939 return true;
1940 }
Javed Absar3d594372017-03-27 20:46:37 +00001941
Andrew Trickdd79f0f2012-10-10 05:43:09 +00001942 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
Andrew Tricke2ff5752013-06-15 04:49:49 +00001943 if ((CurrMOps > 0) && (CurrMOps + uops > SchedModel->getIssueWidth())) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001944 LLVM_DEBUG(dbgs() << " SU(" << SU->NodeNum << ") uops="
1945 << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
Andrew Trick8c9e6722012-06-29 03:23:24 +00001946 return true;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001947 }
Javed Absar3d594372017-03-27 20:46:37 +00001948
1949 if (CurrMOps > 0 &&
1950 ((isTop() && SchedModel->mustBeginGroup(SU->getInstr())) ||
1951 (!isTop() && SchedModel->mustEndGroup(SU->getInstr())))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001952 LLVM_DEBUG(dbgs() << " hazard: SU(" << SU->NodeNum << ") must "
1953 << (isTop() ? "begin" : "end") << " group\n");
Javed Absar3d594372017-03-27 20:46:37 +00001954 return true;
1955 }
1956
Andrew Trick5a22df42013-12-05 17:56:02 +00001957 if (SchedModel->hasInstrSchedModel() && SU->hasReservedResource) {
1958 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
Javed Absare485b142017-10-03 09:35:04 +00001959 for (const MCWriteProcResEntry &PE :
1960 make_range(SchedModel->getWriteProcResBegin(SC),
1961 SchedModel->getWriteProcResEnd(SC))) {
1962 unsigned ResIdx = PE.ProcResourceIdx;
1963 unsigned Cycles = PE.Cycles;
1964 unsigned NRCycle = getNextResourceCycle(ResIdx, Cycles);
Andrew Trick56327222014-06-27 04:57:05 +00001965 if (NRCycle > CurrCycle) {
Andrew Trick040c0da2014-06-27 05:09:36 +00001966#ifndef NDEBUG
Javed Absare485b142017-10-03 09:35:04 +00001967 MaxObservedStall = std::max(Cycles, MaxObservedStall);
Andrew Trick040c0da2014-06-27 05:09:36 +00001968#endif
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001969 LLVM_DEBUG(dbgs() << " SU(" << SU->NodeNum << ") "
1970 << SchedModel->getResourceName(ResIdx) << "="
1971 << NRCycle << "c\n");
Andrew Trick5a22df42013-12-05 17:56:02 +00001972 return true;
Andrew Trick56327222014-06-27 04:57:05 +00001973 }
Andrew Trick5a22df42013-12-05 17:56:02 +00001974 }
1975 }
Andrew Trick8c9e6722012-06-29 03:23:24 +00001976 return false;
1977}
1978
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001979// Find the unscheduled node in ReadySUs with the highest latency.
Andrew Trickfc127d12013-12-07 05:59:44 +00001980unsigned SchedBoundary::
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001981findMaxLatency(ArrayRef<SUnit*> ReadySUs) {
Craig Topperc0196b12014-04-14 00:51:57 +00001982 SUnit *LateSU = nullptr;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001983 unsigned RemLatency = 0;
Javed Absare3a0cc22017-06-21 09:10:10 +00001984 for (SUnit *SU : ReadySUs) {
1985 unsigned L = getUnscheduledLatency(SU);
Andrew Trickf5b8ef22013-06-15 04:49:44 +00001986 if (L > RemLatency) {
Andrew Trickd6d5ad32012-12-18 20:52:56 +00001987 RemLatency = L;
Javed Absare3a0cc22017-06-21 09:10:10 +00001988 LateSU = SU;
Andrew Trickf5b8ef22013-06-15 04:49:44 +00001989 }
Andrew Trickd6d5ad32012-12-18 20:52:56 +00001990 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001991 if (LateSU) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001992 LLVM_DEBUG(dbgs() << Available.getName() << " RemLatency SU("
1993 << LateSU->NodeNum << ") " << RemLatency << "c\n");
Andrew Trickd6d5ad32012-12-18 20:52:56 +00001994 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001995 return RemLatency;
1996}
Andrew Trickf5b8ef22013-06-15 04:49:44 +00001997
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001998// Count resources in this zone and the remaining unscheduled
1999// instruction. Return the max count, scaled. Set OtherCritIdx to the critical
2000// resource index, or zero if the zone is issue limited.
Andrew Trickfc127d12013-12-07 05:59:44 +00002001unsigned SchedBoundary::
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002002getOtherResourceCount(unsigned &OtherCritIdx) {
Alexey Samsonov64c391d2013-07-19 08:55:18 +00002003 OtherCritIdx = 0;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002004 if (!SchedModel->hasInstrSchedModel())
2005 return 0;
2006
2007 unsigned OtherCritCount = Rem->RemIssueCount
2008 + (RetiredMOps * SchedModel->getMicroOpFactor());
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002009 LLVM_DEBUG(dbgs() << " " << Available.getName() << " + Remain MOps: "
2010 << OtherCritCount / SchedModel->getMicroOpFactor() << '\n');
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002011 for (unsigned PIdx = 1, PEnd = SchedModel->getNumProcResourceKinds();
2012 PIdx != PEnd; ++PIdx) {
2013 unsigned OtherCount = getResourceCount(PIdx) + Rem->RemainingCounts[PIdx];
2014 if (OtherCount > OtherCritCount) {
2015 OtherCritCount = OtherCount;
2016 OtherCritIdx = PIdx;
2017 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002018 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002019 if (OtherCritIdx) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002020 LLVM_DEBUG(
2021 dbgs() << " " << Available.getName() << " + Remain CritRes: "
2022 << OtherCritCount / SchedModel->getResourceFactor(OtherCritIdx)
2023 << " " << SchedModel->getResourceName(OtherCritIdx) << "\n");
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002024 }
2025 return OtherCritCount;
2026}
2027
Andrew Trickfc127d12013-12-07 05:59:44 +00002028void SchedBoundary::releaseNode(SUnit *SU, unsigned ReadyCycle) {
Andrew Trick7f1ebbe2014-06-07 01:48:43 +00002029 assert(SU->getInstr() && "Scheduled SUnit must have instr");
2030
2031#ifndef NDEBUG
Andrew Trick491e34a2014-06-12 22:36:28 +00002032 // ReadyCycle was been bumped up to the CurrCycle when this node was
2033 // scheduled, but CurrCycle may have been eagerly advanced immediately after
2034 // scheduling, so may now be greater than ReadyCycle.
2035 if (ReadyCycle > CurrCycle)
2036 MaxObservedStall = std::max(ReadyCycle - CurrCycle, MaxObservedStall);
Andrew Trick7f1ebbe2014-06-07 01:48:43 +00002037#endif
2038
Andrew Trick61f1a272012-05-24 22:11:09 +00002039 if (ReadyCycle < MinReadyCycle)
2040 MinReadyCycle = ReadyCycle;
2041
2042 // Check for interlocks first. For the purpose of other heuristics, an
2043 // instruction that cannot issue appears as if it's not in the ReadyQueue.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002044 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
Matthias Braun6493bc22016-04-22 19:09:17 +00002045 if ((!IsBuffered && ReadyCycle > CurrCycle) || checkHazard(SU) ||
2046 Available.size() >= ReadyListLimit)
Andrew Trick61f1a272012-05-24 22:11:09 +00002047 Pending.push(SU);
2048 else
2049 Available.push(SU);
2050}
2051
2052/// Move the boundary of scheduled code by one cycle.
Andrew Trickfc127d12013-12-07 05:59:44 +00002053void SchedBoundary::bumpCycle(unsigned NextCycle) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002054 if (SchedModel->getMicroOpBufferSize() == 0) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00002055 assert(MinReadyCycle < std::numeric_limits<unsigned>::max() &&
2056 "MinReadyCycle uninitialized");
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002057 if (MinReadyCycle > NextCycle)
2058 NextCycle = MinReadyCycle;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002059 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002060 // Update the current micro-ops, which will issue in the next cycle.
2061 unsigned DecMOps = SchedModel->getIssueWidth() * (NextCycle - CurrCycle);
2062 CurrMOps = (CurrMOps <= DecMOps) ? 0 : CurrMOps - DecMOps;
2063
2064 // Decrement DependentLatency based on the next cycle.
Andrew Trickf5b8ef22013-06-15 04:49:44 +00002065 if ((NextCycle - CurrCycle) > DependentLatency)
2066 DependentLatency = 0;
2067 else
2068 DependentLatency -= (NextCycle - CurrCycle);
Andrew Trick61f1a272012-05-24 22:11:09 +00002069
2070 if (!HazardRec->isEnabled()) {
Andrew Trick45446062012-06-05 21:11:27 +00002071 // Bypass HazardRec virtual calls.
Andrew Trick61f1a272012-05-24 22:11:09 +00002072 CurrCycle = NextCycle;
Matthias Braunb550b762016-04-21 01:54:13 +00002073 } else {
Andrew Trick45446062012-06-05 21:11:27 +00002074 // Bypass getHazardType calls in case of long latency.
Andrew Trick61f1a272012-05-24 22:11:09 +00002075 for (; CurrCycle != NextCycle; ++CurrCycle) {
2076 if (isTop())
2077 HazardRec->AdvanceCycle();
2078 else
2079 HazardRec->RecedeCycle();
2080 }
2081 }
2082 CheckPending = true;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002083 IsResourceLimited =
Jonas Paulsson238c14b2017-10-25 08:23:33 +00002084 checkResourceLimit(SchedModel->getLatencyFactor(), getCriticalCount(),
2085 getScheduledLatency());
Andrew Trick61f1a272012-05-24 22:11:09 +00002086
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002087 LLVM_DEBUG(dbgs() << "Cycle: " << CurrCycle << ' ' << Available.getName()
2088 << '\n');
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002089}
2090
Andrew Trickfc127d12013-12-07 05:59:44 +00002091void SchedBoundary::incExecutedResources(unsigned PIdx, unsigned Count) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002092 ExecutedResCounts[PIdx] += Count;
2093 if (ExecutedResCounts[PIdx] > MaxExecutedResCount)
2094 MaxExecutedResCount = ExecutedResCounts[PIdx];
Andrew Trick61f1a272012-05-24 22:11:09 +00002095}
2096
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002097/// Add the given processor resource to this scheduled zone.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002098///
2099/// \param Cycles indicates the number of consecutive (non-pipelined) cycles
2100/// during which this resource is consumed.
2101///
2102/// \return the next cycle at which the instruction may execute without
2103/// oversubscribing resources.
Andrew Trickfc127d12013-12-07 05:59:44 +00002104unsigned SchedBoundary::
Andrew Trick5a22df42013-12-05 17:56:02 +00002105countResource(unsigned PIdx, unsigned Cycles, unsigned NextCycle) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002106 unsigned Factor = SchedModel->getResourceFactor(PIdx);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002107 unsigned Count = Factor * Cycles;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002108 LLVM_DEBUG(dbgs() << " " << SchedModel->getResourceName(PIdx) << " +"
2109 << Cycles << "x" << Factor << "u\n");
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002110
2111 // Update Executed resources counts.
2112 incExecutedResources(PIdx, Count);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002113 assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
2114 Rem->RemainingCounts[PIdx] -= Count;
2115
Andrew Trickb13ef172013-07-19 00:20:07 +00002116 // Check if this resource exceeds the current critical resource. If so, it
2117 // becomes the critical resource.
2118 if (ZoneCritResIdx != PIdx && (getResourceCount(PIdx) > getCriticalCount())) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002119 ZoneCritResIdx = PIdx;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002120 LLVM_DEBUG(dbgs() << " *** Critical resource "
2121 << SchedModel->getResourceName(PIdx) << ": "
2122 << getResourceCount(PIdx) / SchedModel->getLatencyFactor()
2123 << "c\n");
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002124 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002125 // For reserved resources, record the highest cycle using the resource.
2126 unsigned NextAvailable = getNextResourceCycle(PIdx, Cycles);
2127 if (NextAvailable > CurrCycle) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002128 LLVM_DEBUG(dbgs() << " Resource conflict: "
2129 << SchedModel->getProcResource(PIdx)->Name
2130 << " reserved until @" << NextAvailable << "\n");
Andrew Trick5a22df42013-12-05 17:56:02 +00002131 }
2132 return NextAvailable;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002133}
2134
Andrew Trick45446062012-06-05 21:11:27 +00002135/// Move the boundary of scheduled code by one SUnit.
Andrew Trickfc127d12013-12-07 05:59:44 +00002136void SchedBoundary::bumpNode(SUnit *SU) {
Andrew Trick45446062012-06-05 21:11:27 +00002137 // Update the reservation table.
2138 if (HazardRec->isEnabled()) {
2139 if (!isTop() && SU->isCall) {
2140 // Calls are scheduled with their preceding instructions. For bottom-up
2141 // scheduling, clear the pipeline state before emitting.
2142 HazardRec->Reset();
2143 }
2144 HazardRec->EmitInstruction(SU);
2145 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002146 // checkHazard should prevent scheduling multiple instructions per cycle that
2147 // exceed the issue width.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002148 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
2149 unsigned IncMOps = SchedModel->getNumMicroOps(SU->getInstr());
Daniel Jasper0d92abd2013-12-06 08:58:22 +00002150 assert(
2151 (CurrMOps == 0 || (CurrMOps + IncMOps) <= SchedModel->getIssueWidth()) &&
Andrew Trickf7760a22013-12-06 17:19:20 +00002152 "Cannot schedule this instruction's MicroOps in the current cycle.");
Andrew Trick5a22df42013-12-05 17:56:02 +00002153
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002154 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002155 LLVM_DEBUG(dbgs() << " Ready @" << ReadyCycle << "c\n");
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002156
Andrew Trick5a22df42013-12-05 17:56:02 +00002157 unsigned NextCycle = CurrCycle;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002158 switch (SchedModel->getMicroOpBufferSize()) {
2159 case 0:
2160 assert(ReadyCycle <= CurrCycle && "Broken PendingQueue");
2161 break;
2162 case 1:
2163 if (ReadyCycle > NextCycle) {
2164 NextCycle = ReadyCycle;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002165 LLVM_DEBUG(dbgs() << " *** Stall until: " << ReadyCycle << "\n");
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002166 }
2167 break;
2168 default:
2169 // We don't currently model the OOO reorder buffer, so consider all
Andrew Trick880e5732013-12-05 17:55:58 +00002170 // scheduled MOps to be "retired". We do loosely model in-order resource
2171 // latency. If this instruction uses an in-order resource, account for any
2172 // likely stall cycles.
2173 if (SU->isUnbuffered && ReadyCycle > NextCycle)
2174 NextCycle = ReadyCycle;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002175 break;
2176 }
2177 RetiredMOps += IncMOps;
2178
2179 // Update resource counts and critical resource.
2180 if (SchedModel->hasInstrSchedModel()) {
2181 unsigned DecRemIssue = IncMOps * SchedModel->getMicroOpFactor();
2182 assert(Rem->RemIssueCount >= DecRemIssue && "MOps double counted");
2183 Rem->RemIssueCount -= DecRemIssue;
2184 if (ZoneCritResIdx) {
2185 // Scale scheduled micro-ops for comparing with the critical resource.
2186 unsigned ScaledMOps =
2187 RetiredMOps * SchedModel->getMicroOpFactor();
2188
2189 // If scaled micro-ops are now more than the previous critical resource by
2190 // a full cycle, then micro-ops issue becomes critical.
2191 if ((int)(ScaledMOps - getResourceCount(ZoneCritResIdx))
2192 >= (int)SchedModel->getLatencyFactor()) {
2193 ZoneCritResIdx = 0;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002194 LLVM_DEBUG(dbgs() << " *** Critical resource NumMicroOps: "
2195 << ScaledMOps / SchedModel->getLatencyFactor()
2196 << "c\n");
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002197 }
2198 }
2199 for (TargetSchedModel::ProcResIter
2200 PI = SchedModel->getWriteProcResBegin(SC),
2201 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2202 unsigned RCycle =
Andrew Trick5a22df42013-12-05 17:56:02 +00002203 countResource(PI->ProcResourceIdx, PI->Cycles, NextCycle);
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002204 if (RCycle > NextCycle)
2205 NextCycle = RCycle;
2206 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002207 if (SU->hasReservedResource) {
2208 // For reserved resources, record the highest cycle using the resource.
2209 // For top-down scheduling, this is the cycle in which we schedule this
2210 // instruction plus the number of cycles the operations reserves the
2211 // resource. For bottom-up is it simply the instruction's cycle.
2212 for (TargetSchedModel::ProcResIter
2213 PI = SchedModel->getWriteProcResBegin(SC),
2214 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2215 unsigned PIdx = PI->ProcResourceIdx;
Andrew Trickd14d7c22013-12-28 21:56:57 +00002216 if (SchedModel->getProcResource(PIdx)->BufferSize == 0) {
Chad Rosieraba845e2014-07-02 16:46:08 +00002217 if (isTop()) {
2218 ReservedCycles[PIdx] =
2219 std::max(getNextResourceCycle(PIdx, 0), NextCycle + PI->Cycles);
2220 }
2221 else
2222 ReservedCycles[PIdx] = NextCycle;
Andrew Trickd14d7c22013-12-28 21:56:57 +00002223 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002224 }
2225 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002226 }
2227 // Update ExpectedLatency and DependentLatency.
2228 unsigned &TopLatency = isTop() ? ExpectedLatency : DependentLatency;
2229 unsigned &BotLatency = isTop() ? DependentLatency : ExpectedLatency;
2230 if (SU->getDepth() > TopLatency) {
2231 TopLatency = SU->getDepth();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002232 LLVM_DEBUG(dbgs() << " " << Available.getName() << " TopLatency SU("
2233 << SU->NodeNum << ") " << TopLatency << "c\n");
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002234 }
2235 if (SU->getHeight() > BotLatency) {
2236 BotLatency = SU->getHeight();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002237 LLVM_DEBUG(dbgs() << " " << Available.getName() << " BotLatency SU("
2238 << SU->NodeNum << ") " << BotLatency << "c\n");
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002239 }
2240 // If we stall for any reason, bump the cycle.
Jonas Paulsson238c14b2017-10-25 08:23:33 +00002241 if (NextCycle > CurrCycle)
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002242 bumpCycle(NextCycle);
Jonas Paulsson238c14b2017-10-25 08:23:33 +00002243 else
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002244 // After updating ZoneCritResIdx and ExpectedLatency, check if we're
Alp Tokercb402912014-01-24 17:20:08 +00002245 // resource limited. If a stall occurred, bumpCycle does this.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002246 IsResourceLimited =
Jonas Paulsson238c14b2017-10-25 08:23:33 +00002247 checkResourceLimit(SchedModel->getLatencyFactor(), getCriticalCount(),
2248 getScheduledLatency());
2249
Andrew Trick5a22df42013-12-05 17:56:02 +00002250 // Update CurrMOps after calling bumpCycle to handle stalls, since bumpCycle
2251 // resets CurrMOps. Loop to handle instructions with more MOps than issue in
2252 // one cycle. Since we commonly reach the max MOps here, opportunistically
2253 // bump the cycle to avoid uselessly checking everything in the readyQ.
2254 CurrMOps += IncMOps;
Javed Absar3d594372017-03-27 20:46:37 +00002255
2256 // Bump the cycle count for issue group constraints.
2257 // This must be done after NextCycle has been adjust for all other stalls.
2258 // Calling bumpCycle(X) will reduce CurrMOps by one issue group and set
2259 // currCycle to X.
2260 if ((isTop() && SchedModel->mustEndGroup(SU->getInstr())) ||
2261 (!isTop() && SchedModel->mustBeginGroup(SU->getInstr()))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002262 LLVM_DEBUG(dbgs() << " Bump cycle to " << (isTop() ? "end" : "begin")
2263 << " group\n");
Javed Absar3d594372017-03-27 20:46:37 +00002264 bumpCycle(++NextCycle);
2265 }
2266
Andrew Trick5a22df42013-12-05 17:56:02 +00002267 while (CurrMOps >= SchedModel->getIssueWidth()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002268 LLVM_DEBUG(dbgs() << " *** Max MOps " << CurrMOps << " at cycle "
2269 << CurrCycle << '\n');
Andrew Trickd14d7c22013-12-28 21:56:57 +00002270 bumpCycle(++NextCycle);
Andrew Trick5a22df42013-12-05 17:56:02 +00002271 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002272 LLVM_DEBUG(dumpScheduledState());
Andrew Trick45446062012-06-05 21:11:27 +00002273}
2274
Andrew Trick61f1a272012-05-24 22:11:09 +00002275/// Release pending ready nodes in to the available queue. This makes them
2276/// visible to heuristics.
Andrew Trickfc127d12013-12-07 05:59:44 +00002277void SchedBoundary::releasePending() {
Andrew Trick61f1a272012-05-24 22:11:09 +00002278 // If the available queue is empty, it is safe to reset MinReadyCycle.
2279 if (Available.empty())
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00002280 MinReadyCycle = std::numeric_limits<unsigned>::max();
Andrew Trick61f1a272012-05-24 22:11:09 +00002281
2282 // Check to see if any of the pending instructions are ready to issue. If
2283 // so, add them to the available queue.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002284 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
Andrew Trick61f1a272012-05-24 22:11:09 +00002285 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
2286 SUnit *SU = *(Pending.begin()+i);
Andrew Trick45446062012-06-05 21:11:27 +00002287 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
Andrew Trick61f1a272012-05-24 22:11:09 +00002288
2289 if (ReadyCycle < MinReadyCycle)
2290 MinReadyCycle = ReadyCycle;
2291
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002292 if (!IsBuffered && ReadyCycle > CurrCycle)
Andrew Trick61f1a272012-05-24 22:11:09 +00002293 continue;
2294
Andrew Trick8c9e6722012-06-29 03:23:24 +00002295 if (checkHazard(SU))
Andrew Trick61f1a272012-05-24 22:11:09 +00002296 continue;
2297
Matthias Braun6493bc22016-04-22 19:09:17 +00002298 if (Available.size() >= ReadyListLimit)
2299 break;
2300
Andrew Trick61f1a272012-05-24 22:11:09 +00002301 Available.push(SU);
2302 Pending.remove(Pending.begin()+i);
2303 --i; --e;
2304 }
2305 CheckPending = false;
2306}
2307
2308/// Remove SU from the ready set for this boundary.
Andrew Trickfc127d12013-12-07 05:59:44 +00002309void SchedBoundary::removeReady(SUnit *SU) {
Andrew Trick61f1a272012-05-24 22:11:09 +00002310 if (Available.isInQueue(SU))
2311 Available.remove(Available.find(SU));
2312 else {
2313 assert(Pending.isInQueue(SU) && "bad ready count");
2314 Pending.remove(Pending.find(SU));
2315 }
2316}
2317
2318/// If this queue only has one ready candidate, return it. As a side effect,
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002319/// defer any nodes that now hit a hazard, and advance the cycle until at least
2320/// one node is ready. If multiple instructions are ready, return NULL.
Andrew Trickfc127d12013-12-07 05:59:44 +00002321SUnit *SchedBoundary::pickOnlyChoice() {
Andrew Trick61f1a272012-05-24 22:11:09 +00002322 if (CheckPending)
2323 releasePending();
2324
Andrew Tricke2ff5752013-06-15 04:49:49 +00002325 if (CurrMOps > 0) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002326 // Defer any ready instrs that now have a hazard.
2327 for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
2328 if (checkHazard(*I)) {
2329 Pending.push(*I);
2330 I = Available.remove(I);
2331 continue;
2332 }
2333 ++I;
2334 }
2335 }
Andrew Trick61f1a272012-05-24 22:11:09 +00002336 for (unsigned i = 0; Available.empty(); ++i) {
Chad Rosieraba845e2014-07-02 16:46:08 +00002337// FIXME: Re-enable assert once PR20057 is resolved.
2338// assert(i <= (HazardRec->getMaxLookAhead() + MaxObservedStall) &&
2339// "permanent hazard");
2340 (void)i;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002341 bumpCycle(CurrCycle + 1);
Andrew Trick61f1a272012-05-24 22:11:09 +00002342 releasePending();
2343 }
Matthias Braund29d31e2016-06-23 21:27:38 +00002344
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002345 LLVM_DEBUG(Pending.dump());
2346 LLVM_DEBUG(Available.dump());
Matthias Braund29d31e2016-06-23 21:27:38 +00002347
Andrew Trick61f1a272012-05-24 22:11:09 +00002348 if (Available.size() == 1)
2349 return *Available.begin();
Craig Topperc0196b12014-04-14 00:51:57 +00002350 return nullptr;
Andrew Trick61f1a272012-05-24 22:11:09 +00002351}
2352
Aaron Ballman615eb472017-10-15 14:32:27 +00002353#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002354// This is useful information to dump after bumpNode.
2355// Note that the Queue contents are more useful before pickNodeFromQueue.
Sam Clegg705f7982017-06-21 22:19:17 +00002356LLVM_DUMP_METHOD void SchedBoundary::dumpScheduledState() const {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002357 unsigned ResFactor;
2358 unsigned ResCount;
2359 if (ZoneCritResIdx) {
2360 ResFactor = SchedModel->getResourceFactor(ZoneCritResIdx);
2361 ResCount = getResourceCount(ZoneCritResIdx);
Matthias Braunb550b762016-04-21 01:54:13 +00002362 } else {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002363 ResFactor = SchedModel->getMicroOpFactor();
Javed Absar1a77bcc2017-09-27 10:31:58 +00002364 ResCount = RetiredMOps * ResFactor;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002365 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002366 unsigned LFactor = SchedModel->getLatencyFactor();
2367 dbgs() << Available.getName() << " @" << CurrCycle << "c\n"
2368 << " Retired: " << RetiredMOps;
2369 dbgs() << "\n Executed: " << getExecutedCount() / LFactor << "c";
2370 dbgs() << "\n Critical: " << ResCount / LFactor << "c, "
Andrew Trickfc127d12013-12-07 05:59:44 +00002371 << ResCount / ResFactor << " "
2372 << SchedModel->getResourceName(ZoneCritResIdx)
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002373 << "\n ExpectedLatency: " << ExpectedLatency << "c\n"
2374 << (IsResourceLimited ? " - Resource" : " - Latency")
2375 << " limited.\n";
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002376}
Andrew Trick8e8415f2013-06-15 05:46:47 +00002377#endif
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002378
Andrew Trickfc127d12013-12-07 05:59:44 +00002379//===----------------------------------------------------------------------===//
Andrew Trickd14d7c22013-12-28 21:56:57 +00002380// GenericScheduler - Generic implementation of MachineSchedStrategy.
Andrew Trickfc127d12013-12-07 05:59:44 +00002381//===----------------------------------------------------------------------===//
2382
Andrew Trickd14d7c22013-12-28 21:56:57 +00002383void GenericSchedulerBase::SchedCandidate::
2384initResourceDelta(const ScheduleDAGMI *DAG,
2385 const TargetSchedModel *SchedModel) {
2386 if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
2387 return;
2388
2389 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
2390 for (TargetSchedModel::ProcResIter
2391 PI = SchedModel->getWriteProcResBegin(SC),
2392 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2393 if (PI->ProcResourceIdx == Policy.ReduceResIdx)
2394 ResDelta.CritResources += PI->Cycles;
2395 if (PI->ProcResourceIdx == Policy.DemandResIdx)
2396 ResDelta.DemandedResources += PI->Cycles;
2397 }
2398}
2399
2400/// Set the CandPolicy given a scheduling zone given the current resources and
2401/// latencies inside and outside the zone.
Matthias Braunb550b762016-04-21 01:54:13 +00002402void GenericSchedulerBase::setPolicy(CandPolicy &Policy, bool IsPostRA,
Andrew Trickd14d7c22013-12-28 21:56:57 +00002403 SchedBoundary &CurrZone,
2404 SchedBoundary *OtherZone) {
Eric Christopher572e03a2015-06-19 01:53:21 +00002405 // Apply preemptive heuristics based on the total latency and resources
Andrew Trickd14d7c22013-12-28 21:56:57 +00002406 // inside and outside this zone. Potential stalls should be considered before
2407 // following this policy.
2408
2409 // Compute remaining latency. We need this both to determine whether the
2410 // overall schedule has become latency-limited and whether the instructions
2411 // outside this zone are resource or latency limited.
2412 //
2413 // The "dependent" latency is updated incrementally during scheduling as the
2414 // max height/depth of scheduled nodes minus the cycles since it was
2415 // scheduled:
2416 // DLat = max (N.depth - (CurrCycle - N.ReadyCycle) for N in Zone
2417 //
2418 // The "independent" latency is the max ready queue depth:
2419 // ILat = max N.depth for N in Available|Pending
2420 //
2421 // RemainingLatency is the greater of independent and dependent latency.
2422 unsigned RemLatency = CurrZone.getDependentLatency();
2423 RemLatency = std::max(RemLatency,
2424 CurrZone.findMaxLatency(CurrZone.Available.elements()));
2425 RemLatency = std::max(RemLatency,
2426 CurrZone.findMaxLatency(CurrZone.Pending.elements()));
2427
2428 // Compute the critical resource outside the zone.
Andrew Trick7afe4812013-12-28 22:25:57 +00002429 unsigned OtherCritIdx = 0;
Andrew Trickd14d7c22013-12-28 21:56:57 +00002430 unsigned OtherCount =
2431 OtherZone ? OtherZone->getOtherResourceCount(OtherCritIdx) : 0;
2432
2433 bool OtherResLimited = false;
Jonas Paulsson238c14b2017-10-25 08:23:33 +00002434 if (SchedModel->hasInstrSchedModel())
2435 OtherResLimited = checkResourceLimit(SchedModel->getLatencyFactor(),
2436 OtherCount, RemLatency);
2437
Andrew Trickd14d7c22013-12-28 21:56:57 +00002438 // Schedule aggressively for latency in PostRA mode. We don't check for
2439 // acyclic latency during PostRA, and highly out-of-order processors will
2440 // skip PostRA scheduling.
2441 if (!OtherResLimited) {
2442 if (IsPostRA || (RemLatency + CurrZone.getCurrCycle() > Rem.CriticalPath)) {
2443 Policy.ReduceLatency |= true;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002444 LLVM_DEBUG(dbgs() << " " << CurrZone.Available.getName()
2445 << " RemainingLatency " << RemLatency << " + "
2446 << CurrZone.getCurrCycle() << "c > CritPath "
2447 << Rem.CriticalPath << "\n");
Andrew Trickd14d7c22013-12-28 21:56:57 +00002448 }
2449 }
2450 // If the same resource is limiting inside and outside the zone, do nothing.
2451 if (CurrZone.getZoneCritResIdx() == OtherCritIdx)
2452 return;
2453
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002454 LLVM_DEBUG(if (CurrZone.isResourceLimited()) {
2455 dbgs() << " " << CurrZone.Available.getName() << " ResourceLimited: "
2456 << SchedModel->getResourceName(CurrZone.getZoneCritResIdx()) << "\n";
2457 } if (OtherResLimited) dbgs()
2458 << " RemainingLimit: "
2459 << SchedModel->getResourceName(OtherCritIdx) << "\n";
2460 if (!CurrZone.isResourceLimited() && !OtherResLimited) dbgs()
2461 << " Latency limited both directions.\n");
Andrew Trickd14d7c22013-12-28 21:56:57 +00002462
2463 if (CurrZone.isResourceLimited() && !Policy.ReduceResIdx)
2464 Policy.ReduceResIdx = CurrZone.getZoneCritResIdx();
2465
2466 if (OtherResLimited)
2467 Policy.DemandResIdx = OtherCritIdx;
2468}
2469
2470#ifndef NDEBUG
2471const char *GenericSchedulerBase::getReasonStr(
2472 GenericSchedulerBase::CandReason Reason) {
2473 switch (Reason) {
2474 case NoCand: return "NOCAND ";
Matthias Braun49cb6e92016-05-27 22:14:26 +00002475 case Only1: return "ONLY1 ";
2476 case PhysRegCopy: return "PREG-COPY ";
Andrew Trickd14d7c22013-12-28 21:56:57 +00002477 case RegExcess: return "REG-EXCESS";
2478 case RegCritical: return "REG-CRIT ";
2479 case Stall: return "STALL ";
2480 case Cluster: return "CLUSTER ";
2481 case Weak: return "WEAK ";
2482 case RegMax: return "REG-MAX ";
2483 case ResourceReduce: return "RES-REDUCE";
2484 case ResourceDemand: return "RES-DEMAND";
2485 case TopDepthReduce: return "TOP-DEPTH ";
2486 case TopPathReduce: return "TOP-PATH ";
2487 case BotHeightReduce:return "BOT-HEIGHT";
2488 case BotPathReduce: return "BOT-PATH ";
2489 case NextDefUse: return "DEF-USE ";
2490 case NodeOrder: return "ORDER ";
2491 };
2492 llvm_unreachable("Unknown reason!");
2493}
2494
2495void GenericSchedulerBase::traceCandidate(const SchedCandidate &Cand) {
2496 PressureChange P;
2497 unsigned ResIdx = 0;
2498 unsigned Latency = 0;
2499 switch (Cand.Reason) {
2500 default:
2501 break;
2502 case RegExcess:
2503 P = Cand.RPDelta.Excess;
2504 break;
2505 case RegCritical:
2506 P = Cand.RPDelta.CriticalMax;
2507 break;
2508 case RegMax:
2509 P = Cand.RPDelta.CurrentMax;
2510 break;
2511 case ResourceReduce:
2512 ResIdx = Cand.Policy.ReduceResIdx;
2513 break;
2514 case ResourceDemand:
2515 ResIdx = Cand.Policy.DemandResIdx;
2516 break;
2517 case TopDepthReduce:
2518 Latency = Cand.SU->getDepth();
2519 break;
2520 case TopPathReduce:
2521 Latency = Cand.SU->getHeight();
2522 break;
2523 case BotHeightReduce:
2524 Latency = Cand.SU->getHeight();
2525 break;
2526 case BotPathReduce:
2527 Latency = Cand.SU->getDepth();
2528 break;
2529 }
James Y Knighte72b0db2015-09-18 18:52:20 +00002530 dbgs() << " Cand SU(" << Cand.SU->NodeNum << ") " << getReasonStr(Cand.Reason);
Andrew Trickd14d7c22013-12-28 21:56:57 +00002531 if (P.isValid())
2532 dbgs() << " " << TRI->getRegPressureSetName(P.getPSet())
2533 << ":" << P.getUnitInc() << " ";
2534 else
2535 dbgs() << " ";
2536 if (ResIdx)
2537 dbgs() << " " << SchedModel->getProcResource(ResIdx)->Name << " ";
2538 else
2539 dbgs() << " ";
2540 if (Latency)
2541 dbgs() << " " << Latency << " cycles ";
2542 else
2543 dbgs() << " ";
2544 dbgs() << '\n';
2545}
2546#endif
2547
Jonas Paulssone8f1ac72018-04-12 07:21:39 +00002548namespace llvm {
Andrew Trickd14d7c22013-12-28 21:56:57 +00002549/// Return true if this heuristic determines order.
Jonas Paulssone8f1ac72018-04-12 07:21:39 +00002550bool tryLess(int TryVal, int CandVal,
2551 GenericSchedulerBase::SchedCandidate &TryCand,
2552 GenericSchedulerBase::SchedCandidate &Cand,
2553 GenericSchedulerBase::CandReason Reason) {
Andrew Trickd14d7c22013-12-28 21:56:57 +00002554 if (TryVal < CandVal) {
2555 TryCand.Reason = Reason;
2556 return true;
2557 }
2558 if (TryVal > CandVal) {
2559 if (Cand.Reason > Reason)
2560 Cand.Reason = Reason;
2561 return true;
2562 }
Andrew Trickd14d7c22013-12-28 21:56:57 +00002563 return false;
2564}
2565
Jonas Paulssone8f1ac72018-04-12 07:21:39 +00002566bool tryGreater(int TryVal, int CandVal,
2567 GenericSchedulerBase::SchedCandidate &TryCand,
2568 GenericSchedulerBase::SchedCandidate &Cand,
2569 GenericSchedulerBase::CandReason Reason) {
Andrew Trickd14d7c22013-12-28 21:56:57 +00002570 if (TryVal > CandVal) {
2571 TryCand.Reason = Reason;
2572 return true;
2573 }
2574 if (TryVal < CandVal) {
2575 if (Cand.Reason > Reason)
2576 Cand.Reason = Reason;
2577 return true;
2578 }
Andrew Trickd14d7c22013-12-28 21:56:57 +00002579 return false;
2580}
2581
Jonas Paulssone8f1ac72018-04-12 07:21:39 +00002582bool tryLatency(GenericSchedulerBase::SchedCandidate &TryCand,
2583 GenericSchedulerBase::SchedCandidate &Cand,
2584 SchedBoundary &Zone) {
Andrew Trickd14d7c22013-12-28 21:56:57 +00002585 if (Zone.isTop()) {
2586 if (Cand.SU->getDepth() > Zone.getScheduledLatency()) {
2587 if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2588 TryCand, Cand, GenericSchedulerBase::TopDepthReduce))
2589 return true;
2590 }
2591 if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2592 TryCand, Cand, GenericSchedulerBase::TopPathReduce))
2593 return true;
Matthias Braunb550b762016-04-21 01:54:13 +00002594 } else {
Andrew Trickd14d7c22013-12-28 21:56:57 +00002595 if (Cand.SU->getHeight() > Zone.getScheduledLatency()) {
2596 if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2597 TryCand, Cand, GenericSchedulerBase::BotHeightReduce))
2598 return true;
2599 }
2600 if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2601 TryCand, Cand, GenericSchedulerBase::BotPathReduce))
2602 return true;
2603 }
2604 return false;
2605}
Jonas Paulssone8f1ac72018-04-12 07:21:39 +00002606} // end namespace llvm
Andrew Trickd14d7c22013-12-28 21:56:57 +00002607
Matthias Braun49cb6e92016-05-27 22:14:26 +00002608static void tracePick(GenericSchedulerBase::CandReason Reason, bool IsTop) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002609 LLVM_DEBUG(dbgs() << "Pick " << (IsTop ? "Top " : "Bot ")
2610 << GenericSchedulerBase::getReasonStr(Reason) << '\n');
Matthias Braun49cb6e92016-05-27 22:14:26 +00002611}
2612
Matthias Braun6ad3d052016-06-25 00:23:00 +00002613static void tracePick(const GenericSchedulerBase::SchedCandidate &Cand) {
2614 tracePick(Cand.Reason, Cand.AtTop);
Andrew Trickd14d7c22013-12-28 21:56:57 +00002615}
2616
Andrew Trickfc127d12013-12-07 05:59:44 +00002617void GenericScheduler::initialize(ScheduleDAGMI *dag) {
Andrew Trickd7f890e2013-12-28 21:56:47 +00002618 assert(dag->hasVRegLiveness() &&
2619 "(PreRA)GenericScheduler needs vreg liveness");
2620 DAG = static_cast<ScheduleDAGMILive*>(dag);
Andrew Trickfc127d12013-12-07 05:59:44 +00002621 SchedModel = DAG->getSchedModel();
2622 TRI = DAG->TRI;
2623
2624 Rem.init(DAG, SchedModel);
2625 Top.init(DAG, SchedModel, &Rem);
2626 Bot.init(DAG, SchedModel, &Rem);
2627
2628 // Initialize resource counts.
2629
2630 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
2631 // are disabled, then these HazardRecs will be disabled.
2632 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
Andrew Trickfc127d12013-12-07 05:59:44 +00002633 if (!Top.HazardRec) {
2634 Top.HazardRec =
Eric Christopher99556d72014-10-14 06:56:25 +00002635 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
Eric Christopherd9134482014-08-04 21:25:23 +00002636 Itin, DAG);
Andrew Trickfc127d12013-12-07 05:59:44 +00002637 }
2638 if (!Bot.HazardRec) {
2639 Bot.HazardRec =
Eric Christopher99556d72014-10-14 06:56:25 +00002640 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
Eric Christopherd9134482014-08-04 21:25:23 +00002641 Itin, DAG);
Andrew Trickfc127d12013-12-07 05:59:44 +00002642 }
Matthias Brauncc676c42016-06-25 02:03:36 +00002643 TopCand.SU = nullptr;
2644 BotCand.SU = nullptr;
Andrew Trickfc127d12013-12-07 05:59:44 +00002645}
2646
2647/// Initialize the per-region scheduling policy.
2648void GenericScheduler::initPolicy(MachineBasicBlock::iterator Begin,
2649 MachineBasicBlock::iterator End,
2650 unsigned NumRegionInstrs) {
Justin Bognerfdf9bf42017-10-10 23:50:49 +00002651 const MachineFunction &MF = *Begin->getMF();
Eric Christopher99556d72014-10-14 06:56:25 +00002652 const TargetLowering *TLI = MF.getSubtarget().getTargetLowering();
Andrew Trickfc127d12013-12-07 05:59:44 +00002653
2654 // Avoid setting up the register pressure tracker for small regions to save
2655 // compile time. As a rough heuristic, only track pressure when the number of
2656 // schedulable instructions exceeds half the integer register file.
Andrew Trick350ff2c2014-01-21 21:27:37 +00002657 RegionPolicy.ShouldTrackPressure = true;
Andrew Trick46753512014-01-22 03:38:55 +00002658 for (unsigned VT = MVT::i32; VT > (unsigned)MVT::i1; --VT) {
2659 MVT::SimpleValueType LegalIntVT = (MVT::SimpleValueType)VT;
2660 if (TLI->isTypeLegal(LegalIntVT)) {
Andrew Trick350ff2c2014-01-21 21:27:37 +00002661 unsigned NIntRegs = Context->RegClassInfo->getNumAllocatableRegs(
Andrew Trick46753512014-01-22 03:38:55 +00002662 TLI->getRegClassFor(LegalIntVT));
Andrew Trick350ff2c2014-01-21 21:27:37 +00002663 RegionPolicy.ShouldTrackPressure = NumRegionInstrs > (NIntRegs / 2);
2664 }
2665 }
Andrew Trickfc127d12013-12-07 05:59:44 +00002666
2667 // For generic targets, we default to bottom-up, because it's simpler and more
2668 // compile-time optimizations have been implemented in that direction.
2669 RegionPolicy.OnlyBottomUp = true;
2670
2671 // Allow the subtarget to override default policy.
Duncan P. N. Exon Smith63298722016-07-01 00:23:27 +00002672 MF.getSubtarget().overrideSchedPolicy(RegionPolicy, NumRegionInstrs);
Andrew Trickfc127d12013-12-07 05:59:44 +00002673
2674 // After subtarget overrides, apply command line options.
2675 if (!EnableRegPressure)
2676 RegionPolicy.ShouldTrackPressure = false;
2677
2678 // Check -misched-topdown/bottomup can force or unforce scheduling direction.
2679 // e.g. -misched-bottomup=false allows scheduling in both directions.
2680 assert((!ForceTopDown || !ForceBottomUp) &&
2681 "-misched-topdown incompatible with -misched-bottomup");
2682 if (ForceBottomUp.getNumOccurrences() > 0) {
2683 RegionPolicy.OnlyBottomUp = ForceBottomUp;
2684 if (RegionPolicy.OnlyBottomUp)
2685 RegionPolicy.OnlyTopDown = false;
2686 }
2687 if (ForceTopDown.getNumOccurrences() > 0) {
2688 RegionPolicy.OnlyTopDown = ForceTopDown;
2689 if (RegionPolicy.OnlyTopDown)
2690 RegionPolicy.OnlyBottomUp = false;
2691 }
2692}
2693
Sam Clegg705f7982017-06-21 22:19:17 +00002694void GenericScheduler::dumpPolicy() const {
Matthias Braun8c209aa2017-01-28 02:02:38 +00002695 // Cannot completely remove virtual function even in release mode.
Aaron Ballman615eb472017-10-15 14:32:27 +00002696#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
James Y Knighte72b0db2015-09-18 18:52:20 +00002697 dbgs() << "GenericScheduler RegionPolicy: "
2698 << " ShouldTrackPressure=" << RegionPolicy.ShouldTrackPressure
2699 << " OnlyTopDown=" << RegionPolicy.OnlyTopDown
2700 << " OnlyBottomUp=" << RegionPolicy.OnlyBottomUp
2701 << "\n";
Matthias Braun8c209aa2017-01-28 02:02:38 +00002702#endif
James Y Knighte72b0db2015-09-18 18:52:20 +00002703}
2704
Andrew Trickfc127d12013-12-07 05:59:44 +00002705/// Set IsAcyclicLatencyLimited if the acyclic path is longer than the cyclic
2706/// critical path by more cycles than it takes to drain the instruction buffer.
2707/// We estimate an upper bounds on in-flight instructions as:
2708///
2709/// CyclesPerIteration = max( CyclicPath, Loop-Resource-Height )
2710/// InFlightIterations = AcyclicPath / CyclesPerIteration
2711/// InFlightResources = InFlightIterations * LoopResources
2712///
2713/// TODO: Check execution resources in addition to IssueCount.
2714void GenericScheduler::checkAcyclicLatency() {
2715 if (Rem.CyclicCritPath == 0 || Rem.CyclicCritPath >= Rem.CriticalPath)
2716 return;
2717
2718 // Scaled number of cycles per loop iteration.
2719 unsigned IterCount =
2720 std::max(Rem.CyclicCritPath * SchedModel->getLatencyFactor(),
2721 Rem.RemIssueCount);
2722 // Scaled acyclic critical path.
2723 unsigned AcyclicCount = Rem.CriticalPath * SchedModel->getLatencyFactor();
2724 // InFlightCount = (AcyclicPath / IterCycles) * InstrPerLoop
2725 unsigned InFlightCount =
2726 (AcyclicCount * Rem.RemIssueCount + IterCount-1) / IterCount;
2727 unsigned BufferLimit =
2728 SchedModel->getMicroOpBufferSize() * SchedModel->getMicroOpFactor();
2729
2730 Rem.IsAcyclicLatencyLimited = InFlightCount > BufferLimit;
2731
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002732 LLVM_DEBUG(
2733 dbgs() << "IssueCycles="
2734 << Rem.RemIssueCount / SchedModel->getLatencyFactor() << "c "
2735 << "IterCycles=" << IterCount / SchedModel->getLatencyFactor()
2736 << "c NumIters=" << (AcyclicCount + IterCount - 1) / IterCount
2737 << " InFlight=" << InFlightCount / SchedModel->getMicroOpFactor()
2738 << "m BufferLim=" << SchedModel->getMicroOpBufferSize() << "m\n";
2739 if (Rem.IsAcyclicLatencyLimited) dbgs() << " ACYCLIC LATENCY LIMIT\n");
Andrew Trickfc127d12013-12-07 05:59:44 +00002740}
2741
2742void GenericScheduler::registerRoots() {
2743 Rem.CriticalPath = DAG->ExitSU.getDepth();
2744
2745 // Some roots may not feed into ExitSU. Check all of them in case.
Javed Absare3a0cc22017-06-21 09:10:10 +00002746 for (const SUnit *SU : Bot.Available) {
2747 if (SU->getDepth() > Rem.CriticalPath)
2748 Rem.CriticalPath = SU->getDepth();
Andrew Trickfc127d12013-12-07 05:59:44 +00002749 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002750 LLVM_DEBUG(dbgs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << '\n');
Gerolf Hoflehnerb5220dc2014-08-07 21:49:44 +00002751 if (DumpCriticalPathLength) {
2752 errs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << " \n";
2753 }
Andrew Trickfc127d12013-12-07 05:59:44 +00002754
Matthias Braun99551052017-04-12 18:09:05 +00002755 if (EnableCyclicPath && SchedModel->getMicroOpBufferSize() > 0) {
Andrew Trickfc127d12013-12-07 05:59:44 +00002756 Rem.CyclicCritPath = DAG->computeCyclicCriticalPath();
2757 checkAcyclicLatency();
2758 }
2759}
2760
Jonas Paulssone8f1ac72018-04-12 07:21:39 +00002761namespace llvm {
2762bool tryPressure(const PressureChange &TryP,
2763 const PressureChange &CandP,
2764 GenericSchedulerBase::SchedCandidate &TryCand,
2765 GenericSchedulerBase::SchedCandidate &Cand,
2766 GenericSchedulerBase::CandReason Reason,
2767 const TargetRegisterInfo *TRI,
2768 const MachineFunction &MF) {
Andrew Trickb1a45b62013-08-30 04:27:29 +00002769 // If one candidate decreases and the other increases, go with it.
2770 // Invalid candidates have UnitInc==0.
Hal Finkel7a87f8a2014-10-10 17:06:20 +00002771 if (tryGreater(TryP.getUnitInc() < 0, CandP.getUnitInc() < 0, TryCand, Cand,
2772 Reason)) {
Andrew Trickb1a45b62013-08-30 04:27:29 +00002773 return true;
2774 }
Matthias Braun6ad3d052016-06-25 00:23:00 +00002775 // Do not compare the magnitude of pressure changes between top and bottom
2776 // boundary.
2777 if (Cand.AtTop != TryCand.AtTop)
2778 return false;
2779
2780 // If both candidates affect the same set in the same boundary, go with the
2781 // smallest increase.
2782 unsigned TryPSet = TryP.getPSetOrMax();
2783 unsigned CandPSet = CandP.getPSetOrMax();
2784 if (TryPSet == CandPSet) {
2785 return tryLess(TryP.getUnitInc(), CandP.getUnitInc(), TryCand, Cand,
2786 Reason);
2787 }
Tom Stellard5ce53062015-12-16 18:31:01 +00002788
2789 int TryRank = TryP.isValid() ? TRI->getRegPressureSetScore(MF, TryPSet) :
2790 std::numeric_limits<int>::max();
2791
2792 int CandRank = CandP.isValid() ? TRI->getRegPressureSetScore(MF, CandPSet) :
2793 std::numeric_limits<int>::max();
2794
Andrew Trick401b6952013-07-25 07:26:35 +00002795 // If the candidates are decreasing pressure, reverse priority.
Andrew Trick1a831342013-08-30 03:49:48 +00002796 if (TryP.getUnitInc() < 0)
Andrew Trick401b6952013-07-25 07:26:35 +00002797 std::swap(TryRank, CandRank);
2798 return tryGreater(TryRank, CandRank, TryCand, Cand, Reason);
2799}
2800
Jonas Paulssone8f1ac72018-04-12 07:21:39 +00002801unsigned getWeakLeft(const SUnit *SU, bool isTop) {
Andrew Tricka7714a02012-11-12 19:40:10 +00002802 return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
2803}
2804
Andrew Tricke833e1c2013-04-13 06:07:40 +00002805/// Minimize physical register live ranges. Regalloc wants them adjacent to
2806/// their physreg def/use.
2807///
2808/// FIXME: This is an unnecessary check on the critical path. Most are root/leaf
2809/// copies which can be prescheduled. The rest (e.g. x86 MUL) could be bundled
2810/// with the operation that produces or consumes the physreg. We'll do this when
2811/// regalloc has support for parallel copies.
Jonas Paulssone8f1ac72018-04-12 07:21:39 +00002812int biasPhysRegCopy(const SUnit *SU, bool isTop) {
Andrew Tricke833e1c2013-04-13 06:07:40 +00002813 const MachineInstr *MI = SU->getInstr();
2814 if (!MI->isCopy())
2815 return 0;
2816
2817 unsigned ScheduledOper = isTop ? 1 : 0;
2818 unsigned UnscheduledOper = isTop ? 0 : 1;
2819 // If we have already scheduled the physreg produce/consumer, immediately
2820 // schedule the copy.
2821 if (TargetRegisterInfo::isPhysicalRegister(
2822 MI->getOperand(ScheduledOper).getReg()))
2823 return 1;
2824 // If the physreg is at the boundary, defer it. Otherwise schedule it
2825 // immediately to free the dependent. We can hoist the copy later.
2826 bool AtBoundary = isTop ? !SU->NumSuccsLeft : !SU->NumPredsLeft;
2827 if (TargetRegisterInfo::isPhysicalRegister(
2828 MI->getOperand(UnscheduledOper).getReg()))
2829 return AtBoundary ? -1 : 1;
2830 return 0;
2831}
Jonas Paulssone8f1ac72018-04-12 07:21:39 +00002832} // end namespace llvm
Andrew Tricke833e1c2013-04-13 06:07:40 +00002833
Matthias Braun4f573772016-04-22 19:10:15 +00002834void GenericScheduler::initCandidate(SchedCandidate &Cand, SUnit *SU,
2835 bool AtTop,
2836 const RegPressureTracker &RPTracker,
2837 RegPressureTracker &TempTracker) {
2838 Cand.SU = SU;
Matthias Braun6ad3d052016-06-25 00:23:00 +00002839 Cand.AtTop = AtTop;
Matthias Braun4f573772016-04-22 19:10:15 +00002840 if (DAG->isTrackingPressure()) {
2841 if (AtTop) {
2842 TempTracker.getMaxDownwardPressureDelta(
2843 Cand.SU->getInstr(),
2844 Cand.RPDelta,
2845 DAG->getRegionCriticalPSets(),
2846 DAG->getRegPressure().MaxSetPressure);
2847 } else {
2848 if (VerifyScheduling) {
2849 TempTracker.getMaxUpwardPressureDelta(
2850 Cand.SU->getInstr(),
2851 &DAG->getPressureDiff(Cand.SU),
2852 Cand.RPDelta,
2853 DAG->getRegionCriticalPSets(),
2854 DAG->getRegPressure().MaxSetPressure);
2855 } else {
2856 RPTracker.getUpwardPressureDelta(
2857 Cand.SU->getInstr(),
2858 DAG->getPressureDiff(Cand.SU),
2859 Cand.RPDelta,
2860 DAG->getRegionCriticalPSets(),
2861 DAG->getRegPressure().MaxSetPressure);
2862 }
2863 }
2864 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002865 LLVM_DEBUG(if (Cand.RPDelta.Excess.isValid()) dbgs()
2866 << " Try SU(" << Cand.SU->NodeNum << ") "
2867 << TRI->getRegPressureSetName(Cand.RPDelta.Excess.getPSet()) << ":"
2868 << Cand.RPDelta.Excess.getUnitInc() << "\n");
Matthias Braun4f573772016-04-22 19:10:15 +00002869}
2870
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002871/// Apply a set of heursitics to a new candidate. Heuristics are currently
2872/// hierarchical. This may be more efficient than a graduated cost model because
2873/// we don't need to evaluate all aspects of the model for each node in the
2874/// queue. But it's really done to make the heuristics easier to debug and
2875/// statistically analyze.
2876///
2877/// \param Cand provides the policy and current best candidate.
2878/// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
Matthias Braun6ad3d052016-06-25 00:23:00 +00002879/// \param Zone describes the scheduled zone that we are extending, or nullptr
2880// if Cand is from a different zone than TryCand.
Andrew Trick665d3ec2013-09-19 23:10:59 +00002881void GenericScheduler::tryCandidate(SchedCandidate &Cand,
Andrew Trickbb1247b2013-12-05 17:55:47 +00002882 SchedCandidate &TryCand,
Jonas Paulssone8f1ac72018-04-12 07:21:39 +00002883 SchedBoundary *Zone) const {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002884 // Initialize the candidate if needed.
2885 if (!Cand.isValid()) {
2886 TryCand.Reason = NodeOrder;
2887 return;
2888 }
Andrew Tricke833e1c2013-04-13 06:07:40 +00002889
Matthias Braun6ad3d052016-06-25 00:23:00 +00002890 if (tryGreater(biasPhysRegCopy(TryCand.SU, TryCand.AtTop),
2891 biasPhysRegCopy(Cand.SU, Cand.AtTop),
Andrew Tricke833e1c2013-04-13 06:07:40 +00002892 TryCand, Cand, PhysRegCopy))
2893 return;
2894
Andrew Tricke02d5da2015-05-17 23:40:27 +00002895 // Avoid exceeding the target's limit.
Andrew Trick66c3dfb2013-09-04 21:00:11 +00002896 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.Excess,
2897 Cand.RPDelta.Excess,
Tom Stellard5ce53062015-12-16 18:31:01 +00002898 TryCand, Cand, RegExcess, TRI,
2899 DAG->MF))
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002900 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002901
2902 // Avoid increasing the max critical pressure in the scheduled region.
Andrew Trick66c3dfb2013-09-04 21:00:11 +00002903 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CriticalMax,
2904 Cand.RPDelta.CriticalMax,
Tom Stellard5ce53062015-12-16 18:31:01 +00002905 TryCand, Cand, RegCritical, TRI,
2906 DAG->MF))
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002907 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002908
Matthias Braun6ad3d052016-06-25 00:23:00 +00002909 // We only compare a subset of features when comparing nodes between
2910 // Top and Bottom boundary. Some properties are simply incomparable, in many
2911 // other instances we should only override the other boundary if something
2912 // is a clear good pick on one boundary. Skip heuristics that are more
2913 // "tie-breaking" in nature.
2914 bool SameBoundary = Zone != nullptr;
2915 if (SameBoundary) {
2916 // For loops that are acyclic path limited, aggressively schedule for
Jonas Paulssonbaeb4022016-11-04 08:31:14 +00002917 // latency. Within an single cycle, whenever CurrMOps > 0, allow normal
2918 // heuristics to take precedence.
Matthias Braun6ad3d052016-06-25 00:23:00 +00002919 if (Rem.IsAcyclicLatencyLimited && !Zone->getCurrMOps() &&
2920 tryLatency(TryCand, Cand, *Zone))
2921 return;
Andrew Trickddffae92013-09-06 17:32:36 +00002922
Matthias Braun6ad3d052016-06-25 00:23:00 +00002923 // Prioritize instructions that read unbuffered resources by stall cycles.
2924 if (tryLess(Zone->getLatencyStallCycles(TryCand.SU),
2925 Zone->getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
2926 return;
2927 }
Andrew Trick880e5732013-12-05 17:55:58 +00002928
Andrew Tricka7714a02012-11-12 19:40:10 +00002929 // Keep clustered nodes together to encourage downstream peephole
2930 // optimizations which may reduce resource requirements.
2931 //
2932 // This is a best effort to set things up for a post-RA pass. Optimizations
2933 // like generating loads of multiple registers should ideally be done within
2934 // the scheduler pass by combining the loads during DAG postprocessing.
Matthias Braun6ad3d052016-06-25 00:23:00 +00002935 const SUnit *CandNextClusterSU =
2936 Cand.AtTop ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
2937 const SUnit *TryCandNextClusterSU =
2938 TryCand.AtTop ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
2939 if (tryGreater(TryCand.SU == TryCandNextClusterSU,
2940 Cand.SU == CandNextClusterSU,
Andrew Tricka7714a02012-11-12 19:40:10 +00002941 TryCand, Cand, Cluster))
2942 return;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00002943
Matthias Braun6ad3d052016-06-25 00:23:00 +00002944 if (SameBoundary) {
2945 // Weak edges are for clustering and other constraints.
2946 if (tryLess(getWeakLeft(TryCand.SU, TryCand.AtTop),
2947 getWeakLeft(Cand.SU, Cand.AtTop),
2948 TryCand, Cand, Weak))
2949 return;
Andrew Tricka7714a02012-11-12 19:40:10 +00002950 }
Matthias Braun6ad3d052016-06-25 00:23:00 +00002951
Andrew Trick71f08a32013-06-17 21:45:13 +00002952 // Avoid increasing the max pressure of the entire region.
Andrew Trick66c3dfb2013-09-04 21:00:11 +00002953 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CurrentMax,
2954 Cand.RPDelta.CurrentMax,
Tom Stellard5ce53062015-12-16 18:31:01 +00002955 TryCand, Cand, RegMax, TRI,
2956 DAG->MF))
Andrew Trick71f08a32013-06-17 21:45:13 +00002957 return;
2958
Matthias Braun6ad3d052016-06-25 00:23:00 +00002959 if (SameBoundary) {
2960 // Avoid critical resource consumption and balance the schedule.
2961 TryCand.initResourceDelta(DAG, SchedModel);
2962 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
2963 TryCand, Cand, ResourceReduce))
2964 return;
2965 if (tryGreater(TryCand.ResDelta.DemandedResources,
2966 Cand.ResDelta.DemandedResources,
2967 TryCand, Cand, ResourceDemand))
2968 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002969
Matthias Braun6ad3d052016-06-25 00:23:00 +00002970 // Avoid serializing long latency dependence chains.
2971 // For acyclic path limited loops, latency was already checked above.
2972 if (!RegionPolicy.DisableLatencyHeuristic && TryCand.Policy.ReduceLatency &&
2973 !Rem.IsAcyclicLatencyLimited && tryLatency(TryCand, Cand, *Zone))
2974 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002975
Matthias Braun6ad3d052016-06-25 00:23:00 +00002976 // Fall through to original instruction order.
2977 if ((Zone->isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
2978 || (!Zone->isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
2979 TryCand.Reason = NodeOrder;
2980 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002981 }
2982}
Andrew Trick419eae22012-05-10 21:06:19 +00002983
Andrew Trickc573cd92013-09-06 17:32:44 +00002984/// Pick the best candidate from the queue.
Andrew Trick7ee9de52012-05-10 21:06:16 +00002985///
2986/// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
2987/// DAG building. To adjust for the current scheduling location we need to
2988/// maintain the number of vreg uses remaining to be top-scheduled.
Andrew Trick665d3ec2013-09-19 23:10:59 +00002989void GenericScheduler::pickNodeFromQueue(SchedBoundary &Zone,
Matthias Braun6ad3d052016-06-25 00:23:00 +00002990 const CandPolicy &ZonePolicy,
Andrew Trickbb1247b2013-12-05 17:55:47 +00002991 const RegPressureTracker &RPTracker,
2992 SchedCandidate &Cand) {
Andrew Trick7ee9de52012-05-10 21:06:16 +00002993 // getMaxPressureDelta temporarily modifies the tracker.
2994 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
2995
Matthias Braund29d31e2016-06-23 21:27:38 +00002996 ReadyQueue &Q = Zone.Available;
Javed Absare3a0cc22017-06-21 09:10:10 +00002997 for (SUnit *SU : Q) {
Andrew Trick7ee9de52012-05-10 21:06:16 +00002998
Matthias Braun6ad3d052016-06-25 00:23:00 +00002999 SchedCandidate TryCand(ZonePolicy);
Javed Absare3a0cc22017-06-21 09:10:10 +00003000 initCandidate(TryCand, SU, Zone.isTop(), RPTracker, TempTracker);
Matthias Braun6ad3d052016-06-25 00:23:00 +00003001 // Pass SchedBoundary only when comparing nodes from the same boundary.
3002 SchedBoundary *ZoneArg = Cand.AtTop == TryCand.AtTop ? &Zone : nullptr;
3003 tryCandidate(Cand, TryCand, ZoneArg);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003004 if (TryCand.Reason != NoCand) {
3005 // Initialize resource delta if needed in case future heuristics query it.
3006 if (TryCand.ResDelta == SchedResourceDelta())
3007 TryCand.initResourceDelta(DAG, SchedModel);
3008 Cand.setBest(TryCand);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003009 LLVM_DEBUG(traceCandidate(Cand));
Andrew Trick22025772012-05-17 18:35:10 +00003010 }
Andrew Trick7ee9de52012-05-10 21:06:16 +00003011 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003012}
3013
Andrew Trick22025772012-05-17 18:35:10 +00003014/// Pick the best candidate node from either the top or bottom queue.
Andrew Trick665d3ec2013-09-19 23:10:59 +00003015SUnit *GenericScheduler::pickNodeBidirectional(bool &IsTopNode) {
Andrew Trick22025772012-05-17 18:35:10 +00003016 // Schedule as far as possible in the direction of no choice. This is most
3017 // efficient, but also provides the best heuristics for CriticalPSets.
Andrew Trick61f1a272012-05-24 22:11:09 +00003018 if (SUnit *SU = Bot.pickOnlyChoice()) {
Andrew Trick22025772012-05-17 18:35:10 +00003019 IsTopNode = false;
Matthias Braun49cb6e92016-05-27 22:14:26 +00003020 tracePick(Only1, false);
Andrew Trick61f1a272012-05-24 22:11:09 +00003021 return SU;
Andrew Trick22025772012-05-17 18:35:10 +00003022 }
Andrew Trick61f1a272012-05-24 22:11:09 +00003023 if (SUnit *SU = Top.pickOnlyChoice()) {
Andrew Trick22025772012-05-17 18:35:10 +00003024 IsTopNode = true;
Matthias Braun49cb6e92016-05-27 22:14:26 +00003025 tracePick(Only1, true);
Andrew Trick61f1a272012-05-24 22:11:09 +00003026 return SU;
Andrew Trick22025772012-05-17 18:35:10 +00003027 }
Andrew Trickfc127d12013-12-07 05:59:44 +00003028 // Set the bottom-up policy based on the state of the current bottom zone and
3029 // the instructions outside the zone, including the top zone.
Matthias Braun6ad3d052016-06-25 00:23:00 +00003030 CandPolicy BotPolicy;
3031 setPolicy(BotPolicy, /*IsPostRA=*/false, Bot, &Top);
Andrew Trickfc127d12013-12-07 05:59:44 +00003032 // Set the top-down policy based on the state of the current top zone and
3033 // the instructions outside the zone, including the bottom zone.
Matthias Braun6ad3d052016-06-25 00:23:00 +00003034 CandPolicy TopPolicy;
3035 setPolicy(TopPolicy, /*IsPostRA=*/false, Top, &Bot);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003036
Matthias Brauncc676c42016-06-25 02:03:36 +00003037 // See if BotCand is still valid (because we previously scheduled from Top).
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003038 LLVM_DEBUG(dbgs() << "Picking from Bot:\n");
Matthias Brauncc676c42016-06-25 02:03:36 +00003039 if (!BotCand.isValid() || BotCand.SU->isScheduled ||
3040 BotCand.Policy != BotPolicy) {
3041 BotCand.reset(CandPolicy());
3042 pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), BotCand);
3043 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
3044 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003045 LLVM_DEBUG(traceCandidate(BotCand));
Matthias Brauncc676c42016-06-25 02:03:36 +00003046#ifndef NDEBUG
3047 if (VerifyScheduling) {
3048 SchedCandidate TCand;
3049 TCand.reset(CandPolicy());
3050 pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), TCand);
3051 assert(TCand.SU == BotCand.SU &&
3052 "Last pick result should correspond to re-picking right now");
3053 }
3054#endif
3055 }
Andrew Trick22025772012-05-17 18:35:10 +00003056
Andrew Trick22025772012-05-17 18:35:10 +00003057 // Check if the top Q has a better candidate.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003058 LLVM_DEBUG(dbgs() << "Picking from Top:\n");
Matthias Brauncc676c42016-06-25 02:03:36 +00003059 if (!TopCand.isValid() || TopCand.SU->isScheduled ||
3060 TopCand.Policy != TopPolicy) {
3061 TopCand.reset(CandPolicy());
3062 pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TopCand);
3063 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
3064 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003065 LLVM_DEBUG(traceCandidate(TopCand));
Matthias Brauncc676c42016-06-25 02:03:36 +00003066#ifndef NDEBUG
3067 if (VerifyScheduling) {
3068 SchedCandidate TCand;
3069 TCand.reset(CandPolicy());
3070 pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TCand);
3071 assert(TCand.SU == TopCand.SU &&
3072 "Last pick result should correspond to re-picking right now");
3073 }
3074#endif
3075 }
3076
3077 // Pick best from BotCand and TopCand.
3078 assert(BotCand.isValid());
3079 assert(TopCand.isValid());
3080 SchedCandidate Cand = BotCand;
3081 TopCand.Reason = NoCand;
3082 tryCandidate(Cand, TopCand, nullptr);
3083 if (TopCand.Reason != NoCand) {
3084 Cand.setBest(TopCand);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003085 LLVM_DEBUG(traceCandidate(Cand));
Matthias Brauncc676c42016-06-25 02:03:36 +00003086 }
Andrew Trick22025772012-05-17 18:35:10 +00003087
Matthias Braun6ad3d052016-06-25 00:23:00 +00003088 IsTopNode = Cand.AtTop;
3089 tracePick(Cand);
3090 return Cand.SU;
Andrew Trick22025772012-05-17 18:35:10 +00003091}
3092
3093/// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
Andrew Trick665d3ec2013-09-19 23:10:59 +00003094SUnit *GenericScheduler::pickNode(bool &IsTopNode) {
Andrew Trick7ee9de52012-05-10 21:06:16 +00003095 if (DAG->top() == DAG->bottom()) {
Andrew Trick61f1a272012-05-24 22:11:09 +00003096 assert(Top.Available.empty() && Top.Pending.empty() &&
3097 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
Craig Topperc0196b12014-04-14 00:51:57 +00003098 return nullptr;
Andrew Trick7ee9de52012-05-10 21:06:16 +00003099 }
Andrew Trick7ee9de52012-05-10 21:06:16 +00003100 SUnit *SU;
Andrew Trick984d98b2012-10-08 18:53:53 +00003101 do {
Andrew Trick75e411c2013-09-06 17:32:34 +00003102 if (RegionPolicy.OnlyTopDown) {
Andrew Trick984d98b2012-10-08 18:53:53 +00003103 SU = Top.pickOnlyChoice();
3104 if (!SU) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003105 CandPolicy NoPolicy;
Matthias Brauncc676c42016-06-25 02:03:36 +00003106 TopCand.reset(NoPolicy);
Matthias Braun6ad3d052016-06-25 00:23:00 +00003107 pickNodeFromQueue(Top, NoPolicy, DAG->getTopRPTracker(), TopCand);
Andrew Trick1ab16d92013-09-04 21:00:13 +00003108 assert(TopCand.Reason != NoCand && "failed to find a candidate");
Matthias Braun6ad3d052016-06-25 00:23:00 +00003109 tracePick(TopCand);
Andrew Trick984d98b2012-10-08 18:53:53 +00003110 SU = TopCand.SU;
3111 }
3112 IsTopNode = true;
Matthias Braunb550b762016-04-21 01:54:13 +00003113 } else if (RegionPolicy.OnlyBottomUp) {
Andrew Trick984d98b2012-10-08 18:53:53 +00003114 SU = Bot.pickOnlyChoice();
3115 if (!SU) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003116 CandPolicy NoPolicy;
Matthias Brauncc676c42016-06-25 02:03:36 +00003117 BotCand.reset(NoPolicy);
Matthias Braun6ad3d052016-06-25 00:23:00 +00003118 pickNodeFromQueue(Bot, NoPolicy, DAG->getBotRPTracker(), BotCand);
Andrew Trick1ab16d92013-09-04 21:00:13 +00003119 assert(BotCand.Reason != NoCand && "failed to find a candidate");
Matthias Braun6ad3d052016-06-25 00:23:00 +00003120 tracePick(BotCand);
Andrew Trick984d98b2012-10-08 18:53:53 +00003121 SU = BotCand.SU;
3122 }
3123 IsTopNode = false;
Matthias Braunb550b762016-04-21 01:54:13 +00003124 } else {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003125 SU = pickNodeBidirectional(IsTopNode);
Andrew Trick984d98b2012-10-08 18:53:53 +00003126 }
3127 } while (SU->isScheduled);
3128
Andrew Trick61f1a272012-05-24 22:11:09 +00003129 if (SU->isTopReady())
3130 Top.removeReady(SU);
3131 if (SU->isBottomReady())
3132 Bot.removeReady(SU);
Andrew Trick4e7f6a72012-05-25 02:02:39 +00003133
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003134 LLVM_DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") "
3135 << *SU->getInstr());
Andrew Trick7ee9de52012-05-10 21:06:16 +00003136 return SU;
3137}
3138
Andrew Trick665d3ec2013-09-19 23:10:59 +00003139void GenericScheduler::reschedulePhysRegCopies(SUnit *SU, bool isTop) {
Andrew Tricke833e1c2013-04-13 06:07:40 +00003140 MachineBasicBlock::iterator InsertPos = SU->getInstr();
3141 if (!isTop)
3142 ++InsertPos;
3143 SmallVectorImpl<SDep> &Deps = isTop ? SU->Preds : SU->Succs;
3144
3145 // Find already scheduled copies with a single physreg dependence and move
3146 // them just above the scheduled instruction.
Javed Absare3a0cc22017-06-21 09:10:10 +00003147 for (SDep &Dep : Deps) {
3148 if (Dep.getKind() != SDep::Data || !TRI->isPhysicalRegister(Dep.getReg()))
Andrew Tricke833e1c2013-04-13 06:07:40 +00003149 continue;
Javed Absare3a0cc22017-06-21 09:10:10 +00003150 SUnit *DepSU = Dep.getSUnit();
Andrew Tricke833e1c2013-04-13 06:07:40 +00003151 if (isTop ? DepSU->Succs.size() > 1 : DepSU->Preds.size() > 1)
3152 continue;
3153 MachineInstr *Copy = DepSU->getInstr();
3154 if (!Copy->isCopy())
3155 continue;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003156 LLVM_DEBUG(dbgs() << " Rescheduling physreg copy ";
3157 Dep.getSUnit()->dump(DAG));
Andrew Tricke833e1c2013-04-13 06:07:40 +00003158 DAG->moveInstruction(Copy, InsertPos);
3159 }
3160}
3161
Andrew Trick61f1a272012-05-24 22:11:09 +00003162/// Update the scheduler's state after scheduling a node. This is the same node
Andrew Trickd14d7c22013-12-28 21:56:57 +00003163/// that was just returned by pickNode(). However, ScheduleDAGMILive needs to
3164/// update it's state based on the current cycle before MachineSchedStrategy
3165/// does.
Andrew Tricke833e1c2013-04-13 06:07:40 +00003166///
3167/// FIXME: Eventually, we may bundle physreg copies rather than rescheduling
3168/// them here. See comments in biasPhysRegCopy.
Andrew Trick665d3ec2013-09-19 23:10:59 +00003169void GenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
Andrew Trick45446062012-06-05 21:11:27 +00003170 if (IsTopNode) {
Andrew Trickfc127d12013-12-07 05:59:44 +00003171 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
Andrew Trickce27bb92012-06-29 03:23:22 +00003172 Top.bumpNode(SU);
Andrew Tricke833e1c2013-04-13 06:07:40 +00003173 if (SU->hasPhysRegUses)
3174 reschedulePhysRegCopies(SU, true);
Matthias Braunb550b762016-04-21 01:54:13 +00003175 } else {
Andrew Trickfc127d12013-12-07 05:59:44 +00003176 SU->BotReadyCycle = std::max(SU->BotReadyCycle, Bot.getCurrCycle());
Andrew Trickce27bb92012-06-29 03:23:22 +00003177 Bot.bumpNode(SU);
Andrew Tricke833e1c2013-04-13 06:07:40 +00003178 if (SU->hasPhysRegDefs)
3179 reschedulePhysRegCopies(SU, false);
Andrew Trick61f1a272012-05-24 22:11:09 +00003180 }
3181}
3182
Andrew Trick8823dec2012-03-14 04:00:41 +00003183/// Create the standard converging machine scheduler. This will be used as the
3184/// default scheduler if the target does not set a default.
Matthias Braun115efcd2016-11-28 20:11:54 +00003185ScheduleDAGMILive *llvm::createGenericSchedLive(MachineSchedContext *C) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003186 ScheduleDAGMILive *DAG =
3187 new ScheduleDAGMILive(C, llvm::make_unique<GenericScheduler>(C));
Andrew Tricka7714a02012-11-12 19:40:10 +00003188 // Register DAG post-processors.
Andrew Trick85a1d4c2013-04-24 15:54:43 +00003189 //
3190 // FIXME: extend the mutation API to allow earlier mutations to instantiate
3191 // data and pass it to later mutations. Have a single mutation that gathers
3192 // the interesting nodes in one pass.
Tom Stellard68726a52016-08-19 19:59:18 +00003193 DAG->addMutation(createCopyConstrainDAGMutation(DAG->TII, DAG->TRI));
Andrew Tricka7714a02012-11-12 19:40:10 +00003194 return DAG;
Andrew Tricke1c034f2012-01-17 06:55:03 +00003195}
Andrew Trickd14d7c22013-12-28 21:56:57 +00003196
Matthias Braun115efcd2016-11-28 20:11:54 +00003197static ScheduleDAGInstrs *createConveringSched(MachineSchedContext *C) {
3198 return createGenericSchedLive(C);
3199}
3200
Andrew Tricke1c034f2012-01-17 06:55:03 +00003201static MachineSchedRegistry
Andrew Trick665d3ec2013-09-19 23:10:59 +00003202GenericSchedRegistry("converge", "Standard converging scheduler.",
Matthias Braun115efcd2016-11-28 20:11:54 +00003203 createConveringSched);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003204
3205//===----------------------------------------------------------------------===//
3206// PostGenericScheduler - Generic PostRA implementation of MachineSchedStrategy.
3207//===----------------------------------------------------------------------===//
3208
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003209void PostGenericScheduler::initialize(ScheduleDAGMI *Dag) {
3210 DAG = Dag;
3211 SchedModel = DAG->getSchedModel();
3212 TRI = DAG->TRI;
Andrew Trickd14d7c22013-12-28 21:56:57 +00003213
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003214 Rem.init(DAG, SchedModel);
3215 Top.init(DAG, SchedModel, &Rem);
3216 BotRoots.clear();
Andrew Trickd14d7c22013-12-28 21:56:57 +00003217
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003218 // Initialize the HazardRecognizers. If itineraries don't exist, are empty,
3219 // or are disabled, then these HazardRecs will be disabled.
3220 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003221 if (!Top.HazardRec) {
3222 Top.HazardRec =
Eric Christopher99556d72014-10-14 06:56:25 +00003223 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
Eric Christopherd9134482014-08-04 21:25:23 +00003224 Itin, DAG);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003225 }
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003226}
Andrew Trickd14d7c22013-12-28 21:56:57 +00003227
Andrew Trickd14d7c22013-12-28 21:56:57 +00003228void PostGenericScheduler::registerRoots() {
3229 Rem.CriticalPath = DAG->ExitSU.getDepth();
3230
3231 // Some roots may not feed into ExitSU. Check all of them in case.
Javed Absare3a0cc22017-06-21 09:10:10 +00003232 for (const SUnit *SU : BotRoots) {
3233 if (SU->getDepth() > Rem.CriticalPath)
3234 Rem.CriticalPath = SU->getDepth();
Andrew Trickd14d7c22013-12-28 21:56:57 +00003235 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003236 LLVM_DEBUG(dbgs() << "Critical Path: (PGS-RR) " << Rem.CriticalPath << '\n');
Gerolf Hoflehnerb5220dc2014-08-07 21:49:44 +00003237 if (DumpCriticalPathLength) {
3238 errs() << "Critical Path(PGS-RR ): " << Rem.CriticalPath << " \n";
3239 }
Andrew Trickd14d7c22013-12-28 21:56:57 +00003240}
3241
3242/// Apply a set of heursitics to a new candidate for PostRA scheduling.
3243///
3244/// \param Cand provides the policy and current best candidate.
3245/// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
3246void PostGenericScheduler::tryCandidate(SchedCandidate &Cand,
3247 SchedCandidate &TryCand) {
Andrew Trickd14d7c22013-12-28 21:56:57 +00003248 // Initialize the candidate if needed.
3249 if (!Cand.isValid()) {
3250 TryCand.Reason = NodeOrder;
3251 return;
3252 }
3253
3254 // Prioritize instructions that read unbuffered resources by stall cycles.
3255 if (tryLess(Top.getLatencyStallCycles(TryCand.SU),
3256 Top.getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
3257 return;
3258
Florian Hahnabb42182017-05-23 09:33:34 +00003259 // Keep clustered nodes together.
3260 if (tryGreater(TryCand.SU == DAG->getNextClusterSucc(),
3261 Cand.SU == DAG->getNextClusterSucc(),
3262 TryCand, Cand, Cluster))
3263 return;
3264
Andrew Trickd14d7c22013-12-28 21:56:57 +00003265 // Avoid critical resource consumption and balance the schedule.
3266 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
3267 TryCand, Cand, ResourceReduce))
3268 return;
3269 if (tryGreater(TryCand.ResDelta.DemandedResources,
3270 Cand.ResDelta.DemandedResources,
3271 TryCand, Cand, ResourceDemand))
3272 return;
3273
3274 // Avoid serializing long latency dependence chains.
3275 if (Cand.Policy.ReduceLatency && tryLatency(TryCand, Cand, Top)) {
3276 return;
3277 }
3278
3279 // Fall through to original instruction order.
3280 if (TryCand.SU->NodeNum < Cand.SU->NodeNum)
3281 TryCand.Reason = NodeOrder;
3282}
3283
3284void PostGenericScheduler::pickNodeFromQueue(SchedCandidate &Cand) {
3285 ReadyQueue &Q = Top.Available;
Javed Absare3a0cc22017-06-21 09:10:10 +00003286 for (SUnit *SU : Q) {
Andrew Trickd14d7c22013-12-28 21:56:57 +00003287 SchedCandidate TryCand(Cand.Policy);
Javed Absare3a0cc22017-06-21 09:10:10 +00003288 TryCand.SU = SU;
Matthias Braun6ad3d052016-06-25 00:23:00 +00003289 TryCand.AtTop = true;
Andrew Trickd14d7c22013-12-28 21:56:57 +00003290 TryCand.initResourceDelta(DAG, SchedModel);
3291 tryCandidate(Cand, TryCand);
3292 if (TryCand.Reason != NoCand) {
3293 Cand.setBest(TryCand);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003294 LLVM_DEBUG(traceCandidate(Cand));
Andrew Trickd14d7c22013-12-28 21:56:57 +00003295 }
3296 }
3297}
3298
3299/// Pick the next node to schedule.
3300SUnit *PostGenericScheduler::pickNode(bool &IsTopNode) {
3301 if (DAG->top() == DAG->bottom()) {
3302 assert(Top.Available.empty() && Top.Pending.empty() && "ReadyQ garbage");
Craig Topperc0196b12014-04-14 00:51:57 +00003303 return nullptr;
Andrew Trickd14d7c22013-12-28 21:56:57 +00003304 }
3305 SUnit *SU;
3306 do {
3307 SU = Top.pickOnlyChoice();
Matthias Braun49cb6e92016-05-27 22:14:26 +00003308 if (SU) {
3309 tracePick(Only1, true);
3310 } else {
Andrew Trickd14d7c22013-12-28 21:56:57 +00003311 CandPolicy NoPolicy;
3312 SchedCandidate TopCand(NoPolicy);
3313 // Set the top-down policy based on the state of the current top zone and
3314 // the instructions outside the zone, including the bottom zone.
Craig Topperc0196b12014-04-14 00:51:57 +00003315 setPolicy(TopCand.Policy, /*IsPostRA=*/true, Top, nullptr);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003316 pickNodeFromQueue(TopCand);
3317 assert(TopCand.Reason != NoCand && "failed to find a candidate");
Matthias Braun6ad3d052016-06-25 00:23:00 +00003318 tracePick(TopCand);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003319 SU = TopCand.SU;
3320 }
3321 } while (SU->isScheduled);
3322
3323 IsTopNode = true;
3324 Top.removeReady(SU);
3325
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003326 LLVM_DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") "
3327 << *SU->getInstr());
Andrew Trickd14d7c22013-12-28 21:56:57 +00003328 return SU;
3329}
3330
3331/// Called after ScheduleDAGMI has scheduled an instruction and updated
3332/// scheduled/remaining flags in the DAG nodes.
3333void PostGenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
3334 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
3335 Top.bumpNode(SU);
3336}
3337
Matthias Braun115efcd2016-11-28 20:11:54 +00003338ScheduleDAGMI *llvm::createGenericSchedPostRA(MachineSchedContext *C) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003339 return new ScheduleDAGMI(C, llvm::make_unique<PostGenericScheduler>(C),
Jonas Paulsson28f29482016-11-09 09:59:27 +00003340 /*RemoveKillFlags=*/true);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003341}
Andrew Tricke1c034f2012-01-17 06:55:03 +00003342
3343//===----------------------------------------------------------------------===//
Andrew Trick90f711d2012-10-15 18:02:27 +00003344// ILP Scheduler. Currently for experimental analysis of heuristics.
3345//===----------------------------------------------------------------------===//
3346
3347namespace {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003348
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003349/// Order nodes by the ILP metric.
Andrew Trick90f711d2012-10-15 18:02:27 +00003350struct ILPOrder {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003351 const SchedDFSResult *DFSResult = nullptr;
3352 const BitVector *ScheduledTrees = nullptr;
Andrew Trick90f711d2012-10-15 18:02:27 +00003353 bool MaximizeILP;
3354
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003355 ILPOrder(bool MaxILP) : MaximizeILP(MaxILP) {}
Andrew Trick90f711d2012-10-15 18:02:27 +00003356
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003357 /// Apply a less-than relation on node priority.
Andrew Trick48d392e2012-11-28 05:13:28 +00003358 ///
3359 /// (Return true if A comes after B in the Q.)
Andrew Trick90f711d2012-10-15 18:02:27 +00003360 bool operator()(const SUnit *A, const SUnit *B) const {
Andrew Trick48d392e2012-11-28 05:13:28 +00003361 unsigned SchedTreeA = DFSResult->getSubtreeID(A);
3362 unsigned SchedTreeB = DFSResult->getSubtreeID(B);
3363 if (SchedTreeA != SchedTreeB) {
3364 // Unscheduled trees have lower priority.
3365 if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
3366 return ScheduledTrees->test(SchedTreeB);
3367
3368 // Trees with shallower connections have have lower priority.
3369 if (DFSResult->getSubtreeLevel(SchedTreeA)
3370 != DFSResult->getSubtreeLevel(SchedTreeB)) {
3371 return DFSResult->getSubtreeLevel(SchedTreeA)
3372 < DFSResult->getSubtreeLevel(SchedTreeB);
3373 }
3374 }
Andrew Trick90f711d2012-10-15 18:02:27 +00003375 if (MaximizeILP)
Andrew Trick48d392e2012-11-28 05:13:28 +00003376 return DFSResult->getILP(A) < DFSResult->getILP(B);
Andrew Trick90f711d2012-10-15 18:02:27 +00003377 else
Andrew Trick48d392e2012-11-28 05:13:28 +00003378 return DFSResult->getILP(A) > DFSResult->getILP(B);
Andrew Trick90f711d2012-10-15 18:02:27 +00003379 }
3380};
3381
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003382/// Schedule based on the ILP metric.
Andrew Trick90f711d2012-10-15 18:02:27 +00003383class ILPScheduler : public MachineSchedStrategy {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003384 ScheduleDAGMILive *DAG = nullptr;
Andrew Trick90f711d2012-10-15 18:02:27 +00003385 ILPOrder Cmp;
3386
3387 std::vector<SUnit*> ReadyQ;
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003388
Andrew Trick90f711d2012-10-15 18:02:27 +00003389public:
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003390 ILPScheduler(bool MaximizeILP) : Cmp(MaximizeILP) {}
Andrew Trick90f711d2012-10-15 18:02:27 +00003391
Craig Topper4584cd52014-03-07 09:26:03 +00003392 void initialize(ScheduleDAGMI *dag) override {
Andrew Trickd7f890e2013-12-28 21:56:47 +00003393 assert(dag->hasVRegLiveness() && "ILPScheduler needs vreg liveness");
3394 DAG = static_cast<ScheduleDAGMILive*>(dag);
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00003395 DAG->computeDFSResult();
Andrew Trick44f750a2013-01-25 04:01:04 +00003396 Cmp.DFSResult = DAG->getDFSResult();
3397 Cmp.ScheduledTrees = &DAG->getScheduledTrees();
Andrew Trick90f711d2012-10-15 18:02:27 +00003398 ReadyQ.clear();
Andrew Trick90f711d2012-10-15 18:02:27 +00003399 }
3400
Craig Topper4584cd52014-03-07 09:26:03 +00003401 void registerRoots() override {
Benjamin Krameraa598b32012-11-29 14:36:26 +00003402 // Restore the heap in ReadyQ with the updated DFS results.
3403 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
Andrew Trick90f711d2012-10-15 18:02:27 +00003404 }
3405
3406 /// Implement MachineSchedStrategy interface.
3407 /// -----------------------------------------
3408
Andrew Trick48d392e2012-11-28 05:13:28 +00003409 /// Callback to select the highest priority node from the ready Q.
Craig Topper4584cd52014-03-07 09:26:03 +00003410 SUnit *pickNode(bool &IsTopNode) override {
Craig Topperc0196b12014-04-14 00:51:57 +00003411 if (ReadyQ.empty()) return nullptr;
Matt Arsenault4ab769f2013-03-21 00:57:21 +00003412 std::pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
Andrew Trick90f711d2012-10-15 18:02:27 +00003413 SUnit *SU = ReadyQ.back();
3414 ReadyQ.pop_back();
3415 IsTopNode = false;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003416 LLVM_DEBUG(dbgs() << "Pick node "
3417 << "SU(" << SU->NodeNum << ") "
3418 << " ILP: " << DAG->getDFSResult()->getILP(SU)
3419 << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU)
3420 << " @"
3421 << DAG->getDFSResult()->getSubtreeLevel(
3422 DAG->getDFSResult()->getSubtreeID(SU))
3423 << '\n'
3424 << "Scheduling " << *SU->getInstr());
Andrew Trick90f711d2012-10-15 18:02:27 +00003425 return SU;
3426 }
3427
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003428 /// Scheduler callback to notify that a new subtree is scheduled.
Craig Topper4584cd52014-03-07 09:26:03 +00003429 void scheduleTree(unsigned SubtreeID) override {
Andrew Trick44f750a2013-01-25 04:01:04 +00003430 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3431 }
3432
Andrew Trick48d392e2012-11-28 05:13:28 +00003433 /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
3434 /// DFSResults, and resort the priority Q.
Craig Topper4584cd52014-03-07 09:26:03 +00003435 void schedNode(SUnit *SU, bool IsTopNode) override {
Andrew Trick48d392e2012-11-28 05:13:28 +00003436 assert(!IsTopNode && "SchedDFSResult needs bottom-up");
Andrew Trick48d392e2012-11-28 05:13:28 +00003437 }
Andrew Trick90f711d2012-10-15 18:02:27 +00003438
Craig Topper4584cd52014-03-07 09:26:03 +00003439 void releaseTopNode(SUnit *) override { /*only called for top roots*/ }
Andrew Trick90f711d2012-10-15 18:02:27 +00003440
Craig Topper4584cd52014-03-07 09:26:03 +00003441 void releaseBottomNode(SUnit *SU) override {
Andrew Trick90f711d2012-10-15 18:02:27 +00003442 ReadyQ.push_back(SU);
3443 std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3444 }
3445};
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003446
3447} // end anonymous namespace
Andrew Trick90f711d2012-10-15 18:02:27 +00003448
3449static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003450 return new ScheduleDAGMILive(C, llvm::make_unique<ILPScheduler>(true));
Andrew Trick90f711d2012-10-15 18:02:27 +00003451}
3452static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003453 return new ScheduleDAGMILive(C, llvm::make_unique<ILPScheduler>(false));
Andrew Trick90f711d2012-10-15 18:02:27 +00003454}
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003455
Andrew Trick90f711d2012-10-15 18:02:27 +00003456static MachineSchedRegistry ILPMaxRegistry(
3457 "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
3458static MachineSchedRegistry ILPMinRegistry(
3459 "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
3460
3461//===----------------------------------------------------------------------===//
Andrew Trick63440872012-01-14 02:17:06 +00003462// Machine Instruction Shuffler for Correctness Testing
3463//===----------------------------------------------------------------------===//
3464
Andrew Tricke77e84e2012-01-13 06:30:30 +00003465#ifndef NDEBUG
3466namespace {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003467
Andrew Trick8823dec2012-03-14 04:00:41 +00003468/// Apply a less-than relation on the node order, which corresponds to the
3469/// instruction order prior to scheduling. IsReverse implements greater-than.
3470template<bool IsReverse>
3471struct SUnitOrder {
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003472 bool operator()(SUnit *A, SUnit *B) const {
Andrew Trick8823dec2012-03-14 04:00:41 +00003473 if (IsReverse)
3474 return A->NodeNum > B->NodeNum;
3475 else
3476 return A->NodeNum < B->NodeNum;
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003477 }
3478};
3479
Andrew Tricke77e84e2012-01-13 06:30:30 +00003480/// Reorder instructions as much as possible.
Andrew Trick8823dec2012-03-14 04:00:41 +00003481class InstructionShuffler : public MachineSchedStrategy {
3482 bool IsAlternating;
3483 bool IsTopDown;
3484
3485 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
3486 // gives nodes with a higher number higher priority causing the latest
3487 // instructions to be scheduled first.
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003488 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false>>
Andrew Trick8823dec2012-03-14 04:00:41 +00003489 TopQ;
Eugene Zelenko32a40562017-09-11 23:00:48 +00003490
Andrew Trick8823dec2012-03-14 04:00:41 +00003491 // When scheduling bottom-up, use greater-than as the queue priority.
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003492 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true>>
Andrew Trick8823dec2012-03-14 04:00:41 +00003493 BottomQ;
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003494
Andrew Tricke77e84e2012-01-13 06:30:30 +00003495public:
Andrew Trick8823dec2012-03-14 04:00:41 +00003496 InstructionShuffler(bool alternate, bool topdown)
3497 : IsAlternating(alternate), IsTopDown(topdown) {}
Andrew Tricke77e84e2012-01-13 06:30:30 +00003498
Craig Topper9d74a5a2014-04-29 07:58:41 +00003499 void initialize(ScheduleDAGMI*) override {
Andrew Trick8823dec2012-03-14 04:00:41 +00003500 TopQ.clear();
3501 BottomQ.clear();
3502 }
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003503
Andrew Trick8823dec2012-03-14 04:00:41 +00003504 /// Implement MachineSchedStrategy interface.
3505 /// -----------------------------------------
3506
Craig Topper9d74a5a2014-04-29 07:58:41 +00003507 SUnit *pickNode(bool &IsTopNode) override {
Andrew Trick8823dec2012-03-14 04:00:41 +00003508 SUnit *SU;
3509 if (IsTopDown) {
3510 do {
Craig Topperc0196b12014-04-14 00:51:57 +00003511 if (TopQ.empty()) return nullptr;
Andrew Trick8823dec2012-03-14 04:00:41 +00003512 SU = TopQ.top();
3513 TopQ.pop();
3514 } while (SU->isScheduled);
3515 IsTopNode = true;
Matthias Braunb550b762016-04-21 01:54:13 +00003516 } else {
Andrew Trick8823dec2012-03-14 04:00:41 +00003517 do {
Craig Topperc0196b12014-04-14 00:51:57 +00003518 if (BottomQ.empty()) return nullptr;
Andrew Trick8823dec2012-03-14 04:00:41 +00003519 SU = BottomQ.top();
3520 BottomQ.pop();
3521 } while (SU->isScheduled);
3522 IsTopNode = false;
3523 }
3524 if (IsAlternating)
3525 IsTopDown = !IsTopDown;
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003526 return SU;
3527 }
3528
Craig Topper9d74a5a2014-04-29 07:58:41 +00003529 void schedNode(SUnit *SU, bool IsTopNode) override {}
Andrew Trick61f1a272012-05-24 22:11:09 +00003530
Craig Topper9d74a5a2014-04-29 07:58:41 +00003531 void releaseTopNode(SUnit *SU) override {
Andrew Trick8823dec2012-03-14 04:00:41 +00003532 TopQ.push(SU);
3533 }
Craig Topper9d74a5a2014-04-29 07:58:41 +00003534 void releaseBottomNode(SUnit *SU) override {
Andrew Trick8823dec2012-03-14 04:00:41 +00003535 BottomQ.push(SU);
Andrew Tricke77e84e2012-01-13 06:30:30 +00003536 }
3537};
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003538
3539} // end anonymous namespace
Andrew Tricke77e84e2012-01-13 06:30:30 +00003540
Andrew Trick02a80da2012-03-08 01:41:12 +00003541static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
Andrew Trick8823dec2012-03-14 04:00:41 +00003542 bool Alternate = !ForceTopDown && !ForceBottomUp;
3543 bool TopDown = !ForceBottomUp;
Benjamin Kramer05e7a842012-03-14 11:26:37 +00003544 assert((TopDown || !ForceTopDown) &&
Andrew Trick8823dec2012-03-14 04:00:41 +00003545 "-misched-topdown incompatible with -misched-bottomup");
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003546 return new ScheduleDAGMILive(
3547 C, llvm::make_unique<InstructionShuffler>(Alternate, TopDown));
Andrew Tricke77e84e2012-01-13 06:30:30 +00003548}
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003549
Andrew Trick8823dec2012-03-14 04:00:41 +00003550static MachineSchedRegistry ShufflerRegistry(
3551 "shuffle", "Shuffle machine instructions alternating directions",
3552 createInstructionShuffler);
Andrew Tricke77e84e2012-01-13 06:30:30 +00003553#endif // !NDEBUG
Andrew Trickea9fd952013-01-25 07:45:29 +00003554
3555//===----------------------------------------------------------------------===//
Andrew Trickd7f890e2013-12-28 21:56:47 +00003556// GraphWriter support for ScheduleDAGMILive.
Andrew Trickea9fd952013-01-25 07:45:29 +00003557//===----------------------------------------------------------------------===//
3558
3559#ifndef NDEBUG
3560namespace llvm {
3561
3562template<> struct GraphTraits<
3563 ScheduleDAGMI*> : public GraphTraits<ScheduleDAG*> {};
3564
3565template<>
3566struct DOTGraphTraits<ScheduleDAGMI*> : public DefaultDOTGraphTraits {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003567 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
Andrew Trickea9fd952013-01-25 07:45:29 +00003568
3569 static std::string getGraphName(const ScheduleDAG *G) {
3570 return G->MF.getName();
3571 }
3572
3573 static bool renderGraphFromBottomUp() {
3574 return true;
3575 }
3576
3577 static bool isNodeHidden(const SUnit *Node) {
Matthias Braund78ee542015-09-17 21:09:59 +00003578 if (ViewMISchedCutoff == 0)
3579 return false;
3580 return (Node->Preds.size() > ViewMISchedCutoff
3581 || Node->Succs.size() > ViewMISchedCutoff);
Andrew Trickea9fd952013-01-25 07:45:29 +00003582 }
3583
Andrew Trickea9fd952013-01-25 07:45:29 +00003584 /// If you want to override the dot attributes printed for a particular
3585 /// edge, override this method.
3586 static std::string getEdgeAttributes(const SUnit *Node,
3587 SUnitIterator EI,
3588 const ScheduleDAG *Graph) {
3589 if (EI.isArtificialDep())
3590 return "color=cyan,style=dashed";
3591 if (EI.isCtrlDep())
3592 return "color=blue,style=dashed";
3593 return "";
3594 }
3595
3596 static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) {
Alp Tokere69170a2014-06-26 22:52:05 +00003597 std::string Str;
3598 raw_string_ostream SS(Str);
Andrew Trickd7f890e2013-12-28 21:56:47 +00003599 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3600 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
Craig Topperc0196b12014-04-14 00:51:57 +00003601 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
Andrew Trick7609b7d2013-09-06 17:32:42 +00003602 SS << "SU:" << SU->NodeNum;
3603 if (DFS)
3604 SS << " I:" << DFS->getNumInstrs(SU);
Andrew Trickea9fd952013-01-25 07:45:29 +00003605 return SS.str();
3606 }
Eugene Zelenko32a40562017-09-11 23:00:48 +00003607
Andrew Trickea9fd952013-01-25 07:45:29 +00003608 static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G) {
3609 return G->getGraphNodeLabel(SU);
3610 }
3611
Andrew Trickd7f890e2013-12-28 21:56:47 +00003612 static std::string getNodeAttributes(const SUnit *N, const ScheduleDAG *G) {
Andrew Trickea9fd952013-01-25 07:45:29 +00003613 std::string Str("shape=Mrecord");
Andrew Trickd7f890e2013-12-28 21:56:47 +00003614 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3615 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
Craig Topperc0196b12014-04-14 00:51:57 +00003616 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
Andrew Trickea9fd952013-01-25 07:45:29 +00003617 if (DFS) {
3618 Str += ",style=filled,fillcolor=\"#";
3619 Str += DOT::getColorString(DFS->getSubtreeID(N));
3620 Str += '"';
3621 }
3622 return Str;
3623 }
3624};
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003625
3626} // end namespace llvm
Andrew Trickea9fd952013-01-25 07:45:29 +00003627#endif // NDEBUG
3628
3629/// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
3630/// rendered using 'dot'.
Andrew Trickea9fd952013-01-25 07:45:29 +00003631void ScheduleDAGMI::viewGraph(const Twine &Name, const Twine &Title) {
3632#ifndef NDEBUG
3633 ViewGraph(this, Name, false, Title);
3634#else
3635 errs() << "ScheduleDAGMI::viewGraph is only available in debug builds on "
3636 << "systems with Graphviz or gv!\n";
3637#endif // NDEBUG
3638}
3639
3640/// Out-of-line implementation with no arguments is handy for gdb.
3641void ScheduleDAGMI::viewGraph() {
3642 viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName());
3643}