1dff0c46cSDimitry Andric //===- MachineScheduler.cpp - Machine Instruction Scheduler ---------------===//
2dff0c46cSDimitry Andric //
3dff0c46cSDimitry Andric //                     The LLVM Compiler Infrastructure
4dff0c46cSDimitry Andric //
5dff0c46cSDimitry Andric // This file is distributed under the University of Illinois Open Source
6dff0c46cSDimitry Andric // License. See LICENSE.TXT for details.
7dff0c46cSDimitry Andric //
8dff0c46cSDimitry Andric //===----------------------------------------------------------------------===//
9dff0c46cSDimitry Andric //
10dff0c46cSDimitry Andric // MachineScheduler schedules machine instructions after phi elimination. It
11dff0c46cSDimitry Andric // preserves LiveIntervals so it can be invoked before register allocation.
12dff0c46cSDimitry Andric //
13dff0c46cSDimitry Andric //===----------------------------------------------------------------------===//
14dff0c46cSDimitry Andric 
15db17bf38SDimitry Andric #include "llvm/CodeGen/MachineScheduler.h"
167a7e6055SDimitry Andric #include "llvm/ADT/ArrayRef.h"
177a7e6055SDimitry Andric #include "llvm/ADT/BitVector.h"
187a7e6055SDimitry Andric #include "llvm/ADT/DenseMap.h"
19139f7f9bSDimitry Andric #include "llvm/ADT/PriorityQueue.h"
207a7e6055SDimitry Andric #include "llvm/ADT/STLExtras.h"
21db17bf38SDimitry Andric #include "llvm/ADT/SmallVector.h"
22db17bf38SDimitry Andric #include "llvm/ADT/iterator_range.h"
23139f7f9bSDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
247a7e6055SDimitry Andric #include "llvm/CodeGen/LiveInterval.h"
252cab237bSDimitry Andric #include "llvm/CodeGen/LiveIntervals.h"
267a7e6055SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
27139f7f9bSDimitry Andric #include "llvm/CodeGen/MachineDominators.h"
287a7e6055SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
297a7e6055SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
307a7e6055SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
31139f7f9bSDimitry Andric #include "llvm/CodeGen/MachineLoopInfo.h"
327a7e6055SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
337a7e6055SDimitry Andric #include "llvm/CodeGen/MachinePassRegistry.h"
34f785676fSDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
35dff0c46cSDimitry Andric #include "llvm/CodeGen/Passes.h"
367ae0e2c9SDimitry Andric #include "llvm/CodeGen/RegisterClassInfo.h"
37db17bf38SDimitry Andric #include "llvm/CodeGen/RegisterPressure.h"
387a7e6055SDimitry Andric #include "llvm/CodeGen/ScheduleDAG.h"
397a7e6055SDimitry Andric #include "llvm/CodeGen/ScheduleDAGInstrs.h"
407a7e6055SDimitry Andric #include "llvm/CodeGen/ScheduleDAGMutation.h"
41139f7f9bSDimitry Andric #include "llvm/CodeGen/ScheduleDFS.h"
427ae0e2c9SDimitry Andric #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
437a7e6055SDimitry Andric #include "llvm/CodeGen/SlotIndexes.h"
44*b5893f02SDimitry Andric #include "llvm/CodeGen/TargetFrameLowering.h"
452cab237bSDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
462cab237bSDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
473ca95b02SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
482cab237bSDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
497a7e6055SDimitry Andric #include "llvm/CodeGen/TargetSchedule.h"
502cab237bSDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
514ba319b5SDimitry Andric #include "llvm/Config/llvm-config.h"
527a7e6055SDimitry Andric #include "llvm/MC/LaneBitmask.h"
537a7e6055SDimitry Andric #include "llvm/Pass.h"
54dff0c46cSDimitry Andric #include "llvm/Support/CommandLine.h"
557a7e6055SDimitry Andric #include "llvm/Support/Compiler.h"
56dff0c46cSDimitry Andric #include "llvm/Support/Debug.h"
57dff0c46cSDimitry Andric #include "llvm/Support/ErrorHandling.h"
58139f7f9bSDimitry Andric #include "llvm/Support/GraphWriter.h"
594ba319b5SDimitry Andric #include "llvm/Support/MachineValueType.h"
60dff0c46cSDimitry Andric #include "llvm/Support/raw_ostream.h"
617a7e6055SDimitry Andric #include <algorithm>
627a7e6055SDimitry Andric #include <cassert>
637a7e6055SDimitry Andric #include <cstdint>
647a7e6055SDimitry Andric #include <iterator>
657a7e6055SDimitry Andric #include <limits>
667a7e6055SDimitry Andric #include <memory>
677a7e6055SDimitry Andric #include <string>
687a7e6055SDimitry Andric #include <tuple>
697a7e6055SDimitry Andric #include <utility>
707a7e6055SDimitry Andric #include <vector>
71dff0c46cSDimitry Andric 
72dff0c46cSDimitry Andric using namespace llvm;
73dff0c46cSDimitry Andric 
74302affcbSDimitry Andric #define DEBUG_TYPE "machine-scheduler"
7591bc56edSDimitry Andric 
763861d79fSDimitry Andric namespace llvm {
777a7e6055SDimitry Andric 
783861d79fSDimitry Andric cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
79dff0c46cSDimitry Andric                            cl::desc("Force top-down list scheduling"));
803861d79fSDimitry Andric cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
81dff0c46cSDimitry Andric                             cl::desc("Force bottom-up list scheduling"));
8239d628a0SDimitry Andric cl::opt<bool>
8339d628a0SDimitry Andric DumpCriticalPathLength("misched-dcpl", cl::Hidden,
8439d628a0SDimitry Andric                        cl::desc("Print critical path length to stdout"));
857a7e6055SDimitry Andric 
867a7e6055SDimitry Andric } // end namespace llvm
87dff0c46cSDimitry Andric 
88dff0c46cSDimitry Andric #ifndef NDEBUG
89dff0c46cSDimitry Andric static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
90dff0c46cSDimitry Andric   cl::desc("Pop up a window to show MISched dags after they are processed"));
91dff0c46cSDimitry Andric 
927d523365SDimitry Andric /// In some situations a few uninteresting nodes depend on nearly all other
937d523365SDimitry Andric /// nodes in the graph, provide a cutoff to hide them.
947d523365SDimitry Andric static cl::opt<unsigned> ViewMISchedCutoff("view-misched-cutoff", cl::Hidden,
957d523365SDimitry Andric   cl::desc("Hide nodes with more predecessor/successor than cutoff"));
967d523365SDimitry Andric 
97dff0c46cSDimitry Andric static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
98dff0c46cSDimitry Andric   cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
9991bc56edSDimitry Andric 
10091bc56edSDimitry Andric static cl::opt<std::string> SchedOnlyFunc("misched-only-func", cl::Hidden,
10191bc56edSDimitry Andric   cl::desc("Only schedule this function"));
10291bc56edSDimitry Andric static cl::opt<unsigned> SchedOnlyBlock("misched-only-block", cl::Hidden,
10391bc56edSDimitry Andric                                         cl::desc("Only schedule this MBB#"));
104*b5893f02SDimitry Andric static cl::opt<bool> PrintDAGs("misched-print-dags", cl::Hidden,
105*b5893f02SDimitry Andric                               cl::desc("Print schedule DAGs"));
106dff0c46cSDimitry Andric #else
107*b5893f02SDimitry Andric static const bool ViewMISchedDAGs = false;
108*b5893f02SDimitry Andric static const bool PrintDAGs = false;
109dff0c46cSDimitry Andric #endif // NDEBUG
110dff0c46cSDimitry Andric 
1113ca95b02SDimitry Andric /// Avoid quadratic complexity in unusually large basic blocks by limiting the
1123ca95b02SDimitry Andric /// size of the ready lists.
1133ca95b02SDimitry Andric static cl::opt<unsigned> ReadyListLimit("misched-limit", cl::Hidden,
1143ca95b02SDimitry Andric   cl::desc("Limit ready list to N instructions"), cl::init(256));
1153ca95b02SDimitry Andric 
116f785676fSDimitry Andric static cl::opt<bool> EnableRegPressure("misched-regpressure", cl::Hidden,
117f785676fSDimitry Andric   cl::desc("Enable register pressure scheduling."), cl::init(true));
118f785676fSDimitry Andric 
119f785676fSDimitry Andric static cl::opt<bool> EnableCyclicPath("misched-cyclicpath", cl::Hidden,
120f785676fSDimitry Andric   cl::desc("Enable cyclic critical path analysis."), cl::init(true));
121284c1978SDimitry Andric 
1223ca95b02SDimitry Andric static cl::opt<bool> EnableMemOpCluster("misched-cluster", cl::Hidden,
1233ca95b02SDimitry Andric                                         cl::desc("Enable memop clustering."),
1243ca95b02SDimitry Andric                                         cl::init(true));
125139f7f9bSDimitry Andric 
126139f7f9bSDimitry Andric static cl::opt<bool> VerifyScheduling("verify-misched", cl::Hidden,
127139f7f9bSDimitry Andric   cl::desc("Verify machine instrs before and after machine scheduling"));
128139f7f9bSDimitry Andric 
129139f7f9bSDimitry Andric // DAG subtrees must have at least this many nodes.
130139f7f9bSDimitry Andric static const unsigned MinSubtreeSize = 8;
1313861d79fSDimitry Andric 
132f785676fSDimitry Andric // Pin the vtables to this file.
anchor()133f785676fSDimitry Andric void MachineSchedStrategy::anchor() {}
1347a7e6055SDimitry Andric 
anchor()135f785676fSDimitry Andric void ScheduleDAGMutation::anchor() {}
136f785676fSDimitry Andric 
137dff0c46cSDimitry Andric //===----------------------------------------------------------------------===//
138dff0c46cSDimitry Andric // Machine Instruction Scheduling Pass and Registry
139dff0c46cSDimitry Andric //===----------------------------------------------------------------------===//
140dff0c46cSDimitry Andric 
MachineSchedContext()1417a7e6055SDimitry Andric MachineSchedContext::MachineSchedContext() {
1427ae0e2c9SDimitry Andric   RegClassInfo = new RegisterClassInfo();
1437ae0e2c9SDimitry Andric }
1447ae0e2c9SDimitry Andric 
~MachineSchedContext()1457ae0e2c9SDimitry Andric MachineSchedContext::~MachineSchedContext() {
1467ae0e2c9SDimitry Andric   delete RegClassInfo;
1477ae0e2c9SDimitry Andric }
1487ae0e2c9SDimitry Andric 
149dff0c46cSDimitry Andric namespace {
1507a7e6055SDimitry Andric 
15191bc56edSDimitry Andric /// Base class for a machine scheduler class that can run at any point.
15291bc56edSDimitry Andric class MachineSchedulerBase : public MachineSchedContext,
153dff0c46cSDimitry Andric                              public MachineFunctionPass {
154dff0c46cSDimitry Andric public:
MachineSchedulerBase(char & ID)15591bc56edSDimitry Andric   MachineSchedulerBase(char &ID): MachineFunctionPass(ID) {}
15691bc56edSDimitry Andric 
15791bc56edSDimitry Andric   void print(raw_ostream &O, const Module* = nullptr) const override;
15891bc56edSDimitry Andric 
15991bc56edSDimitry Andric protected:
1607d523365SDimitry Andric   void scheduleRegions(ScheduleDAGInstrs &Scheduler, bool FixKillFlags);
16191bc56edSDimitry Andric };
16291bc56edSDimitry Andric 
16391bc56edSDimitry Andric /// MachineScheduler runs after coalescing and before register allocation.
16491bc56edSDimitry Andric class MachineScheduler : public MachineSchedulerBase {
16591bc56edSDimitry Andric public:
166dff0c46cSDimitry Andric   MachineScheduler();
167dff0c46cSDimitry Andric 
16891bc56edSDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override;
169dff0c46cSDimitry Andric 
17091bc56edSDimitry Andric   bool runOnMachineFunction(MachineFunction&) override;
171dff0c46cSDimitry Andric 
172dff0c46cSDimitry Andric   static char ID; // Class identification, replacement for typeinfo
173f785676fSDimitry Andric 
174f785676fSDimitry Andric protected:
175f785676fSDimitry Andric   ScheduleDAGInstrs *createMachineScheduler();
176dff0c46cSDimitry Andric };
17791bc56edSDimitry Andric 
17891bc56edSDimitry Andric /// PostMachineScheduler runs after shortly before code emission.
17991bc56edSDimitry Andric class PostMachineScheduler : public MachineSchedulerBase {
18091bc56edSDimitry Andric public:
18191bc56edSDimitry Andric   PostMachineScheduler();
18291bc56edSDimitry Andric 
18391bc56edSDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override;
18491bc56edSDimitry Andric 
18591bc56edSDimitry Andric   bool runOnMachineFunction(MachineFunction&) override;
18691bc56edSDimitry Andric 
18791bc56edSDimitry Andric   static char ID; // Class identification, replacement for typeinfo
18891bc56edSDimitry Andric 
18991bc56edSDimitry Andric protected:
19091bc56edSDimitry Andric   ScheduleDAGInstrs *createPostMachineScheduler();
19191bc56edSDimitry Andric };
1927a7e6055SDimitry Andric 
1937a7e6055SDimitry Andric } // end anonymous namespace
194dff0c46cSDimitry Andric 
195dff0c46cSDimitry Andric char MachineScheduler::ID = 0;
196dff0c46cSDimitry Andric 
197dff0c46cSDimitry Andric char &llvm::MachineSchedulerID = MachineScheduler::ID;
198dff0c46cSDimitry Andric 
199302affcbSDimitry Andric INITIALIZE_PASS_BEGIN(MachineScheduler, DEBUG_TYPE,
200dff0c46cSDimitry Andric                       "Machine Instruction Scheduler", false, false)
INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)2017d523365SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
2027a7e6055SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
203dff0c46cSDimitry Andric INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
204dff0c46cSDimitry Andric INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
205302affcbSDimitry Andric INITIALIZE_PASS_END(MachineScheduler, DEBUG_TYPE,
206dff0c46cSDimitry Andric                     "Machine Instruction Scheduler", false, false)
207dff0c46cSDimitry Andric 
2082cab237bSDimitry Andric MachineScheduler::MachineScheduler() : MachineSchedulerBase(ID) {
209dff0c46cSDimitry Andric   initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
210dff0c46cSDimitry Andric }
211dff0c46cSDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const212dff0c46cSDimitry Andric void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
213dff0c46cSDimitry Andric   AU.setPreservesCFG();
214dff0c46cSDimitry Andric   AU.addRequiredID(MachineDominatorsID);
215dff0c46cSDimitry Andric   AU.addRequired<MachineLoopInfo>();
2167d523365SDimitry Andric   AU.addRequired<AAResultsWrapperPass>();
217dff0c46cSDimitry Andric   AU.addRequired<TargetPassConfig>();
218dff0c46cSDimitry Andric   AU.addRequired<SlotIndexes>();
219dff0c46cSDimitry Andric   AU.addPreserved<SlotIndexes>();
220dff0c46cSDimitry Andric   AU.addRequired<LiveIntervals>();
221dff0c46cSDimitry Andric   AU.addPreserved<LiveIntervals>();
222dff0c46cSDimitry Andric   MachineFunctionPass::getAnalysisUsage(AU);
223dff0c46cSDimitry Andric }
224dff0c46cSDimitry Andric 
22591bc56edSDimitry Andric char PostMachineScheduler::ID = 0;
22691bc56edSDimitry Andric 
22791bc56edSDimitry Andric char &llvm::PostMachineSchedulerID = PostMachineScheduler::ID;
22891bc56edSDimitry Andric 
22991bc56edSDimitry Andric INITIALIZE_PASS(PostMachineScheduler, "postmisched",
23091bc56edSDimitry Andric                 "PostRA Machine Instruction Scheduler", false, false)
23191bc56edSDimitry Andric 
PostMachineScheduler()2322cab237bSDimitry Andric PostMachineScheduler::PostMachineScheduler() : MachineSchedulerBase(ID) {
23391bc56edSDimitry Andric   initializePostMachineSchedulerPass(*PassRegistry::getPassRegistry());
23491bc56edSDimitry Andric }
23591bc56edSDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const23691bc56edSDimitry Andric void PostMachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
23791bc56edSDimitry Andric   AU.setPreservesCFG();
23891bc56edSDimitry Andric   AU.addRequiredID(MachineDominatorsID);
23991bc56edSDimitry Andric   AU.addRequired<MachineLoopInfo>();
24091bc56edSDimitry Andric   AU.addRequired<TargetPassConfig>();
24191bc56edSDimitry Andric   MachineFunctionPass::getAnalysisUsage(AU);
24291bc56edSDimitry Andric }
24391bc56edSDimitry Andric 
244*b5893f02SDimitry Andric MachinePassRegistry<MachineSchedRegistry::ScheduleDAGCtor>
245*b5893f02SDimitry Andric     MachineSchedRegistry::Registry;
246dff0c46cSDimitry Andric 
247dff0c46cSDimitry Andric /// A dummy default scheduler factory indicates whether the scheduler
248dff0c46cSDimitry Andric /// is overridden on the command line.
useDefaultMachineSched(MachineSchedContext * C)249dff0c46cSDimitry Andric static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
25091bc56edSDimitry Andric   return nullptr;
251dff0c46cSDimitry Andric }
252dff0c46cSDimitry Andric 
253dff0c46cSDimitry Andric /// MachineSchedOpt allows command line selection of the scheduler.
254dff0c46cSDimitry Andric static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
255dff0c46cSDimitry Andric                RegisterPassParser<MachineSchedRegistry>>
256dff0c46cSDimitry Andric MachineSchedOpt("misched",
257dff0c46cSDimitry Andric                 cl::init(&useDefaultMachineSched), cl::Hidden,
258dff0c46cSDimitry Andric                 cl::desc("Machine instruction scheduler to use"));
259dff0c46cSDimitry Andric 
260dff0c46cSDimitry Andric static MachineSchedRegistry
261dff0c46cSDimitry Andric DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
262dff0c46cSDimitry Andric                      useDefaultMachineSched);
263dff0c46cSDimitry Andric 
264ff0cc061SDimitry Andric static cl::opt<bool> EnableMachineSched(
265ff0cc061SDimitry Andric     "enable-misched",
266ff0cc061SDimitry Andric     cl::desc("Enable the machine instruction scheduling pass."), cl::init(true),
267ff0cc061SDimitry Andric     cl::Hidden);
268ff0cc061SDimitry Andric 
2693ca95b02SDimitry Andric static cl::opt<bool> EnablePostRAMachineSched(
2703ca95b02SDimitry Andric     "enable-post-misched",
2713ca95b02SDimitry Andric     cl::desc("Enable the post-ra machine instruction scheduling pass."),
2723ca95b02SDimitry Andric     cl::init(true), cl::Hidden);
2733ca95b02SDimitry Andric 
2747ae0e2c9SDimitry Andric /// Decrement this iterator until reaching the top or a non-debug instr.
275f785676fSDimitry Andric static MachineBasicBlock::const_iterator
priorNonDebug(MachineBasicBlock::const_iterator I,MachineBasicBlock::const_iterator Beg)276f785676fSDimitry Andric priorNonDebug(MachineBasicBlock::const_iterator I,
277f785676fSDimitry Andric               MachineBasicBlock::const_iterator Beg) {
2787ae0e2c9SDimitry Andric   assert(I != Beg && "reached the top of the region, cannot decrement");
2797ae0e2c9SDimitry Andric   while (--I != Beg) {
2804ba319b5SDimitry Andric     if (!I->isDebugInstr())
2817ae0e2c9SDimitry Andric       break;
2827ae0e2c9SDimitry Andric   }
2837ae0e2c9SDimitry Andric   return I;
2847ae0e2c9SDimitry Andric }
2857ae0e2c9SDimitry Andric 
286f785676fSDimitry Andric /// Non-const version.
287f785676fSDimitry Andric static MachineBasicBlock::iterator
priorNonDebug(MachineBasicBlock::iterator I,MachineBasicBlock::const_iterator Beg)288f785676fSDimitry Andric priorNonDebug(MachineBasicBlock::iterator I,
289f785676fSDimitry Andric               MachineBasicBlock::const_iterator Beg) {
290d88c1a5aSDimitry Andric   return priorNonDebug(MachineBasicBlock::const_iterator(I), Beg)
291d88c1a5aSDimitry Andric       .getNonConstIterator();
292f785676fSDimitry Andric }
293f785676fSDimitry Andric 
2947ae0e2c9SDimitry Andric /// If this iterator is a debug value, increment until reaching the End or a
2957ae0e2c9SDimitry Andric /// non-debug instruction.
296f785676fSDimitry Andric static MachineBasicBlock::const_iterator
nextIfDebug(MachineBasicBlock::const_iterator I,MachineBasicBlock::const_iterator End)297f785676fSDimitry Andric nextIfDebug(MachineBasicBlock::const_iterator I,
298f785676fSDimitry Andric             MachineBasicBlock::const_iterator End) {
2997ae0e2c9SDimitry Andric   for(; I != End; ++I) {
3004ba319b5SDimitry Andric     if (!I->isDebugInstr())
3017ae0e2c9SDimitry Andric       break;
3027ae0e2c9SDimitry Andric   }
3037ae0e2c9SDimitry Andric   return I;
3047ae0e2c9SDimitry Andric }
3057ae0e2c9SDimitry Andric 
306f785676fSDimitry Andric /// Non-const version.
307f785676fSDimitry Andric static MachineBasicBlock::iterator
nextIfDebug(MachineBasicBlock::iterator I,MachineBasicBlock::const_iterator End)308f785676fSDimitry Andric nextIfDebug(MachineBasicBlock::iterator I,
309f785676fSDimitry Andric             MachineBasicBlock::const_iterator End) {
310d88c1a5aSDimitry Andric   return nextIfDebug(MachineBasicBlock::const_iterator(I), End)
311d88c1a5aSDimitry Andric       .getNonConstIterator();
312f785676fSDimitry Andric }
313f785676fSDimitry Andric 
314f785676fSDimitry Andric /// Instantiate a ScheduleDAGInstrs that will be owned by the caller.
createMachineScheduler()315f785676fSDimitry Andric ScheduleDAGInstrs *MachineScheduler::createMachineScheduler() {
316f785676fSDimitry Andric   // Select the scheduler, or set the default.
317f785676fSDimitry Andric   MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
318f785676fSDimitry Andric   if (Ctor != useDefaultMachineSched)
319f785676fSDimitry Andric     return Ctor(this);
320f785676fSDimitry Andric 
321f785676fSDimitry Andric   // Get the default scheduler set by the target for this function.
322f785676fSDimitry Andric   ScheduleDAGInstrs *Scheduler = PassConfig->createMachineScheduler(this);
323f785676fSDimitry Andric   if (Scheduler)
324f785676fSDimitry Andric     return Scheduler;
325f785676fSDimitry Andric 
326f785676fSDimitry Andric   // Default to GenericScheduler.
32791bc56edSDimitry Andric   return createGenericSchedLive(this);
32891bc56edSDimitry Andric }
32991bc56edSDimitry Andric 
33091bc56edSDimitry Andric /// Instantiate a ScheduleDAGInstrs for PostRA scheduling that will be owned by
33191bc56edSDimitry Andric /// the caller. We don't have a command line option to override the postRA
33291bc56edSDimitry Andric /// scheduler. The Target must configure it.
createPostMachineScheduler()33391bc56edSDimitry Andric ScheduleDAGInstrs *PostMachineScheduler::createPostMachineScheduler() {
33491bc56edSDimitry Andric   // Get the postRA scheduler set by the target for this function.
33591bc56edSDimitry Andric   ScheduleDAGInstrs *Scheduler = PassConfig->createPostMachineScheduler(this);
33691bc56edSDimitry Andric   if (Scheduler)
33791bc56edSDimitry Andric     return Scheduler;
33891bc56edSDimitry Andric 
33991bc56edSDimitry Andric   // Default to GenericScheduler.
34091bc56edSDimitry Andric   return createGenericSchedPostRA(this);
341f785676fSDimitry Andric }
342f785676fSDimitry Andric 
343dff0c46cSDimitry Andric /// Top-level MachineScheduler pass driver.
344dff0c46cSDimitry Andric ///
345dff0c46cSDimitry Andric /// Visit blocks in function order. Divide each block into scheduling regions
346dff0c46cSDimitry Andric /// and visit them bottom-up. Visiting regions bottom-up is not required, but is
347dff0c46cSDimitry Andric /// consistent with the DAG builder, which traverses the interior of the
348dff0c46cSDimitry Andric /// scheduling regions bottom-up.
349dff0c46cSDimitry Andric ///
350dff0c46cSDimitry Andric /// This design avoids exposing scheduling boundaries to the DAG builder,
351dff0c46cSDimitry Andric /// simplifying the DAG builder's support for "special" target instructions.
352dff0c46cSDimitry Andric /// At the same time the design allows target schedulers to operate across
3534ba319b5SDimitry Andric /// scheduling boundaries, for example to bundle the boundary instructions
354dff0c46cSDimitry Andric /// without reordering them. This creates complexity, because the target
355dff0c46cSDimitry Andric /// scheduler must update the RegionBegin and RegionEnd positions cached by
356dff0c46cSDimitry Andric /// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
357dff0c46cSDimitry Andric /// design would be to split blocks at scheduling boundaries, but LLVM has a
358dff0c46cSDimitry Andric /// general bias against block splitting purely for implementation simplicity.
runOnMachineFunction(MachineFunction & mf)359dff0c46cSDimitry Andric bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
3602cab237bSDimitry Andric   if (skipFunction(mf.getFunction()))
3613ca95b02SDimitry Andric     return false;
3623ca95b02SDimitry Andric 
363ff0cc061SDimitry Andric   if (EnableMachineSched.getNumOccurrences()) {
364ff0cc061SDimitry Andric     if (!EnableMachineSched)
365ff0cc061SDimitry Andric       return false;
366ff0cc061SDimitry Andric   } else if (!mf.getSubtarget().enableMachineScheduler())
367ff0cc061SDimitry Andric     return false;
368ff0cc061SDimitry Andric 
3694ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Before MISched:\n"; mf.print(dbgs()));
3707ae0e2c9SDimitry Andric 
371dff0c46cSDimitry Andric   // Initialize the context of the pass.
372dff0c46cSDimitry Andric   MF = &mf;
373dff0c46cSDimitry Andric   MLI = &getAnalysis<MachineLoopInfo>();
374dff0c46cSDimitry Andric   MDT = &getAnalysis<MachineDominatorTree>();
375dff0c46cSDimitry Andric   PassConfig = &getAnalysis<TargetPassConfig>();
3767d523365SDimitry Andric   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
377dff0c46cSDimitry Andric 
378dff0c46cSDimitry Andric   LIS = &getAnalysis<LiveIntervals>();
379dff0c46cSDimitry Andric 
380139f7f9bSDimitry Andric   if (VerifyScheduling) {
3814ba319b5SDimitry Andric     LLVM_DEBUG(LIS->dump());
382139f7f9bSDimitry Andric     MF->verify(this, "Before machine scheduling.");
383139f7f9bSDimitry Andric   }
3847ae0e2c9SDimitry Andric   RegClassInfo->runOnMachineFunction(*MF);
3857ae0e2c9SDimitry Andric 
386f785676fSDimitry Andric   // Instantiate the selected scheduler for this target, function, and
387f785676fSDimitry Andric   // optimization level.
38891bc56edSDimitry Andric   std::unique_ptr<ScheduleDAGInstrs> Scheduler(createMachineScheduler());
3897d523365SDimitry Andric   scheduleRegions(*Scheduler, false);
39091bc56edSDimitry Andric 
3914ba319b5SDimitry Andric   LLVM_DEBUG(LIS->dump());
39291bc56edSDimitry Andric   if (VerifyScheduling)
39391bc56edSDimitry Andric     MF->verify(this, "After machine scheduling.");
39491bc56edSDimitry Andric   return true;
39591bc56edSDimitry Andric }
39691bc56edSDimitry Andric 
runOnMachineFunction(MachineFunction & mf)39791bc56edSDimitry Andric bool PostMachineScheduler::runOnMachineFunction(MachineFunction &mf) {
3982cab237bSDimitry Andric   if (skipFunction(mf.getFunction()))
39991bc56edSDimitry Andric     return false;
40091bc56edSDimitry Andric 
4013ca95b02SDimitry Andric   if (EnablePostRAMachineSched.getNumOccurrences()) {
4023ca95b02SDimitry Andric     if (!EnablePostRAMachineSched)
4033ca95b02SDimitry Andric       return false;
4043ca95b02SDimitry Andric   } else if (!mf.getSubtarget().enablePostRAScheduler()) {
4054ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Subtarget disables post-MI-sched.\n");
40691bc56edSDimitry Andric     return false;
40791bc56edSDimitry Andric   }
4084ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Before post-MI-sched:\n"; mf.print(dbgs()));
40991bc56edSDimitry Andric 
41091bc56edSDimitry Andric   // Initialize the context of the pass.
41191bc56edSDimitry Andric   MF = &mf;
4122cab237bSDimitry Andric   MLI = &getAnalysis<MachineLoopInfo>();
41391bc56edSDimitry Andric   PassConfig = &getAnalysis<TargetPassConfig>();
41491bc56edSDimitry Andric 
41591bc56edSDimitry Andric   if (VerifyScheduling)
41691bc56edSDimitry Andric     MF->verify(this, "Before post machine scheduling.");
41791bc56edSDimitry Andric 
41891bc56edSDimitry Andric   // Instantiate the selected scheduler for this target, function, and
41991bc56edSDimitry Andric   // optimization level.
42091bc56edSDimitry Andric   std::unique_ptr<ScheduleDAGInstrs> Scheduler(createPostMachineScheduler());
4217d523365SDimitry Andric   scheduleRegions(*Scheduler, true);
42291bc56edSDimitry Andric 
42391bc56edSDimitry Andric   if (VerifyScheduling)
42491bc56edSDimitry Andric     MF->verify(this, "After post machine scheduling.");
42591bc56edSDimitry Andric   return true;
42691bc56edSDimitry Andric }
42791bc56edSDimitry Andric 
42891bc56edSDimitry Andric /// Return true of the given instruction should not be included in a scheduling
42991bc56edSDimitry Andric /// region.
43091bc56edSDimitry Andric ///
43191bc56edSDimitry Andric /// MachineScheduler does not currently support scheduling across calls. To
43291bc56edSDimitry Andric /// handle calls, the DAG builder needs to be modified to create register
43391bc56edSDimitry Andric /// anti/output dependencies on the registers clobbered by the call's regmask
43491bc56edSDimitry Andric /// operand. In PreRA scheduling, the stack pointer adjustment already prevents
43591bc56edSDimitry Andric /// scheduling across calls. In PostRA scheduling, we need the isCall to enforce
43691bc56edSDimitry Andric /// the boundary, but there would be no benefit to postRA scheduling across
43791bc56edSDimitry Andric /// calls this late anyway.
isSchedBoundary(MachineBasicBlock::iterator MI,MachineBasicBlock * MBB,MachineFunction * MF,const TargetInstrInfo * TII)43891bc56edSDimitry Andric static bool isSchedBoundary(MachineBasicBlock::iterator MI,
43991bc56edSDimitry Andric                             MachineBasicBlock *MBB,
44091bc56edSDimitry Andric                             MachineFunction *MF,
4417d523365SDimitry Andric                             const TargetInstrInfo *TII) {
4423ca95b02SDimitry Andric   return MI->isCall() || TII->isSchedulingBoundary(*MI, MBB, *MF);
44391bc56edSDimitry Andric }
44491bc56edSDimitry Andric 
4452cab237bSDimitry Andric /// A region of an MBB for scheduling.
4462cab237bSDimitry Andric namespace {
4472cab237bSDimitry Andric struct SchedRegion {
4482cab237bSDimitry Andric   /// RegionBegin is the first instruction in the scheduling region, and
4492cab237bSDimitry Andric   /// RegionEnd is either MBB->end() or the scheduling boundary after the
4502cab237bSDimitry Andric   /// last instruction in the scheduling region. These iterators cannot refer
4512cab237bSDimitry Andric   /// to instructions outside of the identified scheduling region because
4522cab237bSDimitry Andric   /// those may be reordered before scheduling this region.
4532cab237bSDimitry Andric   MachineBasicBlock::iterator RegionBegin;
4542cab237bSDimitry Andric   MachineBasicBlock::iterator RegionEnd;
4552cab237bSDimitry Andric   unsigned NumRegionInstrs;
4562cab237bSDimitry Andric 
SchedRegion__anon1997d06d0211::SchedRegion4572cab237bSDimitry Andric   SchedRegion(MachineBasicBlock::iterator B, MachineBasicBlock::iterator E,
4582cab237bSDimitry Andric               unsigned N) :
4592cab237bSDimitry Andric     RegionBegin(B), RegionEnd(E), NumRegionInstrs(N) {}
4602cab237bSDimitry Andric };
4612cab237bSDimitry Andric } // end anonymous namespace
4622cab237bSDimitry Andric 
4632cab237bSDimitry Andric using MBBRegionsVector = SmallVector<SchedRegion, 16>;
4642cab237bSDimitry Andric 
4652cab237bSDimitry Andric static void
getSchedRegions(MachineBasicBlock * MBB,MBBRegionsVector & Regions,bool RegionsTopDown)4662cab237bSDimitry Andric getSchedRegions(MachineBasicBlock *MBB,
4672cab237bSDimitry Andric                 MBBRegionsVector &Regions,
4682cab237bSDimitry Andric                 bool RegionsTopDown) {
4692cab237bSDimitry Andric   MachineFunction *MF = MBB->getParent();
4702cab237bSDimitry Andric   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
4712cab237bSDimitry Andric 
4722cab237bSDimitry Andric   MachineBasicBlock::iterator I = nullptr;
4732cab237bSDimitry Andric   for(MachineBasicBlock::iterator RegionEnd = MBB->end();
4742cab237bSDimitry Andric       RegionEnd != MBB->begin(); RegionEnd = I) {
4752cab237bSDimitry Andric 
4762cab237bSDimitry Andric     // Avoid decrementing RegionEnd for blocks with no terminator.
4772cab237bSDimitry Andric     if (RegionEnd != MBB->end() ||
4782cab237bSDimitry Andric         isSchedBoundary(&*std::prev(RegionEnd), &*MBB, MF, TII)) {
4792cab237bSDimitry Andric       --RegionEnd;
4802cab237bSDimitry Andric     }
4812cab237bSDimitry Andric 
4822cab237bSDimitry Andric     // The next region starts above the previous region. Look backward in the
4832cab237bSDimitry Andric     // instruction stream until we find the nearest boundary.
4842cab237bSDimitry Andric     unsigned NumRegionInstrs = 0;
4852cab237bSDimitry Andric     I = RegionEnd;
4862cab237bSDimitry Andric     for (;I != MBB->begin(); --I) {
4872cab237bSDimitry Andric       MachineInstr &MI = *std::prev(I);
4882cab237bSDimitry Andric       if (isSchedBoundary(&MI, &*MBB, MF, TII))
4892cab237bSDimitry Andric         break;
4904ba319b5SDimitry Andric       if (!MI.isDebugInstr())
4912cab237bSDimitry Andric         // MBB::size() uses instr_iterator to count. Here we need a bundle to
4922cab237bSDimitry Andric         // count as a single instruction.
4932cab237bSDimitry Andric         ++NumRegionInstrs;
4942cab237bSDimitry Andric     }
4952cab237bSDimitry Andric 
4962cab237bSDimitry Andric     Regions.push_back(SchedRegion(I, RegionEnd, NumRegionInstrs));
4972cab237bSDimitry Andric   }
4982cab237bSDimitry Andric 
4992cab237bSDimitry Andric   if (RegionsTopDown)
5002cab237bSDimitry Andric     std::reverse(Regions.begin(), Regions.end());
5012cab237bSDimitry Andric }
5022cab237bSDimitry Andric 
50391bc56edSDimitry Andric /// Main driver for both MachineScheduler and PostMachineScheduler.
scheduleRegions(ScheduleDAGInstrs & Scheduler,bool FixKillFlags)5047d523365SDimitry Andric void MachineSchedulerBase::scheduleRegions(ScheduleDAGInstrs &Scheduler,
5057d523365SDimitry Andric                                            bool FixKillFlags) {
506dff0c46cSDimitry Andric   // Visit all machine basic blocks.
5077ae0e2c9SDimitry Andric   //
5087ae0e2c9SDimitry Andric   // TODO: Visit blocks in global postorder or postorder within the bottom-up
5097ae0e2c9SDimitry Andric   // loop tree. Then we can optionally compute global RegPressure.
510dff0c46cSDimitry Andric   for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
511dff0c46cSDimitry Andric        MBB != MBBEnd; ++MBB) {
512dff0c46cSDimitry Andric 
5137d523365SDimitry Andric     Scheduler.startBlock(&*MBB);
51491bc56edSDimitry Andric 
51591bc56edSDimitry Andric #ifndef NDEBUG
51691bc56edSDimitry Andric     if (SchedOnlyFunc.getNumOccurrences() && SchedOnlyFunc != MF->getName())
51791bc56edSDimitry Andric       continue;
51891bc56edSDimitry Andric     if (SchedOnlyBlock.getNumOccurrences()
51991bc56edSDimitry Andric         && (int)SchedOnlyBlock != MBB->getNumber())
52091bc56edSDimitry Andric       continue;
52191bc56edSDimitry Andric #endif
522dff0c46cSDimitry Andric 
5232cab237bSDimitry Andric     // Break the block into scheduling regions [I, RegionEnd). RegionEnd
5242cab237bSDimitry Andric     // points to the scheduling boundary at the bottom of the region. The DAG
5252cab237bSDimitry Andric     // does not include RegionEnd, but the region does (i.e. the next
5262cab237bSDimitry Andric     // RegionEnd is above the previous RegionBegin). If the current block has
5272cab237bSDimitry Andric     // no terminator then RegionEnd == MBB->end() for the bottom region.
5282cab237bSDimitry Andric     //
5292cab237bSDimitry Andric     // All the regions of MBB are first found and stored in MBBRegions, which
5302cab237bSDimitry Andric     // will be processed (MBB) top-down if initialized with true.
531dff0c46cSDimitry Andric     //
532dff0c46cSDimitry Andric     // The Scheduler may insert instructions during either schedule() or
533dff0c46cSDimitry Andric     // exitRegion(), even for empty regions. So the local iterators 'I' and
5342cab237bSDimitry Andric     // 'RegionEnd' are invalid across these calls. Instructions must not be
5352cab237bSDimitry Andric     // added to other regions than the current one without updating MBBRegions.
5367ae0e2c9SDimitry Andric 
5372cab237bSDimitry Andric     MBBRegionsVector MBBRegions;
5382cab237bSDimitry Andric     getSchedRegions(&*MBB, MBBRegions, Scheduler.doMBBSchedRegionsTopDown());
5392cab237bSDimitry Andric     for (MBBRegionsVector::iterator R = MBBRegions.begin();
5402cab237bSDimitry Andric          R != MBBRegions.end(); ++R) {
5412cab237bSDimitry Andric       MachineBasicBlock::iterator I = R->RegionBegin;
5422cab237bSDimitry Andric       MachineBasicBlock::iterator RegionEnd = R->RegionEnd;
5432cab237bSDimitry Andric       unsigned NumRegionInstrs = R->NumRegionInstrs;
544dff0c46cSDimitry Andric 
545dff0c46cSDimitry Andric       // Notify the scheduler of the region, even if we may skip scheduling
546dff0c46cSDimitry Andric       // it. Perhaps it still needs to be bundled.
5477d523365SDimitry Andric       Scheduler.enterRegion(&*MBB, I, RegionEnd, NumRegionInstrs);
548dff0c46cSDimitry Andric 
549dff0c46cSDimitry Andric       // Skip empty scheduling regions (0 or 1 schedulable instructions).
55091bc56edSDimitry Andric       if (I == RegionEnd || I == std::prev(RegionEnd)) {
551dff0c46cSDimitry Andric         // Close the current region. Bundle the terminator if needed.
552dff0c46cSDimitry Andric         // This invalidates 'RegionEnd' and 'I'.
55391bc56edSDimitry Andric         Scheduler.exitRegion();
554dff0c46cSDimitry Andric         continue;
555dff0c46cSDimitry Andric       }
5564ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "********** MI Scheduling **********\n");
5574ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << MF->getName() << ":" << printMBBReference(*MBB)
5584ba319b5SDimitry Andric                         << " " << MBB->getName() << "\n  From: " << *I
5594ba319b5SDimitry Andric                         << "    To: ";
560dff0c46cSDimitry Andric                  if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
561dff0c46cSDimitry Andric                  else dbgs() << "End";
5623ca95b02SDimitry Andric                  dbgs() << " RegionInstrs: " << NumRegionInstrs << '\n');
56339d628a0SDimitry Andric       if (DumpCriticalPathLength) {
56439d628a0SDimitry Andric         errs() << MF->getName();
5652cab237bSDimitry Andric         errs() << ":%bb. " << MBB->getNumber();
56639d628a0SDimitry Andric         errs() << " " << MBB->getName() << " \n";
56739d628a0SDimitry Andric       }
568dff0c46cSDimitry Andric 
569dff0c46cSDimitry Andric       // Schedule a region: possibly reorder instructions.
5702cab237bSDimitry Andric       // This invalidates the original region iterators.
57191bc56edSDimitry Andric       Scheduler.schedule();
572dff0c46cSDimitry Andric 
573dff0c46cSDimitry Andric       // Close the current region.
57491bc56edSDimitry Andric       Scheduler.exitRegion();
575dff0c46cSDimitry Andric     }
57691bc56edSDimitry Andric     Scheduler.finishBlock();
57791bc56edSDimitry Andric     // FIXME: Ideally, no further passes should rely on kill flags. However,
5787d523365SDimitry Andric     // thumb2 size reduction is currently an exception, so the PostMIScheduler
5797d523365SDimitry Andric     // needs to do this.
5807d523365SDimitry Andric     if (FixKillFlags)
581302affcbSDimitry Andric       Scheduler.fixupKills(*MBB);
58291bc56edSDimitry Andric   }
58391bc56edSDimitry Andric   Scheduler.finalizeSchedule();
584dff0c46cSDimitry Andric }
585dff0c46cSDimitry Andric 
print(raw_ostream & O,const Module * m) const58691bc56edSDimitry Andric void MachineSchedulerBase::print(raw_ostream &O, const Module* m) const {
587dff0c46cSDimitry Andric   // unimplemented
588dff0c46cSDimitry Andric }
589dff0c46cSDimitry Andric 
5907a7e6055SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump() const591edd7eaddSDimitry Andric LLVM_DUMP_METHOD void ReadyQueue::dump() const {
5927d523365SDimitry Andric   dbgs() << "Queue " << Name << ": ";
593edd7eaddSDimitry Andric   for (const SUnit *SU : Queue)
594edd7eaddSDimitry Andric     dbgs() << SU->NodeNum << " ";
5953861d79fSDimitry Andric   dbgs() << "\n";
5963861d79fSDimitry Andric }
5977a7e6055SDimitry Andric #endif
598dff0c46cSDimitry Andric 
599dff0c46cSDimitry Andric //===----------------------------------------------------------------------===//
60091bc56edSDimitry Andric // ScheduleDAGMI - Basic machine instruction scheduling. This is
60191bc56edSDimitry Andric // independent of PreRA/PostRA scheduling and involves no extra book-keeping for
60291bc56edSDimitry Andric // virtual registers.
60391bc56edSDimitry Andric // ===----------------------------------------------------------------------===/
604dff0c46cSDimitry Andric 
60591bc56edSDimitry Andric // Provide a vtable anchor.
6067a7e6055SDimitry Andric ScheduleDAGMI::~ScheduleDAGMI() = default;
607139f7f9bSDimitry Andric 
canAddEdge(SUnit * SuccSU,SUnit * PredSU)608284c1978SDimitry Andric bool ScheduleDAGMI::canAddEdge(SUnit *SuccSU, SUnit *PredSU) {
609284c1978SDimitry Andric   return SuccSU == &ExitSU || !Topo.IsReachable(PredSU, SuccSU);
610284c1978SDimitry Andric }
611284c1978SDimitry Andric 
addEdge(SUnit * SuccSU,const SDep & PredDep)612139f7f9bSDimitry Andric bool ScheduleDAGMI::addEdge(SUnit *SuccSU, const SDep &PredDep) {
613139f7f9bSDimitry Andric   if (SuccSU != &ExitSU) {
614139f7f9bSDimitry Andric     // Do not use WillCreateCycle, it assumes SD scheduling.
615139f7f9bSDimitry Andric     // If Pred is reachable from Succ, then the edge creates a cycle.
616139f7f9bSDimitry Andric     if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
617139f7f9bSDimitry Andric       return false;
618139f7f9bSDimitry Andric     Topo.AddPred(SuccSU, PredDep.getSUnit());
619139f7f9bSDimitry Andric   }
620139f7f9bSDimitry Andric   SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
621139f7f9bSDimitry Andric   // Return true regardless of whether a new edge needed to be inserted.
622139f7f9bSDimitry Andric   return true;
623139f7f9bSDimitry Andric }
624139f7f9bSDimitry Andric 
625dff0c46cSDimitry Andric /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
626dff0c46cSDimitry Andric /// NumPredsLeft reaches zero, release the successor node.
6277ae0e2c9SDimitry Andric ///
6287ae0e2c9SDimitry Andric /// FIXME: Adjust SuccSU height based on MinLatency.
releaseSucc(SUnit * SU,SDep * SuccEdge)629dff0c46cSDimitry Andric void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
630dff0c46cSDimitry Andric   SUnit *SuccSU = SuccEdge->getSUnit();
631dff0c46cSDimitry Andric 
632139f7f9bSDimitry Andric   if (SuccEdge->isWeak()) {
633139f7f9bSDimitry Andric     --SuccSU->WeakPredsLeft;
634139f7f9bSDimitry Andric     if (SuccEdge->isCluster())
635139f7f9bSDimitry Andric       NextClusterSucc = SuccSU;
636139f7f9bSDimitry Andric     return;
637139f7f9bSDimitry Andric   }
638dff0c46cSDimitry Andric #ifndef NDEBUG
639dff0c46cSDimitry Andric   if (SuccSU->NumPredsLeft == 0) {
640dff0c46cSDimitry Andric     dbgs() << "*** Scheduling failed! ***\n";
641*b5893f02SDimitry Andric     dumpNode(*SuccSU);
642dff0c46cSDimitry Andric     dbgs() << " has been released too many times!\n";
64391bc56edSDimitry Andric     llvm_unreachable(nullptr);
644dff0c46cSDimitry Andric   }
645dff0c46cSDimitry Andric #endif
64691bc56edSDimitry Andric   // SU->TopReadyCycle was set to CurrCycle when it was scheduled. However,
64791bc56edSDimitry Andric   // CurrCycle may have advanced since then.
64891bc56edSDimitry Andric   if (SuccSU->TopReadyCycle < SU->TopReadyCycle + SuccEdge->getLatency())
64991bc56edSDimitry Andric     SuccSU->TopReadyCycle = SU->TopReadyCycle + SuccEdge->getLatency();
65091bc56edSDimitry Andric 
651dff0c46cSDimitry Andric   --SuccSU->NumPredsLeft;
652dff0c46cSDimitry Andric   if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
653dff0c46cSDimitry Andric     SchedImpl->releaseTopNode(SuccSU);
654dff0c46cSDimitry Andric }
655dff0c46cSDimitry Andric 
656dff0c46cSDimitry Andric /// releaseSuccessors - Call releaseSucc on each of SU's successors.
releaseSuccessors(SUnit * SU)657dff0c46cSDimitry Andric void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
658edd7eaddSDimitry Andric   for (SDep &Succ : SU->Succs)
659edd7eaddSDimitry Andric     releaseSucc(SU, &Succ);
660dff0c46cSDimitry Andric }
661dff0c46cSDimitry Andric 
662dff0c46cSDimitry Andric /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
663dff0c46cSDimitry Andric /// NumSuccsLeft reaches zero, release the predecessor node.
6647ae0e2c9SDimitry Andric ///
6657ae0e2c9SDimitry Andric /// FIXME: Adjust PredSU height based on MinLatency.
releasePred(SUnit * SU,SDep * PredEdge)666dff0c46cSDimitry Andric void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
667dff0c46cSDimitry Andric   SUnit *PredSU = PredEdge->getSUnit();
668dff0c46cSDimitry Andric 
669139f7f9bSDimitry Andric   if (PredEdge->isWeak()) {
670139f7f9bSDimitry Andric     --PredSU->WeakSuccsLeft;
671139f7f9bSDimitry Andric     if (PredEdge->isCluster())
672139f7f9bSDimitry Andric       NextClusterPred = PredSU;
673139f7f9bSDimitry Andric     return;
674139f7f9bSDimitry Andric   }
675dff0c46cSDimitry Andric #ifndef NDEBUG
676dff0c46cSDimitry Andric   if (PredSU->NumSuccsLeft == 0) {
677dff0c46cSDimitry Andric     dbgs() << "*** Scheduling failed! ***\n";
678*b5893f02SDimitry Andric     dumpNode(*PredSU);
679dff0c46cSDimitry Andric     dbgs() << " has been released too many times!\n";
68091bc56edSDimitry Andric     llvm_unreachable(nullptr);
681dff0c46cSDimitry Andric   }
682dff0c46cSDimitry Andric #endif
68391bc56edSDimitry Andric   // SU->BotReadyCycle was set to CurrCycle when it was scheduled. However,
68491bc56edSDimitry Andric   // CurrCycle may have advanced since then.
68591bc56edSDimitry Andric   if (PredSU->BotReadyCycle < SU->BotReadyCycle + PredEdge->getLatency())
68691bc56edSDimitry Andric     PredSU->BotReadyCycle = SU->BotReadyCycle + PredEdge->getLatency();
68791bc56edSDimitry Andric 
688dff0c46cSDimitry Andric   --PredSU->NumSuccsLeft;
689dff0c46cSDimitry Andric   if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
690dff0c46cSDimitry Andric     SchedImpl->releaseBottomNode(PredSU);
691dff0c46cSDimitry Andric }
692dff0c46cSDimitry Andric 
693dff0c46cSDimitry Andric /// releasePredecessors - Call releasePred on each of SU's predecessors.
releasePredecessors(SUnit * SU)694dff0c46cSDimitry Andric void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
695edd7eaddSDimitry Andric   for (SDep &Pred : SU->Preds)
696edd7eaddSDimitry Andric     releasePred(SU, &Pred);
697dff0c46cSDimitry Andric }
698dff0c46cSDimitry Andric 
startBlock(MachineBasicBlock * bb)6992cab237bSDimitry Andric void ScheduleDAGMI::startBlock(MachineBasicBlock *bb) {
7002cab237bSDimitry Andric   ScheduleDAGInstrs::startBlock(bb);
7012cab237bSDimitry Andric   SchedImpl->enterMBB(bb);
7022cab237bSDimitry Andric }
7032cab237bSDimitry Andric 
finishBlock()7042cab237bSDimitry Andric void ScheduleDAGMI::finishBlock() {
7052cab237bSDimitry Andric   SchedImpl->leaveMBB();
7062cab237bSDimitry Andric   ScheduleDAGInstrs::finishBlock();
7072cab237bSDimitry Andric }
7082cab237bSDimitry Andric 
70991bc56edSDimitry Andric /// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
71091bc56edSDimitry Andric /// crossing a scheduling boundary. [begin, end) includes all instructions in
71191bc56edSDimitry Andric /// the region, including the boundary itself and single-instruction regions
71291bc56edSDimitry Andric /// that don't get scheduled.
enterRegion(MachineBasicBlock * bb,MachineBasicBlock::iterator begin,MachineBasicBlock::iterator end,unsigned regioninstrs)71391bc56edSDimitry Andric void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
71491bc56edSDimitry Andric                                      MachineBasicBlock::iterator begin,
71591bc56edSDimitry Andric                                      MachineBasicBlock::iterator end,
71691bc56edSDimitry Andric                                      unsigned regioninstrs)
71791bc56edSDimitry Andric {
71891bc56edSDimitry Andric   ScheduleDAGInstrs::enterRegion(bb, begin, end, regioninstrs);
71991bc56edSDimitry Andric 
72091bc56edSDimitry Andric   SchedImpl->initPolicy(begin, end, regioninstrs);
72191bc56edSDimitry Andric }
72291bc56edSDimitry Andric 
723284c1978SDimitry Andric /// This is normally called from the main scheduler loop but may also be invoked
724284c1978SDimitry Andric /// by the scheduling strategy to perform additional code motion.
moveInstruction(MachineInstr * MI,MachineBasicBlock::iterator InsertPos)72591bc56edSDimitry Andric void ScheduleDAGMI::moveInstruction(
72691bc56edSDimitry Andric   MachineInstr *MI, MachineBasicBlock::iterator InsertPos) {
7277ae0e2c9SDimitry Andric   // Advance RegionBegin if the first instruction moves down.
728dff0c46cSDimitry Andric   if (&*RegionBegin == MI)
7297ae0e2c9SDimitry Andric     ++RegionBegin;
7307ae0e2c9SDimitry Andric 
7317ae0e2c9SDimitry Andric   // Update the instruction stream.
732dff0c46cSDimitry Andric   BB->splice(InsertPos, BB, MI);
7337ae0e2c9SDimitry Andric 
7347ae0e2c9SDimitry Andric   // Update LiveIntervals
73591bc56edSDimitry Andric   if (LIS)
7363ca95b02SDimitry Andric     LIS->handleMove(*MI, /*UpdateFlags=*/true);
7377ae0e2c9SDimitry Andric 
7387ae0e2c9SDimitry Andric   // Recede RegionBegin if an instruction moves above the first.
739dff0c46cSDimitry Andric   if (RegionBegin == InsertPos)
740dff0c46cSDimitry Andric     RegionBegin = MI;
741dff0c46cSDimitry Andric }
742dff0c46cSDimitry Andric 
checkSchedLimit()743dff0c46cSDimitry Andric bool ScheduleDAGMI::checkSchedLimit() {
744dff0c46cSDimitry Andric #ifndef NDEBUG
745dff0c46cSDimitry Andric   if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
746dff0c46cSDimitry Andric     CurrentTop = CurrentBottom;
747dff0c46cSDimitry Andric     return false;
748dff0c46cSDimitry Andric   }
749dff0c46cSDimitry Andric   ++NumInstrsScheduled;
750dff0c46cSDimitry Andric #endif
751dff0c46cSDimitry Andric   return true;
752dff0c46cSDimitry Andric }
753dff0c46cSDimitry Andric 
75491bc56edSDimitry Andric /// Per-region scheduling driver, called back from
75591bc56edSDimitry Andric /// MachineScheduler::runOnMachineFunction. This is a simplified driver that
75691bc56edSDimitry Andric /// does not consider liveness or register pressure. It is useful for PostRA
75791bc56edSDimitry Andric /// scheduling and potentially other custom schedulers.
schedule()75891bc56edSDimitry Andric void ScheduleDAGMI::schedule() {
7594ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "ScheduleDAGMI::schedule starting\n");
7604ba319b5SDimitry Andric   LLVM_DEBUG(SchedImpl->dumpPolicy());
7617d523365SDimitry Andric 
76291bc56edSDimitry Andric   // Build the DAG.
76391bc56edSDimitry Andric   buildSchedGraph(AA);
76491bc56edSDimitry Andric 
76591bc56edSDimitry Andric   Topo.InitDAGTopologicalSorting();
76691bc56edSDimitry Andric 
76791bc56edSDimitry Andric   postprocessDAG();
76891bc56edSDimitry Andric 
76991bc56edSDimitry Andric   SmallVector<SUnit*, 8> TopRoots, BotRoots;
77091bc56edSDimitry Andric   findRootsAndBiasEdges(TopRoots, BotRoots);
77191bc56edSDimitry Andric 
772*b5893f02SDimitry Andric   LLVM_DEBUG(dump());
773*b5893f02SDimitry Andric   if (PrintDAGs) dump();
7744ba319b5SDimitry Andric   if (ViewMISchedDAGs) viewGraph();
7754ba319b5SDimitry Andric 
77691bc56edSDimitry Andric   // Initialize the strategy before modifying the DAG.
77791bc56edSDimitry Andric   // This may initialize a DFSResult to be used for queue priority.
77891bc56edSDimitry Andric   SchedImpl->initialize(this);
77991bc56edSDimitry Andric 
78091bc56edSDimitry Andric   // Initialize ready queues now that the DAG and priority data are finalized.
78191bc56edSDimitry Andric   initQueues(TopRoots, BotRoots);
78291bc56edSDimitry Andric 
78391bc56edSDimitry Andric   bool IsTopNode = false;
7847d523365SDimitry Andric   while (true) {
7854ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "** ScheduleDAGMI::schedule picking next node\n");
7867d523365SDimitry Andric     SUnit *SU = SchedImpl->pickNode(IsTopNode);
7877d523365SDimitry Andric     if (!SU) break;
7887d523365SDimitry Andric 
78991bc56edSDimitry Andric     assert(!SU->isScheduled && "Node already scheduled");
79091bc56edSDimitry Andric     if (!checkSchedLimit())
79191bc56edSDimitry Andric       break;
79291bc56edSDimitry Andric 
79391bc56edSDimitry Andric     MachineInstr *MI = SU->getInstr();
79491bc56edSDimitry Andric     if (IsTopNode) {
79591bc56edSDimitry Andric       assert(SU->isTopReady() && "node still has unscheduled dependencies");
79691bc56edSDimitry Andric       if (&*CurrentTop == MI)
79791bc56edSDimitry Andric         CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
79891bc56edSDimitry Andric       else
79991bc56edSDimitry Andric         moveInstruction(MI, CurrentTop);
8003ca95b02SDimitry Andric     } else {
80191bc56edSDimitry Andric       assert(SU->isBottomReady() && "node still has unscheduled dependencies");
80291bc56edSDimitry Andric       MachineBasicBlock::iterator priorII =
80391bc56edSDimitry Andric         priorNonDebug(CurrentBottom, CurrentTop);
80491bc56edSDimitry Andric       if (&*priorII == MI)
80591bc56edSDimitry Andric         CurrentBottom = priorII;
80691bc56edSDimitry Andric       else {
80791bc56edSDimitry Andric         if (&*CurrentTop == MI)
80891bc56edSDimitry Andric           CurrentTop = nextIfDebug(++CurrentTop, priorII);
80991bc56edSDimitry Andric         moveInstruction(MI, CurrentBottom);
81091bc56edSDimitry Andric         CurrentBottom = MI;
81191bc56edSDimitry Andric       }
81291bc56edSDimitry Andric     }
81391bc56edSDimitry Andric     // Notify the scheduling strategy before updating the DAG.
81491bc56edSDimitry Andric     // This sets the scheduled node's ReadyCycle to CurrCycle. When updateQueues
81591bc56edSDimitry Andric     // runs, it can then use the accurate ReadyCycle time to determine whether
81691bc56edSDimitry Andric     // newly released nodes can move to the readyQ.
81791bc56edSDimitry Andric     SchedImpl->schedNode(SU, IsTopNode);
81891bc56edSDimitry Andric 
81991bc56edSDimitry Andric     updateQueues(SU, IsTopNode);
82091bc56edSDimitry Andric   }
82191bc56edSDimitry Andric   assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
82291bc56edSDimitry Andric 
82391bc56edSDimitry Andric   placeDebugValues();
82491bc56edSDimitry Andric 
8254ba319b5SDimitry Andric   LLVM_DEBUG({
8262cab237bSDimitry Andric     dbgs() << "*** Final schedule for "
8272cab237bSDimitry Andric            << printMBBReference(*begin()->getParent()) << " ***\n";
82891bc56edSDimitry Andric     dumpSchedule();
82991bc56edSDimitry Andric     dbgs() << '\n';
83091bc56edSDimitry Andric   });
83191bc56edSDimitry Andric }
83291bc56edSDimitry Andric 
83391bc56edSDimitry Andric /// Apply each ScheduleDAGMutation step in order.
postprocessDAG()83491bc56edSDimitry Andric void ScheduleDAGMI::postprocessDAG() {
835edd7eaddSDimitry Andric   for (auto &m : Mutations)
836edd7eaddSDimitry Andric     m->apply(this);
83791bc56edSDimitry Andric }
83891bc56edSDimitry Andric 
83991bc56edSDimitry Andric void ScheduleDAGMI::
findRootsAndBiasEdges(SmallVectorImpl<SUnit * > & TopRoots,SmallVectorImpl<SUnit * > & BotRoots)84091bc56edSDimitry Andric findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
84191bc56edSDimitry Andric                       SmallVectorImpl<SUnit*> &BotRoots) {
842edd7eaddSDimitry Andric   for (SUnit &SU : SUnits) {
843edd7eaddSDimitry Andric     assert(!SU.isBoundaryNode() && "Boundary node should not be in SUnits");
84491bc56edSDimitry Andric 
84591bc56edSDimitry Andric     // Order predecessors so DFSResult follows the critical path.
846edd7eaddSDimitry Andric     SU.biasCriticalPath();
84791bc56edSDimitry Andric 
84891bc56edSDimitry Andric     // A SUnit is ready to top schedule if it has no predecessors.
849edd7eaddSDimitry Andric     if (!SU.NumPredsLeft)
850edd7eaddSDimitry Andric       TopRoots.push_back(&SU);
85191bc56edSDimitry Andric     // A SUnit is ready to bottom schedule if it has no successors.
852edd7eaddSDimitry Andric     if (!SU.NumSuccsLeft)
853edd7eaddSDimitry Andric       BotRoots.push_back(&SU);
85491bc56edSDimitry Andric   }
85591bc56edSDimitry Andric   ExitSU.biasCriticalPath();
85691bc56edSDimitry Andric }
85791bc56edSDimitry Andric 
85891bc56edSDimitry Andric /// Identify DAG roots and setup scheduler queues.
initQueues(ArrayRef<SUnit * > TopRoots,ArrayRef<SUnit * > BotRoots)85991bc56edSDimitry Andric void ScheduleDAGMI::initQueues(ArrayRef<SUnit*> TopRoots,
86091bc56edSDimitry Andric                                ArrayRef<SUnit*> BotRoots) {
86191bc56edSDimitry Andric   NextClusterSucc = nullptr;
86291bc56edSDimitry Andric   NextClusterPred = nullptr;
86391bc56edSDimitry Andric 
86491bc56edSDimitry Andric   // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
86591bc56edSDimitry Andric   //
86691bc56edSDimitry Andric   // Nodes with unreleased weak edges can still be roots.
86791bc56edSDimitry Andric   // Release top roots in forward order.
868edd7eaddSDimitry Andric   for (SUnit *SU : TopRoots)
869edd7eaddSDimitry Andric     SchedImpl->releaseTopNode(SU);
870edd7eaddSDimitry Andric 
87191bc56edSDimitry Andric   // Release bottom roots in reverse order so the higher priority nodes appear
87291bc56edSDimitry Andric   // first. This is more natural and slightly more efficient.
87391bc56edSDimitry Andric   for (SmallVectorImpl<SUnit*>::const_reverse_iterator
87491bc56edSDimitry Andric          I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I) {
87591bc56edSDimitry Andric     SchedImpl->releaseBottomNode(*I);
87691bc56edSDimitry Andric   }
87791bc56edSDimitry Andric 
87891bc56edSDimitry Andric   releaseSuccessors(&EntrySU);
87991bc56edSDimitry Andric   releasePredecessors(&ExitSU);
88091bc56edSDimitry Andric 
88191bc56edSDimitry Andric   SchedImpl->registerRoots();
88291bc56edSDimitry Andric 
88391bc56edSDimitry Andric   // Advance past initial DebugValues.
88491bc56edSDimitry Andric   CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
88591bc56edSDimitry Andric   CurrentBottom = RegionEnd;
88691bc56edSDimitry Andric }
88791bc56edSDimitry Andric 
88891bc56edSDimitry Andric /// Update scheduler queues after scheduling an instruction.
updateQueues(SUnit * SU,bool IsTopNode)88991bc56edSDimitry Andric void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
89091bc56edSDimitry Andric   // Release dependent instructions for scheduling.
89191bc56edSDimitry Andric   if (IsTopNode)
89291bc56edSDimitry Andric     releaseSuccessors(SU);
89391bc56edSDimitry Andric   else
89491bc56edSDimitry Andric     releasePredecessors(SU);
89591bc56edSDimitry Andric 
89691bc56edSDimitry Andric   SU->isScheduled = true;
89791bc56edSDimitry Andric }
89891bc56edSDimitry Andric 
89991bc56edSDimitry Andric /// Reinsert any remaining debug_values, just like the PostRA scheduler.
placeDebugValues()90091bc56edSDimitry Andric void ScheduleDAGMI::placeDebugValues() {
90191bc56edSDimitry Andric   // If first instruction was a DBG_VALUE then put it back.
90291bc56edSDimitry Andric   if (FirstDbgValue) {
90391bc56edSDimitry Andric     BB->splice(RegionBegin, BB, FirstDbgValue);
90491bc56edSDimitry Andric     RegionBegin = FirstDbgValue;
90591bc56edSDimitry Andric   }
90691bc56edSDimitry Andric 
90791bc56edSDimitry Andric   for (std::vector<std::pair<MachineInstr *, MachineInstr *>>::iterator
90891bc56edSDimitry Andric          DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
90991bc56edSDimitry Andric     std::pair<MachineInstr *, MachineInstr *> P = *std::prev(DI);
91091bc56edSDimitry Andric     MachineInstr *DbgValue = P.first;
91191bc56edSDimitry Andric     MachineBasicBlock::iterator OrigPrevMI = P.second;
91291bc56edSDimitry Andric     if (&*RegionBegin == DbgValue)
91391bc56edSDimitry Andric       ++RegionBegin;
91491bc56edSDimitry Andric     BB->splice(++OrigPrevMI, BB, DbgValue);
91591bc56edSDimitry Andric     if (OrigPrevMI == std::prev(RegionEnd))
91691bc56edSDimitry Andric       RegionEnd = DbgValue;
91791bc56edSDimitry Andric   }
91891bc56edSDimitry Andric   DbgValues.clear();
91991bc56edSDimitry Andric   FirstDbgValue = nullptr;
92091bc56edSDimitry Andric }
92191bc56edSDimitry Andric 
92291bc56edSDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dumpSchedule() const9237a7e6055SDimitry Andric LLVM_DUMP_METHOD void ScheduleDAGMI::dumpSchedule() const {
92491bc56edSDimitry Andric   for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
92591bc56edSDimitry Andric     if (SUnit *SU = getSUnit(&(*MI)))
926*b5893f02SDimitry Andric       dumpNode(*SU);
92791bc56edSDimitry Andric     else
92891bc56edSDimitry Andric       dbgs() << "Missing SUnit\n";
92991bc56edSDimitry Andric   }
93091bc56edSDimitry Andric }
93191bc56edSDimitry Andric #endif
93291bc56edSDimitry Andric 
93391bc56edSDimitry Andric //===----------------------------------------------------------------------===//
93491bc56edSDimitry Andric // ScheduleDAGMILive - Base class for MachineInstr scheduling with LiveIntervals
93591bc56edSDimitry Andric // preservation.
93691bc56edSDimitry Andric //===----------------------------------------------------------------------===//
93791bc56edSDimitry Andric 
~ScheduleDAGMILive()93891bc56edSDimitry Andric ScheduleDAGMILive::~ScheduleDAGMILive() {
93991bc56edSDimitry Andric   delete DFSResult;
94091bc56edSDimitry Andric }
94191bc56edSDimitry Andric 
collectVRegUses(SUnit & SU)942d88c1a5aSDimitry Andric void ScheduleDAGMILive::collectVRegUses(SUnit &SU) {
943d88c1a5aSDimitry Andric   const MachineInstr &MI = *SU.getInstr();
944d88c1a5aSDimitry Andric   for (const MachineOperand &MO : MI.operands()) {
945d88c1a5aSDimitry Andric     if (!MO.isReg())
946d88c1a5aSDimitry Andric       continue;
947d88c1a5aSDimitry Andric     if (!MO.readsReg())
948d88c1a5aSDimitry Andric       continue;
949d88c1a5aSDimitry Andric     if (TrackLaneMasks && !MO.isUse())
950d88c1a5aSDimitry Andric       continue;
951d88c1a5aSDimitry Andric 
952d88c1a5aSDimitry Andric     unsigned Reg = MO.getReg();
953d88c1a5aSDimitry Andric     if (!TargetRegisterInfo::isVirtualRegister(Reg))
954d88c1a5aSDimitry Andric       continue;
955d88c1a5aSDimitry Andric 
956d88c1a5aSDimitry Andric     // Ignore re-defs.
957d88c1a5aSDimitry Andric     if (TrackLaneMasks) {
958d88c1a5aSDimitry Andric       bool FoundDef = false;
959d88c1a5aSDimitry Andric       for (const MachineOperand &MO2 : MI.operands()) {
960d88c1a5aSDimitry Andric         if (MO2.isReg() && MO2.isDef() && MO2.getReg() == Reg && !MO2.isDead()) {
961d88c1a5aSDimitry Andric           FoundDef = true;
962d88c1a5aSDimitry Andric           break;
963d88c1a5aSDimitry Andric         }
964d88c1a5aSDimitry Andric       }
965d88c1a5aSDimitry Andric       if (FoundDef)
966d88c1a5aSDimitry Andric         continue;
967d88c1a5aSDimitry Andric     }
968d88c1a5aSDimitry Andric 
969d88c1a5aSDimitry Andric     // Record this local VReg use.
970d88c1a5aSDimitry Andric     VReg2SUnitMultiMap::iterator UI = VRegUses.find(Reg);
971d88c1a5aSDimitry Andric     for (; UI != VRegUses.end(); ++UI) {
972d88c1a5aSDimitry Andric       if (UI->SU == &SU)
973d88c1a5aSDimitry Andric         break;
974d88c1a5aSDimitry Andric     }
975d88c1a5aSDimitry Andric     if (UI == VRegUses.end())
976d88c1a5aSDimitry Andric       VRegUses.insert(VReg2SUnit(Reg, LaneBitmask::getNone(), &SU));
977d88c1a5aSDimitry Andric   }
978d88c1a5aSDimitry Andric }
979d88c1a5aSDimitry Andric 
9807ae0e2c9SDimitry Andric /// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
9817ae0e2c9SDimitry Andric /// crossing a scheduling boundary. [begin, end) includes all instructions in
9827ae0e2c9SDimitry Andric /// the region, including the boundary itself and single-instruction regions
9837ae0e2c9SDimitry Andric /// that don't get scheduled.
enterRegion(MachineBasicBlock * bb,MachineBasicBlock::iterator begin,MachineBasicBlock::iterator end,unsigned regioninstrs)98491bc56edSDimitry Andric void ScheduleDAGMILive::enterRegion(MachineBasicBlock *bb,
9857ae0e2c9SDimitry Andric                                 MachineBasicBlock::iterator begin,
9867ae0e2c9SDimitry Andric                                 MachineBasicBlock::iterator end,
987f785676fSDimitry Andric                                 unsigned regioninstrs)
9887ae0e2c9SDimitry Andric {
98991bc56edSDimitry Andric   // ScheduleDAGMI initializes SchedImpl's per-region policy.
99091bc56edSDimitry Andric   ScheduleDAGMI::enterRegion(bb, begin, end, regioninstrs);
991dff0c46cSDimitry Andric 
9927ae0e2c9SDimitry Andric   // For convenience remember the end of the liveness region.
99391bc56edSDimitry Andric   LiveRegionEnd = (RegionEnd == bb->end()) ? RegionEnd : std::next(RegionEnd);
994f785676fSDimitry Andric 
995f785676fSDimitry Andric   SUPressureDiffs.clear();
996f785676fSDimitry Andric 
997f785676fSDimitry Andric   ShouldTrackPressure = SchedImpl->shouldTrackPressure();
9983ca95b02SDimitry Andric   ShouldTrackLaneMasks = SchedImpl->shouldTrackLaneMasks();
9993ca95b02SDimitry Andric 
10003ca95b02SDimitry Andric   assert((!ShouldTrackLaneMasks || ShouldTrackPressure) &&
10013ca95b02SDimitry Andric          "ShouldTrackLaneMasks requires ShouldTrackPressure");
10027ae0e2c9SDimitry Andric }
10037ae0e2c9SDimitry Andric 
10047ae0e2c9SDimitry Andric // Setup the register pressure trackers for the top scheduled top and bottom
10057ae0e2c9SDimitry Andric // scheduled regions.
initRegPressure()100691bc56edSDimitry Andric void ScheduleDAGMILive::initRegPressure() {
1007d88c1a5aSDimitry Andric   VRegUses.clear();
1008d88c1a5aSDimitry Andric   VRegUses.setUniverse(MRI.getNumVirtRegs());
1009d88c1a5aSDimitry Andric   for (SUnit &SU : SUnits)
1010d88c1a5aSDimitry Andric     collectVRegUses(SU);
1011d88c1a5aSDimitry Andric 
10123ca95b02SDimitry Andric   TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin,
10133ca95b02SDimitry Andric                     ShouldTrackLaneMasks, false);
10143ca95b02SDimitry Andric   BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
10153ca95b02SDimitry Andric                     ShouldTrackLaneMasks, false);
10167ae0e2c9SDimitry Andric 
10177ae0e2c9SDimitry Andric   // Close the RPTracker to finalize live ins.
10187ae0e2c9SDimitry Andric   RPTracker.closeRegion();
10197ae0e2c9SDimitry Andric 
10204ba319b5SDimitry Andric   LLVM_DEBUG(RPTracker.dump());
10217ae0e2c9SDimitry Andric 
10227ae0e2c9SDimitry Andric   // Initialize the live ins and live outs.
10237ae0e2c9SDimitry Andric   TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
10247ae0e2c9SDimitry Andric   BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
10257ae0e2c9SDimitry Andric 
10267ae0e2c9SDimitry Andric   // Close one end of the tracker so we can call
10277ae0e2c9SDimitry Andric   // getMaxUpward/DownwardPressureDelta before advancing across any
10287ae0e2c9SDimitry Andric   // instructions. This converts currently live regs into live ins/outs.
10297ae0e2c9SDimitry Andric   TopRPTracker.closeTop();
10307ae0e2c9SDimitry Andric   BotRPTracker.closeBottom();
10317ae0e2c9SDimitry Andric 
1032f785676fSDimitry Andric   BotRPTracker.initLiveThru(RPTracker);
1033f785676fSDimitry Andric   if (!BotRPTracker.getLiveThru().empty()) {
1034f785676fSDimitry Andric     TopRPTracker.initLiveThru(BotRPTracker.getLiveThru());
10354ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Live Thru: ";
1036f785676fSDimitry Andric                dumpRegSetPressure(BotRPTracker.getLiveThru(), TRI));
1037f785676fSDimitry Andric   };
1038f785676fSDimitry Andric 
1039f785676fSDimitry Andric   // For each live out vreg reduce the pressure change associated with other
1040f785676fSDimitry Andric   // uses of the same vreg below the live-out reaching def.
1041f785676fSDimitry Andric   updatePressureDiffs(RPTracker.getPressure().LiveOutRegs);
1042f785676fSDimitry Andric 
10437ae0e2c9SDimitry Andric   // Account for liveness generated by the region boundary.
1044f785676fSDimitry Andric   if (LiveRegionEnd != RegionEnd) {
10453ca95b02SDimitry Andric     SmallVector<RegisterMaskPair, 8> LiveUses;
1046f785676fSDimitry Andric     BotRPTracker.recede(&LiveUses);
1047f785676fSDimitry Andric     updatePressureDiffs(LiveUses);
1048f785676fSDimitry Andric   }
10497ae0e2c9SDimitry Andric 
10504ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Top Pressure:\n";
10517d523365SDimitry Andric              dumpRegSetPressure(TopRPTracker.getRegSetPressureAtPos(), TRI);
10527d523365SDimitry Andric              dbgs() << "Bottom Pressure:\n";
10534ba319b5SDimitry Andric              dumpRegSetPressure(BotRPTracker.getRegSetPressureAtPos(), TRI););
10547d523365SDimitry Andric 
10552cab237bSDimitry Andric   assert((BotRPTracker.getPos() == RegionEnd ||
10564ba319b5SDimitry Andric           (RegionEnd->isDebugInstr() &&
10572cab237bSDimitry Andric            BotRPTracker.getPos() == priorNonDebug(RegionEnd, RegionBegin))) &&
10582cab237bSDimitry Andric          "Can't find the region bottom");
10597ae0e2c9SDimitry Andric 
10607ae0e2c9SDimitry Andric   // Cache the list of excess pressure sets in this region. This will also track
10617ae0e2c9SDimitry Andric   // the max pressure in the scheduled code for these sets.
10627ae0e2c9SDimitry Andric   RegionCriticalPSets.clear();
1063139f7f9bSDimitry Andric   const std::vector<unsigned> &RegionPressure =
1064139f7f9bSDimitry Andric     RPTracker.getPressure().MaxSetPressure;
10657ae0e2c9SDimitry Andric   for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
1066f785676fSDimitry Andric     unsigned Limit = RegClassInfo->getRegPressureSetLimit(i);
1067f785676fSDimitry Andric     if (RegionPressure[i] > Limit) {
10684ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << TRI->getRegPressureSetName(i) << " Limit " << Limit
10693861d79fSDimitry Andric                         << " Actual " << RegionPressure[i] << "\n");
1070f785676fSDimitry Andric       RegionCriticalPSets.push_back(PressureChange(i));
1071f785676fSDimitry Andric     }
10727ae0e2c9SDimitry Andric   }
10734ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Excess PSets: ";
10744ba319b5SDimitry Andric              for (const PressureChange &RCPS
10754ba319b5SDimitry Andric                   : RegionCriticalPSets) dbgs()
10764ba319b5SDimitry Andric              << TRI->getRegPressureSetName(RCPS.getPSet()) << " ";
10777ae0e2c9SDimitry Andric              dbgs() << "\n");
10787ae0e2c9SDimitry Andric }
10797ae0e2c9SDimitry Andric 
108091bc56edSDimitry Andric void ScheduleDAGMILive::
updateScheduledPressure(const SUnit * SU,const std::vector<unsigned> & NewMaxPressure)1081f785676fSDimitry Andric updateScheduledPressure(const SUnit *SU,
1082f785676fSDimitry Andric                         const std::vector<unsigned> &NewMaxPressure) {
1083f785676fSDimitry Andric   const PressureDiff &PDiff = getPressureDiff(SU);
1084f785676fSDimitry Andric   unsigned CritIdx = 0, CritEnd = RegionCriticalPSets.size();
1085edd7eaddSDimitry Andric   for (const PressureChange &PC : PDiff) {
1086edd7eaddSDimitry Andric     if (!PC.isValid())
1087f785676fSDimitry Andric       break;
1088edd7eaddSDimitry Andric     unsigned ID = PC.getPSet();
1089f785676fSDimitry Andric     while (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() < ID)
1090f785676fSDimitry Andric       ++CritIdx;
1091f785676fSDimitry Andric     if (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() == ID) {
1092f785676fSDimitry Andric       if ((int)NewMaxPressure[ID] > RegionCriticalPSets[CritIdx].getUnitInc()
10937a7e6055SDimitry Andric           && NewMaxPressure[ID] <= (unsigned)std::numeric_limits<int16_t>::max())
1094f785676fSDimitry Andric         RegionCriticalPSets[CritIdx].setUnitInc(NewMaxPressure[ID]);
10957ae0e2c9SDimitry Andric     }
1096f785676fSDimitry Andric     unsigned Limit = RegClassInfo->getRegPressureSetLimit(ID);
1097f785676fSDimitry Andric     if (NewMaxPressure[ID] >= Limit - 2) {
10984ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "  " << TRI->getRegPressureSetName(ID) << ": "
1099ff0cc061SDimitry Andric                         << NewMaxPressure[ID]
11004ba319b5SDimitry Andric                         << ((NewMaxPressure[ID] > Limit) ? " > " : " <= ")
11014ba319b5SDimitry Andric                         << Limit << "(+ " << BotRPTracker.getLiveThru()[ID]
11024ba319b5SDimitry Andric                         << " livethru)\n");
1103284c1978SDimitry Andric     }
1104f785676fSDimitry Andric   }
1105f785676fSDimitry Andric }
1106f785676fSDimitry Andric 
1107f785676fSDimitry Andric /// Update the PressureDiff array for liveness after scheduling this
1108f785676fSDimitry Andric /// instruction.
updatePressureDiffs(ArrayRef<RegisterMaskPair> LiveUses)11093ca95b02SDimitry Andric void ScheduleDAGMILive::updatePressureDiffs(
11103ca95b02SDimitry Andric     ArrayRef<RegisterMaskPair> LiveUses) {
11113ca95b02SDimitry Andric   for (const RegisterMaskPair &P : LiveUses) {
11123ca95b02SDimitry Andric     unsigned Reg = P.RegUnit;
1113f785676fSDimitry Andric     /// FIXME: Currently assuming single-use physregs.
1114f785676fSDimitry Andric     if (!TRI->isVirtualRegister(Reg))
1115f785676fSDimitry Andric       continue;
1116f785676fSDimitry Andric 
11173ca95b02SDimitry Andric     if (ShouldTrackLaneMasks) {
11183ca95b02SDimitry Andric       // If the register has just become live then other uses won't change
11193ca95b02SDimitry Andric       // this fact anymore => decrement pressure.
11203ca95b02SDimitry Andric       // If the register has just become dead then other uses make it come
11213ca95b02SDimitry Andric       // back to life => increment pressure.
1122d88c1a5aSDimitry Andric       bool Decrement = P.LaneMask.any();
11233ca95b02SDimitry Andric 
11243ca95b02SDimitry Andric       for (const VReg2SUnit &V2SU
11253ca95b02SDimitry Andric            : make_range(VRegUses.find(Reg), VRegUses.end())) {
11263ca95b02SDimitry Andric         SUnit &SU = *V2SU.SU;
11273ca95b02SDimitry Andric         if (SU.isScheduled || &SU == &ExitSU)
11283ca95b02SDimitry Andric           continue;
11293ca95b02SDimitry Andric 
11303ca95b02SDimitry Andric         PressureDiff &PDiff = getPressureDiff(&SU);
11313ca95b02SDimitry Andric         PDiff.addPressureChange(Reg, Decrement, &MRI);
11324ba319b5SDimitry Andric         LLVM_DEBUG(dbgs() << "  UpdateRegP: SU(" << SU.NodeNum << ") "
11334ba319b5SDimitry Andric                           << printReg(Reg, TRI) << ':'
11344ba319b5SDimitry Andric                           << PrintLaneMask(P.LaneMask) << ' ' << *SU.getInstr();
11354ba319b5SDimitry Andric                    dbgs() << "              to "; PDiff.dump(*TRI););
11363ca95b02SDimitry Andric       }
11373ca95b02SDimitry Andric     } else {
1138d88c1a5aSDimitry Andric       assert(P.LaneMask.any());
11394ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "  LiveReg: " << printVRegOrUnit(Reg, TRI) << "\n");
1140f785676fSDimitry Andric       // This may be called before CurrentBottom has been initialized. However,
1141f785676fSDimitry Andric       // BotRPTracker must have a valid position. We want the value live into the
1142f785676fSDimitry Andric       // instruction or live out of the block, so ask for the previous
1143f785676fSDimitry Andric       // instruction's live-out.
1144f785676fSDimitry Andric       const LiveInterval &LI = LIS->getInterval(Reg);
1145f785676fSDimitry Andric       VNInfo *VNI;
1146f785676fSDimitry Andric       MachineBasicBlock::const_iterator I =
1147f785676fSDimitry Andric         nextIfDebug(BotRPTracker.getPos(), BB->end());
1148f785676fSDimitry Andric       if (I == BB->end())
1149f785676fSDimitry Andric         VNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
1150f785676fSDimitry Andric       else {
11513ca95b02SDimitry Andric         LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(*I));
1152f785676fSDimitry Andric         VNI = LRQ.valueIn();
1153f785676fSDimitry Andric       }
1154f785676fSDimitry Andric       // RegisterPressureTracker guarantees that readsReg is true for LiveUses.
1155f785676fSDimitry Andric       assert(VNI && "No live value at use.");
11567d523365SDimitry Andric       for (const VReg2SUnit &V2SU
11577d523365SDimitry Andric            : make_range(VRegUses.find(Reg), VRegUses.end())) {
11587d523365SDimitry Andric         SUnit *SU = V2SU.SU;
11593ca95b02SDimitry Andric         // If this use comes before the reaching def, it cannot be a last use,
11603ca95b02SDimitry Andric         // so decrease its pressure change.
1161f785676fSDimitry Andric         if (!SU->isScheduled && SU != &ExitSU) {
11623ca95b02SDimitry Andric           LiveQueryResult LRQ =
11633ca95b02SDimitry Andric               LI.Query(LIS->getInstructionIndex(*SU->getInstr()));
11647d523365SDimitry Andric           if (LRQ.valueIn() == VNI) {
11657d523365SDimitry Andric             PressureDiff &PDiff = getPressureDiff(SU);
11667d523365SDimitry Andric             PDiff.addPressureChange(Reg, true, &MRI);
11674ba319b5SDimitry Andric             LLVM_DEBUG(dbgs() << "  UpdateRegP: SU(" << SU->NodeNum << ") "
11687d523365SDimitry Andric                               << *SU->getInstr();
11694ba319b5SDimitry Andric                        dbgs() << "              to "; PDiff.dump(*TRI););
11707d523365SDimitry Andric           }
1171f785676fSDimitry Andric         }
1172f785676fSDimitry Andric       }
1173f785676fSDimitry Andric     }
11747ae0e2c9SDimitry Andric   }
11753ca95b02SDimitry Andric }
11767ae0e2c9SDimitry Andric 
dump() const1177*b5893f02SDimitry Andric void ScheduleDAGMILive::dump() const {
1178*b5893f02SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1179*b5893f02SDimitry Andric   if (EntrySU.getInstr() != nullptr)
1180*b5893f02SDimitry Andric     dumpNodeAll(EntrySU);
1181*b5893f02SDimitry Andric   for (const SUnit &SU : SUnits) {
1182*b5893f02SDimitry Andric     dumpNodeAll(SU);
1183*b5893f02SDimitry Andric     if (ShouldTrackPressure) {
1184*b5893f02SDimitry Andric       dbgs() << "  Pressure Diff      : ";
1185*b5893f02SDimitry Andric       getPressureDiff(&SU).dump(*TRI);
1186*b5893f02SDimitry Andric     }
1187*b5893f02SDimitry Andric     dbgs() << "  Single Issue       : ";
1188*b5893f02SDimitry Andric     if (SchedModel.mustBeginGroup(SU.getInstr()) &&
1189*b5893f02SDimitry Andric         SchedModel.mustEndGroup(SU.getInstr()))
1190*b5893f02SDimitry Andric       dbgs() << "true;";
1191*b5893f02SDimitry Andric     else
1192*b5893f02SDimitry Andric       dbgs() << "false;";
1193*b5893f02SDimitry Andric     dbgs() << '\n';
1194*b5893f02SDimitry Andric   }
1195*b5893f02SDimitry Andric   if (ExitSU.getInstr() != nullptr)
1196*b5893f02SDimitry Andric     dumpNodeAll(ExitSU);
1197*b5893f02SDimitry Andric #endif
1198*b5893f02SDimitry Andric }
1199*b5893f02SDimitry Andric 
12003861d79fSDimitry Andric /// schedule - Called back from MachineScheduler::runOnMachineFunction
12013861d79fSDimitry Andric /// after setting up the current scheduling region. [RegionBegin, RegionEnd)
12023861d79fSDimitry Andric /// only includes instructions that have DAG nodes, not scheduling boundaries.
12033861d79fSDimitry Andric ///
12043861d79fSDimitry Andric /// This is a skeletal driver, with all the functionality pushed into helpers,
12057d523365SDimitry Andric /// so that it can be easily extended by experimental schedulers. Generally,
12063861d79fSDimitry Andric /// implementing MachineSchedStrategy should be sufficient to implement a new
12073861d79fSDimitry Andric /// scheduling algorithm. However, if a scheduler further subclasses
120891bc56edSDimitry Andric /// ScheduleDAGMILive then it will want to override this virtual method in order
120991bc56edSDimitry Andric /// to update any specialized state.
schedule()121091bc56edSDimitry Andric void ScheduleDAGMILive::schedule() {
12114ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "ScheduleDAGMILive::schedule starting\n");
12124ba319b5SDimitry Andric   LLVM_DEBUG(SchedImpl->dumpPolicy());
12133861d79fSDimitry Andric   buildDAGWithRegPressure();
12143861d79fSDimitry Andric 
1215139f7f9bSDimitry Andric   Topo.InitDAGTopologicalSorting();
1216139f7f9bSDimitry Andric 
12173861d79fSDimitry Andric   postprocessDAG();
12183861d79fSDimitry Andric 
1219139f7f9bSDimitry Andric   SmallVector<SUnit*, 8> TopRoots, BotRoots;
1220139f7f9bSDimitry Andric   findRootsAndBiasEdges(TopRoots, BotRoots);
1221139f7f9bSDimitry Andric 
1222139f7f9bSDimitry Andric   // Initialize the strategy before modifying the DAG.
1223139f7f9bSDimitry Andric   // This may initialize a DFSResult to be used for queue priority.
1224139f7f9bSDimitry Andric   SchedImpl->initialize(this);
1225139f7f9bSDimitry Andric 
1226*b5893f02SDimitry Andric   LLVM_DEBUG(dump());
1227*b5893f02SDimitry Andric   if (PrintDAGs) dump();
12283861d79fSDimitry Andric   if (ViewMISchedDAGs) viewGraph();
12293861d79fSDimitry Andric 
1230139f7f9bSDimitry Andric   // Initialize ready queues now that the DAG and priority data are finalized.
1231139f7f9bSDimitry Andric   initQueues(TopRoots, BotRoots);
12323861d79fSDimitry Andric 
12333861d79fSDimitry Andric   bool IsTopNode = false;
12347d523365SDimitry Andric   while (true) {
12354ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "** ScheduleDAGMILive::schedule picking next node\n");
12367d523365SDimitry Andric     SUnit *SU = SchedImpl->pickNode(IsTopNode);
12377d523365SDimitry Andric     if (!SU) break;
12387d523365SDimitry Andric 
12393861d79fSDimitry Andric     assert(!SU->isScheduled && "Node already scheduled");
12403861d79fSDimitry Andric     if (!checkSchedLimit())
12413861d79fSDimitry Andric       break;
12423861d79fSDimitry Andric 
12433861d79fSDimitry Andric     scheduleMI(SU, IsTopNode);
12443861d79fSDimitry Andric 
124591bc56edSDimitry Andric     if (DFSResult) {
124691bc56edSDimitry Andric       unsigned SubtreeID = DFSResult->getSubtreeID(SU);
124791bc56edSDimitry Andric       if (!ScheduledTrees.test(SubtreeID)) {
124891bc56edSDimitry Andric         ScheduledTrees.set(SubtreeID);
124991bc56edSDimitry Andric         DFSResult->scheduleTree(SubtreeID);
125091bc56edSDimitry Andric         SchedImpl->scheduleTree(SubtreeID);
125191bc56edSDimitry Andric       }
125291bc56edSDimitry Andric     }
125391bc56edSDimitry Andric 
125491bc56edSDimitry Andric     // Notify the scheduling strategy after updating the DAG.
125591bc56edSDimitry Andric     SchedImpl->schedNode(SU, IsTopNode);
1256ff0cc061SDimitry Andric 
1257ff0cc061SDimitry Andric     updateQueues(SU, IsTopNode);
12583861d79fSDimitry Andric   }
12593861d79fSDimitry Andric   assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
12603861d79fSDimitry Andric 
12613861d79fSDimitry Andric   placeDebugValues();
12623861d79fSDimitry Andric 
12634ba319b5SDimitry Andric   LLVM_DEBUG({
12642cab237bSDimitry Andric     dbgs() << "*** Final schedule for "
12652cab237bSDimitry Andric            << printMBBReference(*begin()->getParent()) << " ***\n";
12663861d79fSDimitry Andric     dumpSchedule();
12673861d79fSDimitry Andric     dbgs() << '\n';
12683861d79fSDimitry Andric   });
12693861d79fSDimitry Andric }
12703861d79fSDimitry Andric 
12713861d79fSDimitry Andric /// Build the DAG and setup three register pressure trackers.
buildDAGWithRegPressure()127291bc56edSDimitry Andric void ScheduleDAGMILive::buildDAGWithRegPressure() {
1273f785676fSDimitry Andric   if (!ShouldTrackPressure) {
1274f785676fSDimitry Andric     RPTracker.reset();
1275f785676fSDimitry Andric     RegionCriticalPSets.clear();
1276f785676fSDimitry Andric     buildSchedGraph(AA);
1277f785676fSDimitry Andric     return;
1278f785676fSDimitry Andric   }
1279f785676fSDimitry Andric 
12803861d79fSDimitry Andric   // Initialize the register pressure tracker used by buildSchedGraph.
1281f785676fSDimitry Andric   RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
12823ca95b02SDimitry Andric                  ShouldTrackLaneMasks, /*TrackUntiedDefs=*/true);
12833861d79fSDimitry Andric 
12843861d79fSDimitry Andric   // Account for liveness generate by the region boundary.
12853861d79fSDimitry Andric   if (LiveRegionEnd != RegionEnd)
12863861d79fSDimitry Andric     RPTracker.recede();
12873861d79fSDimitry Andric 
12883861d79fSDimitry Andric   // Build the DAG, and compute current register pressure.
12893ca95b02SDimitry Andric   buildSchedGraph(AA, &RPTracker, &SUPressureDiffs, LIS, ShouldTrackLaneMasks);
12903861d79fSDimitry Andric 
12913861d79fSDimitry Andric   // Initialize top/bottom trackers after computing region pressure.
12923861d79fSDimitry Andric   initRegPressure();
12933861d79fSDimitry Andric }
12943861d79fSDimitry Andric 
computeDFSResult()129591bc56edSDimitry Andric void ScheduleDAGMILive::computeDFSResult() {
1296139f7f9bSDimitry Andric   if (!DFSResult)
1297139f7f9bSDimitry Andric     DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize);
1298139f7f9bSDimitry Andric   DFSResult->clear();
1299139f7f9bSDimitry Andric   ScheduledTrees.clear();
1300139f7f9bSDimitry Andric   DFSResult->resize(SUnits.size());
1301139f7f9bSDimitry Andric   DFSResult->compute(SUnits);
1302139f7f9bSDimitry Andric   ScheduledTrees.resize(DFSResult->getNumSubtrees());
1303139f7f9bSDimitry Andric }
13047ae0e2c9SDimitry Andric 
1305f785676fSDimitry Andric /// Compute the max cyclic critical path through the DAG. The scheduling DAG
1306f785676fSDimitry Andric /// only provides the critical path for single block loops. To handle loops that
1307f785676fSDimitry Andric /// span blocks, we could use the vreg path latencies provided by
1308f785676fSDimitry Andric /// MachineTraceMetrics instead. However, MachineTraceMetrics is not currently
1309f785676fSDimitry Andric /// available for use in the scheduler.
1310f785676fSDimitry Andric ///
1311f785676fSDimitry Andric /// The cyclic path estimation identifies a def-use pair that crosses the back
1312f785676fSDimitry Andric /// edge and considers the depth and height of the nodes. For example, consider
1313f785676fSDimitry Andric /// the following instruction sequence where each instruction has unit latency
1314f785676fSDimitry Andric /// and defines an epomymous virtual register:
1315f785676fSDimitry Andric ///
1316f785676fSDimitry Andric /// a->b(a,c)->c(b)->d(c)->exit
1317f785676fSDimitry Andric ///
1318f785676fSDimitry Andric /// The cyclic critical path is a two cycles: b->c->b
1319f785676fSDimitry Andric /// The acyclic critical path is four cycles: a->b->c->d->exit
1320f785676fSDimitry Andric /// LiveOutHeight = height(c) = len(c->d->exit) = 2
1321f785676fSDimitry Andric /// LiveOutDepth = depth(c) + 1 = len(a->b->c) + 1 = 3
1322f785676fSDimitry Andric /// LiveInHeight = height(b) + 1 = len(b->c->d->exit) + 1 = 4
1323f785676fSDimitry Andric /// LiveInDepth = depth(b) = len(a->b) = 1
1324f785676fSDimitry Andric ///
1325f785676fSDimitry Andric /// LiveOutDepth - LiveInDepth = 3 - 1 = 2
1326f785676fSDimitry Andric /// LiveInHeight - LiveOutHeight = 4 - 2 = 2
1327f785676fSDimitry Andric /// CyclicCriticalPath = min(2, 2) = 2
132891bc56edSDimitry Andric ///
132991bc56edSDimitry Andric /// This could be relevant to PostRA scheduling, but is currently implemented
133091bc56edSDimitry Andric /// assuming LiveIntervals.
computeCyclicCriticalPath()133191bc56edSDimitry Andric unsigned ScheduleDAGMILive::computeCyclicCriticalPath() {
1332f785676fSDimitry Andric   // This only applies to single block loop.
1333f785676fSDimitry Andric   if (!BB->isSuccessor(BB))
1334f785676fSDimitry Andric     return 0;
1335f785676fSDimitry Andric 
1336f785676fSDimitry Andric   unsigned MaxCyclicLatency = 0;
1337f785676fSDimitry Andric   // Visit each live out vreg def to find def/use pairs that cross iterations.
13383ca95b02SDimitry Andric   for (const RegisterMaskPair &P : RPTracker.getPressure().LiveOutRegs) {
13393ca95b02SDimitry Andric     unsigned Reg = P.RegUnit;
1340f785676fSDimitry Andric     if (!TRI->isVirtualRegister(Reg))
1341f785676fSDimitry Andric         continue;
1342f785676fSDimitry Andric     const LiveInterval &LI = LIS->getInterval(Reg);
1343f785676fSDimitry Andric     const VNInfo *DefVNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
1344f785676fSDimitry Andric     if (!DefVNI)
1345f785676fSDimitry Andric       continue;
1346f785676fSDimitry Andric 
1347f785676fSDimitry Andric     MachineInstr *DefMI = LIS->getInstructionFromIndex(DefVNI->def);
1348f785676fSDimitry Andric     const SUnit *DefSU = getSUnit(DefMI);
1349f785676fSDimitry Andric     if (!DefSU)
1350f785676fSDimitry Andric       continue;
1351f785676fSDimitry Andric 
1352f785676fSDimitry Andric     unsigned LiveOutHeight = DefSU->getHeight();
1353f785676fSDimitry Andric     unsigned LiveOutDepth = DefSU->getDepth() + DefSU->Latency;
1354f785676fSDimitry Andric     // Visit all local users of the vreg def.
13557d523365SDimitry Andric     for (const VReg2SUnit &V2SU
13567d523365SDimitry Andric          : make_range(VRegUses.find(Reg), VRegUses.end())) {
13577d523365SDimitry Andric       SUnit *SU = V2SU.SU;
13587d523365SDimitry Andric       if (SU == &ExitSU)
1359f785676fSDimitry Andric         continue;
1360f785676fSDimitry Andric 
1361f785676fSDimitry Andric       // Only consider uses of the phi.
13623ca95b02SDimitry Andric       LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(*SU->getInstr()));
1363f785676fSDimitry Andric       if (!LRQ.valueIn()->isPHIDef())
1364f785676fSDimitry Andric         continue;
1365f785676fSDimitry Andric 
1366f785676fSDimitry Andric       // Assume that a path spanning two iterations is a cycle, which could
1367f785676fSDimitry Andric       // overestimate in strange cases. This allows cyclic latency to be
1368f785676fSDimitry Andric       // estimated as the minimum slack of the vreg's depth or height.
1369f785676fSDimitry Andric       unsigned CyclicLatency = 0;
13707d523365SDimitry Andric       if (LiveOutDepth > SU->getDepth())
13717d523365SDimitry Andric         CyclicLatency = LiveOutDepth - SU->getDepth();
1372f785676fSDimitry Andric 
13737d523365SDimitry Andric       unsigned LiveInHeight = SU->getHeight() + DefSU->Latency;
1374f785676fSDimitry Andric       if (LiveInHeight > LiveOutHeight) {
1375f785676fSDimitry Andric         if (LiveInHeight - LiveOutHeight < CyclicLatency)
1376f785676fSDimitry Andric           CyclicLatency = LiveInHeight - LiveOutHeight;
13773ca95b02SDimitry Andric       } else
1378f785676fSDimitry Andric         CyclicLatency = 0;
1379f785676fSDimitry Andric 
13804ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "Cyclic Path: SU(" << DefSU->NodeNum << ") -> SU("
13817d523365SDimitry Andric                         << SU->NodeNum << ") = " << CyclicLatency << "c\n");
1382f785676fSDimitry Andric       if (CyclicLatency > MaxCyclicLatency)
1383f785676fSDimitry Andric         MaxCyclicLatency = CyclicLatency;
1384f785676fSDimitry Andric     }
1385f785676fSDimitry Andric   }
13864ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Cyclic Critical Path: " << MaxCyclicLatency << "c\n");
1387f785676fSDimitry Andric   return MaxCyclicLatency;
1388f785676fSDimitry Andric }
1389f785676fSDimitry Andric 
13903ca95b02SDimitry Andric /// Release ExitSU predecessors and setup scheduler queues. Re-position
13913ca95b02SDimitry Andric /// the Top RP tracker in case the region beginning has changed.
initQueues(ArrayRef<SUnit * > TopRoots,ArrayRef<SUnit * > BotRoots)13923ca95b02SDimitry Andric void ScheduleDAGMILive::initQueues(ArrayRef<SUnit*> TopRoots,
13933ca95b02SDimitry Andric                                    ArrayRef<SUnit*> BotRoots) {
13943ca95b02SDimitry Andric   ScheduleDAGMI::initQueues(TopRoots, BotRoots);
13953ca95b02SDimitry Andric   if (ShouldTrackPressure) {
13963ca95b02SDimitry Andric     assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
13973ca95b02SDimitry Andric     TopRPTracker.setPos(CurrentTop);
13983ca95b02SDimitry Andric   }
13993ca95b02SDimitry Andric }
14003ca95b02SDimitry Andric 
14013861d79fSDimitry Andric /// Move an instruction and update register pressure.
scheduleMI(SUnit * SU,bool IsTopNode)140291bc56edSDimitry Andric void ScheduleDAGMILive::scheduleMI(SUnit *SU, bool IsTopNode) {
1403dff0c46cSDimitry Andric   // Move the instruction to its new location in the instruction stream.
1404dff0c46cSDimitry Andric   MachineInstr *MI = SU->getInstr();
1405dff0c46cSDimitry Andric 
1406dff0c46cSDimitry Andric   if (IsTopNode) {
1407dff0c46cSDimitry Andric     assert(SU->isTopReady() && "node still has unscheduled dependencies");
1408dff0c46cSDimitry Andric     if (&*CurrentTop == MI)
14097ae0e2c9SDimitry Andric       CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
14107ae0e2c9SDimitry Andric     else {
1411dff0c46cSDimitry Andric       moveInstruction(MI, CurrentTop);
14127ae0e2c9SDimitry Andric       TopRPTracker.setPos(MI);
14137ae0e2c9SDimitry Andric     }
14147ae0e2c9SDimitry Andric 
1415f785676fSDimitry Andric     if (ShouldTrackPressure) {
14167ae0e2c9SDimitry Andric       // Update top scheduled pressure.
14173ca95b02SDimitry Andric       RegisterOperands RegOpers;
14183ca95b02SDimitry Andric       RegOpers.collect(*MI, *TRI, MRI, ShouldTrackLaneMasks, false);
14193ca95b02SDimitry Andric       if (ShouldTrackLaneMasks) {
14203ca95b02SDimitry Andric         // Adjust liveness and add missing dead+read-undef flags.
14213ca95b02SDimitry Andric         SlotIndex SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot();
14223ca95b02SDimitry Andric         RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx, MI);
14233ca95b02SDimitry Andric       } else {
14243ca95b02SDimitry Andric         // Adjust for missing dead-def flags.
14253ca95b02SDimitry Andric         RegOpers.detectDeadDefs(*MI, *LIS);
14263ca95b02SDimitry Andric       }
14273ca95b02SDimitry Andric 
14283ca95b02SDimitry Andric       TopRPTracker.advance(RegOpers);
14297ae0e2c9SDimitry Andric       assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
14304ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "Top Pressure:\n"; dumpRegSetPressure(
14314ba319b5SDimitry Andric                      TopRPTracker.getRegSetPressureAtPos(), TRI););
14327d523365SDimitry Andric 
1433f785676fSDimitry Andric       updateScheduledPressure(SU, TopRPTracker.getPressure().MaxSetPressure);
1434f785676fSDimitry Andric     }
14353ca95b02SDimitry Andric   } else {
1436dff0c46cSDimitry Andric     assert(SU->isBottomReady() && "node still has unscheduled dependencies");
14377ae0e2c9SDimitry Andric     MachineBasicBlock::iterator priorII =
14387ae0e2c9SDimitry Andric       priorNonDebug(CurrentBottom, CurrentTop);
14397ae0e2c9SDimitry Andric     if (&*priorII == MI)
14407ae0e2c9SDimitry Andric       CurrentBottom = priorII;
1441dff0c46cSDimitry Andric     else {
14427ae0e2c9SDimitry Andric       if (&*CurrentTop == MI) {
14437ae0e2c9SDimitry Andric         CurrentTop = nextIfDebug(++CurrentTop, priorII);
14447ae0e2c9SDimitry Andric         TopRPTracker.setPos(CurrentTop);
14457ae0e2c9SDimitry Andric       }
1446dff0c46cSDimitry Andric       moveInstruction(MI, CurrentBottom);
1447dff0c46cSDimitry Andric       CurrentBottom = MI;
14484ba319b5SDimitry Andric       BotRPTracker.setPos(CurrentBottom);
1449dff0c46cSDimitry Andric     }
1450f785676fSDimitry Andric     if (ShouldTrackPressure) {
14513ca95b02SDimitry Andric       RegisterOperands RegOpers;
14523ca95b02SDimitry Andric       RegOpers.collect(*MI, *TRI, MRI, ShouldTrackLaneMasks, false);
14533ca95b02SDimitry Andric       if (ShouldTrackLaneMasks) {
14543ca95b02SDimitry Andric         // Adjust liveness and add missing dead+read-undef flags.
14553ca95b02SDimitry Andric         SlotIndex SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot();
14563ca95b02SDimitry Andric         RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx, MI);
14573ca95b02SDimitry Andric       } else {
14583ca95b02SDimitry Andric         // Adjust for missing dead-def flags.
14593ca95b02SDimitry Andric         RegOpers.detectDeadDefs(*MI, *LIS);
14603ca95b02SDimitry Andric       }
14613ca95b02SDimitry Andric 
14622cab237bSDimitry Andric       if (BotRPTracker.getPos() != CurrentBottom)
14633ca95b02SDimitry Andric         BotRPTracker.recedeSkipDebugValues();
14643ca95b02SDimitry Andric       SmallVector<RegisterMaskPair, 8> LiveUses;
14653ca95b02SDimitry Andric       BotRPTracker.recede(RegOpers, &LiveUses);
14667ae0e2c9SDimitry Andric       assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
14674ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "Bottom Pressure:\n"; dumpRegSetPressure(
14684ba319b5SDimitry Andric                      BotRPTracker.getRegSetPressureAtPos(), TRI););
14697d523365SDimitry Andric 
1470f785676fSDimitry Andric       updateScheduledPressure(SU, BotRPTracker.getPressure().MaxSetPressure);
1471f785676fSDimitry Andric       updatePressureDiffs(LiveUses);
1472f785676fSDimitry Andric     }
14733861d79fSDimitry Andric   }
14743861d79fSDimitry Andric }
14757ae0e2c9SDimitry Andric 
1476dff0c46cSDimitry Andric //===----------------------------------------------------------------------===//
14773ca95b02SDimitry Andric // BaseMemOpClusterMutation - DAG post-processing to cluster loads or stores.
1478139f7f9bSDimitry Andric //===----------------------------------------------------------------------===//
1479139f7f9bSDimitry Andric 
1480139f7f9bSDimitry Andric namespace {
14817a7e6055SDimitry Andric 
14824ba319b5SDimitry Andric /// Post-process the DAG to create cluster edges between neighboring
14833ca95b02SDimitry Andric /// loads or between neighboring stores.
14843ca95b02SDimitry Andric class BaseMemOpClusterMutation : public ScheduleDAGMutation {
14853ca95b02SDimitry Andric   struct MemOpInfo {
1486139f7f9bSDimitry Andric     SUnit *SU;
1487*b5893f02SDimitry Andric     MachineOperand *BaseOp;
14883ca95b02SDimitry Andric     int64_t Offset;
14897a7e6055SDimitry Andric 
MemOpInfo__anon1997d06d0311::BaseMemOpClusterMutation::MemOpInfo1490*b5893f02SDimitry Andric     MemOpInfo(SUnit *su, MachineOperand *Op, int64_t ofs)
1491*b5893f02SDimitry Andric         : SU(su), BaseOp(Op), Offset(ofs) {}
149291bc56edSDimitry Andric 
operator <__anon1997d06d0311::BaseMemOpClusterMutation::MemOpInfo14933ca95b02SDimitry Andric     bool operator<(const MemOpInfo &RHS) const {
1494*b5893f02SDimitry Andric       if (BaseOp->getType() != RHS.BaseOp->getType())
1495*b5893f02SDimitry Andric         return BaseOp->getType() < RHS.BaseOp->getType();
1496*b5893f02SDimitry Andric 
1497*b5893f02SDimitry Andric       if (BaseOp->isReg())
1498*b5893f02SDimitry Andric         return std::make_tuple(BaseOp->getReg(), Offset, SU->NodeNum) <
1499*b5893f02SDimitry Andric                std::make_tuple(RHS.BaseOp->getReg(), RHS.Offset,
1500*b5893f02SDimitry Andric                                RHS.SU->NodeNum);
1501*b5893f02SDimitry Andric       if (BaseOp->isFI()) {
1502*b5893f02SDimitry Andric         const MachineFunction &MF =
1503*b5893f02SDimitry Andric             *BaseOp->getParent()->getParent()->getParent();
1504*b5893f02SDimitry Andric         const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
1505*b5893f02SDimitry Andric         bool StackGrowsDown = TFI.getStackGrowthDirection() ==
1506*b5893f02SDimitry Andric                               TargetFrameLowering::StackGrowsDown;
1507*b5893f02SDimitry Andric         // Can't use tuple comparison here since we might need to use a
1508*b5893f02SDimitry Andric         // different order when the stack grows down.
1509*b5893f02SDimitry Andric         if (BaseOp->getIndex() != RHS.BaseOp->getIndex())
1510*b5893f02SDimitry Andric           return StackGrowsDown ? BaseOp->getIndex() > RHS.BaseOp->getIndex()
1511*b5893f02SDimitry Andric                                 : BaseOp->getIndex() < RHS.BaseOp->getIndex();
1512*b5893f02SDimitry Andric 
1513*b5893f02SDimitry Andric         if (Offset != RHS.Offset)
1514*b5893f02SDimitry Andric           return StackGrowsDown ? Offset > RHS.Offset : Offset < RHS.Offset;
1515*b5893f02SDimitry Andric 
1516*b5893f02SDimitry Andric         return SU->NodeNum < RHS.SU->NodeNum;
1517*b5893f02SDimitry Andric       }
1518*b5893f02SDimitry Andric 
1519*b5893f02SDimitry Andric       llvm_unreachable("MemOpClusterMutation only supports register or frame "
1520*b5893f02SDimitry Andric                        "index bases.");
152191bc56edSDimitry Andric     }
1522139f7f9bSDimitry Andric   };
1523139f7f9bSDimitry Andric 
1524139f7f9bSDimitry Andric   const TargetInstrInfo *TII;
1525139f7f9bSDimitry Andric   const TargetRegisterInfo *TRI;
15263ca95b02SDimitry Andric   bool IsLoad;
1527139f7f9bSDimitry Andric 
15283ca95b02SDimitry Andric public:
BaseMemOpClusterMutation(const TargetInstrInfo * tii,const TargetRegisterInfo * tri,bool IsLoad)15293ca95b02SDimitry Andric   BaseMemOpClusterMutation(const TargetInstrInfo *tii,
15303ca95b02SDimitry Andric                            const TargetRegisterInfo *tri, bool IsLoad)
15313ca95b02SDimitry Andric       : TII(tii), TRI(tri), IsLoad(IsLoad) {}
15323ca95b02SDimitry Andric 
15333ca95b02SDimitry Andric   void apply(ScheduleDAGInstrs *DAGInstrs) override;
15343ca95b02SDimitry Andric 
1535139f7f9bSDimitry Andric protected:
15363ca95b02SDimitry Andric   void clusterNeighboringMemOps(ArrayRef<SUnit *> MemOps, ScheduleDAGMI *DAG);
15373ca95b02SDimitry Andric };
15383ca95b02SDimitry Andric 
15393ca95b02SDimitry Andric class StoreClusterMutation : public BaseMemOpClusterMutation {
15403ca95b02SDimitry Andric public:
StoreClusterMutation(const TargetInstrInfo * tii,const TargetRegisterInfo * tri)15413ca95b02SDimitry Andric   StoreClusterMutation(const TargetInstrInfo *tii,
15423ca95b02SDimitry Andric                        const TargetRegisterInfo *tri)
15433ca95b02SDimitry Andric       : BaseMemOpClusterMutation(tii, tri, false) {}
15443ca95b02SDimitry Andric };
15453ca95b02SDimitry Andric 
15463ca95b02SDimitry Andric class LoadClusterMutation : public BaseMemOpClusterMutation {
15473ca95b02SDimitry Andric public:
LoadClusterMutation(const TargetInstrInfo * tii,const TargetRegisterInfo * tri)15483ca95b02SDimitry Andric   LoadClusterMutation(const TargetInstrInfo *tii, const TargetRegisterInfo *tri)
15493ca95b02SDimitry Andric       : BaseMemOpClusterMutation(tii, tri, true) {}
1550139f7f9bSDimitry Andric };
15517a7e6055SDimitry Andric 
15527a7e6055SDimitry Andric } // end anonymous namespace
1553139f7f9bSDimitry Andric 
1554d88c1a5aSDimitry Andric namespace llvm {
1555d88c1a5aSDimitry Andric 
1556d88c1a5aSDimitry Andric std::unique_ptr<ScheduleDAGMutation>
createLoadClusterDAGMutation(const TargetInstrInfo * TII,const TargetRegisterInfo * TRI)1557d88c1a5aSDimitry Andric createLoadClusterDAGMutation(const TargetInstrInfo *TII,
1558d88c1a5aSDimitry Andric                              const TargetRegisterInfo *TRI) {
15597a7e6055SDimitry Andric   return EnableMemOpCluster ? llvm::make_unique<LoadClusterMutation>(TII, TRI)
1560d88c1a5aSDimitry Andric                             : nullptr;
1561d88c1a5aSDimitry Andric }
1562d88c1a5aSDimitry Andric 
1563d88c1a5aSDimitry Andric std::unique_ptr<ScheduleDAGMutation>
createStoreClusterDAGMutation(const TargetInstrInfo * TII,const TargetRegisterInfo * TRI)1564d88c1a5aSDimitry Andric createStoreClusterDAGMutation(const TargetInstrInfo *TII,
1565d88c1a5aSDimitry Andric                               const TargetRegisterInfo *TRI) {
15667a7e6055SDimitry Andric   return EnableMemOpCluster ? llvm::make_unique<StoreClusterMutation>(TII, TRI)
1567d88c1a5aSDimitry Andric                             : nullptr;
1568d88c1a5aSDimitry Andric }
1569d88c1a5aSDimitry Andric 
15707a7e6055SDimitry Andric } // end namespace llvm
1571d88c1a5aSDimitry Andric 
clusterNeighboringMemOps(ArrayRef<SUnit * > MemOps,ScheduleDAGMI * DAG)15723ca95b02SDimitry Andric void BaseMemOpClusterMutation::clusterNeighboringMemOps(
15733ca95b02SDimitry Andric     ArrayRef<SUnit *> MemOps, ScheduleDAGMI *DAG) {
15743ca95b02SDimitry Andric   SmallVector<MemOpInfo, 32> MemOpRecords;
1575edd7eaddSDimitry Andric   for (SUnit *SU : MemOps) {
1576*b5893f02SDimitry Andric     MachineOperand *BaseOp;
15773ca95b02SDimitry Andric     int64_t Offset;
1578*b5893f02SDimitry Andric     if (TII->getMemOperandWithOffset(*SU->getInstr(), BaseOp, Offset, TRI))
1579*b5893f02SDimitry Andric       MemOpRecords.push_back(MemOpInfo(SU, BaseOp, Offset));
1580139f7f9bSDimitry Andric   }
15813ca95b02SDimitry Andric   if (MemOpRecords.size() < 2)
1582139f7f9bSDimitry Andric     return;
15833ca95b02SDimitry Andric 
1584*b5893f02SDimitry Andric   llvm::sort(MemOpRecords);
1585139f7f9bSDimitry Andric   unsigned ClusterLength = 1;
15863ca95b02SDimitry Andric   for (unsigned Idx = 0, End = MemOpRecords.size(); Idx < (End - 1); ++Idx) {
15873ca95b02SDimitry Andric     SUnit *SUa = MemOpRecords[Idx].SU;
15883ca95b02SDimitry Andric     SUnit *SUb = MemOpRecords[Idx+1].SU;
1589*b5893f02SDimitry Andric     if (TII->shouldClusterMemOps(*MemOpRecords[Idx].BaseOp,
1590*b5893f02SDimitry Andric                                  *MemOpRecords[Idx + 1].BaseOp,
15913ca95b02SDimitry Andric                                  ClusterLength) &&
15923ca95b02SDimitry Andric         DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
15934ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "Cluster ld/st SU(" << SUa->NodeNum << ") - SU("
1594139f7f9bSDimitry Andric                         << SUb->NodeNum << ")\n");
1595139f7f9bSDimitry Andric       // Copy successor edges from SUa to SUb. Interleaving computation
1596139f7f9bSDimitry Andric       // dependent on SUa can prevent load combining due to register reuse.
1597139f7f9bSDimitry Andric       // Predecessor edges do not need to be copied from SUb to SUa since nearby
1598139f7f9bSDimitry Andric       // loads should have effectively the same inputs.
1599edd7eaddSDimitry Andric       for (const SDep &Succ : SUa->Succs) {
1600edd7eaddSDimitry Andric         if (Succ.getSUnit() == SUb)
1601139f7f9bSDimitry Andric           continue;
16024ba319b5SDimitry Andric         LLVM_DEBUG(dbgs() << "  Copy Succ SU(" << Succ.getSUnit()->NodeNum
16034ba319b5SDimitry Andric                           << ")\n");
1604edd7eaddSDimitry Andric         DAG->addEdge(Succ.getSUnit(), SDep(SUb, SDep::Artificial));
1605139f7f9bSDimitry Andric       }
1606139f7f9bSDimitry Andric       ++ClusterLength;
16073ca95b02SDimitry Andric     } else
1608139f7f9bSDimitry Andric       ClusterLength = 1;
1609139f7f9bSDimitry Andric   }
1610139f7f9bSDimitry Andric }
1611139f7f9bSDimitry Andric 
16124ba319b5SDimitry Andric /// Callback from DAG postProcessing to create cluster edges for loads.
apply(ScheduleDAGInstrs * DAGInstrs)16133ca95b02SDimitry Andric void BaseMemOpClusterMutation::apply(ScheduleDAGInstrs *DAGInstrs) {
16143ca95b02SDimitry Andric   ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs);
16153ca95b02SDimitry Andric 
1616139f7f9bSDimitry Andric   // Map DAG NodeNum to store chain ID.
1617139f7f9bSDimitry Andric   DenseMap<unsigned, unsigned> StoreChainIDs;
16183ca95b02SDimitry Andric   // Map each store chain to a set of dependent MemOps.
1619139f7f9bSDimitry Andric   SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
1620edd7eaddSDimitry Andric   for (SUnit &SU : DAG->SUnits) {
1621edd7eaddSDimitry Andric     if ((IsLoad && !SU.getInstr()->mayLoad()) ||
1622edd7eaddSDimitry Andric         (!IsLoad && !SU.getInstr()->mayStore()))
1623139f7f9bSDimitry Andric       continue;
16243ca95b02SDimitry Andric 
1625139f7f9bSDimitry Andric     unsigned ChainPredID = DAG->SUnits.size();
1626edd7eaddSDimitry Andric     for (const SDep &Pred : SU.Preds) {
1627edd7eaddSDimitry Andric       if (Pred.isCtrl()) {
1628edd7eaddSDimitry Andric         ChainPredID = Pred.getSUnit()->NodeNum;
1629139f7f9bSDimitry Andric         break;
1630139f7f9bSDimitry Andric       }
1631139f7f9bSDimitry Andric     }
1632139f7f9bSDimitry Andric     // Check if this chain-like pred has been seen
16333ca95b02SDimitry Andric     // before. ChainPredID==MaxNodeID at the top of the schedule.
1634139f7f9bSDimitry Andric     unsigned NumChains = StoreChainDependents.size();
1635139f7f9bSDimitry Andric     std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
1636139f7f9bSDimitry Andric       StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
1637139f7f9bSDimitry Andric     if (Result.second)
1638139f7f9bSDimitry Andric       StoreChainDependents.resize(NumChains + 1);
1639edd7eaddSDimitry Andric     StoreChainDependents[Result.first->second].push_back(&SU);
1640139f7f9bSDimitry Andric   }
16413ca95b02SDimitry Andric 
1642139f7f9bSDimitry Andric   // Iterate over the store chains.
1643edd7eaddSDimitry Andric   for (auto &SCD : StoreChainDependents)
1644edd7eaddSDimitry Andric     clusterNeighboringMemOps(SCD, DAG);
1645139f7f9bSDimitry Andric }
1646139f7f9bSDimitry Andric 
1647139f7f9bSDimitry Andric //===----------------------------------------------------------------------===//
1648284c1978SDimitry Andric // CopyConstrain - DAG post-processing to encourage copy elimination.
1649284c1978SDimitry Andric //===----------------------------------------------------------------------===//
1650284c1978SDimitry Andric 
1651284c1978SDimitry Andric namespace {
16527a7e6055SDimitry Andric 
16534ba319b5SDimitry Andric /// Post-process the DAG to create weak edges from all uses of a copy to
1654284c1978SDimitry Andric /// the one use that defines the copy's source vreg, most likely an induction
1655284c1978SDimitry Andric /// variable increment.
1656284c1978SDimitry Andric class CopyConstrain : public ScheduleDAGMutation {
1657284c1978SDimitry Andric   // Transient state.
1658284c1978SDimitry Andric   SlotIndex RegionBeginIdx;
16592cab237bSDimitry Andric 
1660284c1978SDimitry Andric   // RegionEndIdx is the slot index of the last non-debug instruction in the
1661284c1978SDimitry Andric   // scheduling region. So we may have RegionBeginIdx == RegionEndIdx.
1662284c1978SDimitry Andric   SlotIndex RegionEndIdx;
16637a7e6055SDimitry Andric 
1664284c1978SDimitry Andric public:
CopyConstrain(const TargetInstrInfo *,const TargetRegisterInfo *)1665284c1978SDimitry Andric   CopyConstrain(const TargetInstrInfo *, const TargetRegisterInfo *) {}
1666284c1978SDimitry Andric 
16673ca95b02SDimitry Andric   void apply(ScheduleDAGInstrs *DAGInstrs) override;
1668284c1978SDimitry Andric 
1669284c1978SDimitry Andric protected:
167091bc56edSDimitry Andric   void constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG);
1671284c1978SDimitry Andric };
16727a7e6055SDimitry Andric 
16737a7e6055SDimitry Andric } // end anonymous namespace
1674284c1978SDimitry Andric 
1675d88c1a5aSDimitry Andric namespace llvm {
1676d88c1a5aSDimitry Andric 
1677d88c1a5aSDimitry Andric std::unique_ptr<ScheduleDAGMutation>
createCopyConstrainDAGMutation(const TargetInstrInfo * TII,const TargetRegisterInfo * TRI)1678d88c1a5aSDimitry Andric createCopyConstrainDAGMutation(const TargetInstrInfo *TII,
1679d88c1a5aSDimitry Andric                                const TargetRegisterInfo *TRI) {
16807a7e6055SDimitry Andric   return llvm::make_unique<CopyConstrain>(TII, TRI);
1681d88c1a5aSDimitry Andric }
1682d88c1a5aSDimitry Andric 
16837a7e6055SDimitry Andric } // end namespace llvm
1684d88c1a5aSDimitry Andric 
1685284c1978SDimitry Andric /// constrainLocalCopy handles two possibilities:
1686284c1978SDimitry Andric /// 1) Local src:
1687284c1978SDimitry Andric /// I0:     = dst
1688284c1978SDimitry Andric /// I1: src = ...
1689284c1978SDimitry Andric /// I2:     = dst
1690284c1978SDimitry Andric /// I3: dst = src (copy)
1691284c1978SDimitry Andric /// (create pred->succ edges I0->I1, I2->I1)
1692284c1978SDimitry Andric ///
1693284c1978SDimitry Andric /// 2) Local copy:
1694284c1978SDimitry Andric /// I0: dst = src (copy)
1695284c1978SDimitry Andric /// I1:     = dst
1696284c1978SDimitry Andric /// I2: src = ...
1697284c1978SDimitry Andric /// I3:     = dst
1698284c1978SDimitry Andric /// (create pred->succ edges I1->I2, I3->I2)
1699284c1978SDimitry Andric ///
1700284c1978SDimitry Andric /// Although the MachineScheduler is currently constrained to single blocks,
1701284c1978SDimitry Andric /// this algorithm should handle extended blocks. An EBB is a set of
1702284c1978SDimitry Andric /// contiguously numbered blocks such that the previous block in the EBB is
1703284c1978SDimitry Andric /// always the single predecessor.
constrainLocalCopy(SUnit * CopySU,ScheduleDAGMILive * DAG)170491bc56edSDimitry Andric void CopyConstrain::constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG) {
1705284c1978SDimitry Andric   LiveIntervals *LIS = DAG->getLIS();
1706284c1978SDimitry Andric   MachineInstr *Copy = CopySU->getInstr();
1707284c1978SDimitry Andric 
1708284c1978SDimitry Andric   // Check for pure vreg copies.
17093ca95b02SDimitry Andric   const MachineOperand &SrcOp = Copy->getOperand(1);
17103ca95b02SDimitry Andric   unsigned SrcReg = SrcOp.getReg();
17113ca95b02SDimitry Andric   if (!TargetRegisterInfo::isVirtualRegister(SrcReg) || !SrcOp.readsReg())
1712284c1978SDimitry Andric     return;
1713284c1978SDimitry Andric 
17143ca95b02SDimitry Andric   const MachineOperand &DstOp = Copy->getOperand(0);
17153ca95b02SDimitry Andric   unsigned DstReg = DstOp.getReg();
17163ca95b02SDimitry Andric   if (!TargetRegisterInfo::isVirtualRegister(DstReg) || DstOp.isDead())
1717284c1978SDimitry Andric     return;
1718284c1978SDimitry Andric 
1719284c1978SDimitry Andric   // Check if either the dest or source is local. If it's live across a back
1720284c1978SDimitry Andric   // edge, it's not local. Note that if both vregs are live across the back
1721284c1978SDimitry Andric   // edge, we cannot successfully contrain the copy without cyclic scheduling.
1722ff0cc061SDimitry Andric   // If both the copy's source and dest are local live intervals, then we
1723ff0cc061SDimitry Andric   // should treat the dest as the global for the purpose of adding
1724ff0cc061SDimitry Andric   // constraints. This adds edges from source's other uses to the copy.
1725ff0cc061SDimitry Andric   unsigned LocalReg = SrcReg;
1726ff0cc061SDimitry Andric   unsigned GlobalReg = DstReg;
1727284c1978SDimitry Andric   LiveInterval *LocalLI = &LIS->getInterval(LocalReg);
1728284c1978SDimitry Andric   if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx)) {
1729ff0cc061SDimitry Andric     LocalReg = DstReg;
1730ff0cc061SDimitry Andric     GlobalReg = SrcReg;
1731284c1978SDimitry Andric     LocalLI = &LIS->getInterval(LocalReg);
1732284c1978SDimitry Andric     if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx))
1733284c1978SDimitry Andric       return;
1734284c1978SDimitry Andric   }
1735284c1978SDimitry Andric   LiveInterval *GlobalLI = &LIS->getInterval(GlobalReg);
1736284c1978SDimitry Andric 
1737284c1978SDimitry Andric   // Find the global segment after the start of the local LI.
1738284c1978SDimitry Andric   LiveInterval::iterator GlobalSegment = GlobalLI->find(LocalLI->beginIndex());
1739284c1978SDimitry Andric   // If GlobalLI does not overlap LocalLI->start, then a copy directly feeds a
1740284c1978SDimitry Andric   // local live range. We could create edges from other global uses to the local
1741284c1978SDimitry Andric   // start, but the coalescer should have already eliminated these cases, so
1742284c1978SDimitry Andric   // don't bother dealing with it.
1743284c1978SDimitry Andric   if (GlobalSegment == GlobalLI->end())
1744284c1978SDimitry Andric     return;
1745284c1978SDimitry Andric 
1746284c1978SDimitry Andric   // If GlobalSegment is killed at the LocalLI->start, the call to find()
1747284c1978SDimitry Andric   // returned the next global segment. But if GlobalSegment overlaps with
17484ba319b5SDimitry Andric   // LocalLI->start, then advance to the next segment. If a hole in GlobalLI
1749284c1978SDimitry Andric   // exists in LocalLI's vicinity, GlobalSegment will be the end of the hole.
1750284c1978SDimitry Andric   if (GlobalSegment->contains(LocalLI->beginIndex()))
1751284c1978SDimitry Andric     ++GlobalSegment;
1752284c1978SDimitry Andric 
1753284c1978SDimitry Andric   if (GlobalSegment == GlobalLI->end())
1754284c1978SDimitry Andric     return;
1755284c1978SDimitry Andric 
1756284c1978SDimitry Andric   // Check if GlobalLI contains a hole in the vicinity of LocalLI.
1757284c1978SDimitry Andric   if (GlobalSegment != GlobalLI->begin()) {
1758284c1978SDimitry Andric     // Two address defs have no hole.
175991bc56edSDimitry Andric     if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->end,
1760284c1978SDimitry Andric                                GlobalSegment->start)) {
1761284c1978SDimitry Andric       return;
1762284c1978SDimitry Andric     }
1763f785676fSDimitry Andric     // If the prior global segment may be defined by the same two-address
1764f785676fSDimitry Andric     // instruction that also defines LocalLI, then can't make a hole here.
176591bc56edSDimitry Andric     if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->start,
1766f785676fSDimitry Andric                                LocalLI->beginIndex())) {
1767f785676fSDimitry Andric       return;
1768f785676fSDimitry Andric     }
1769284c1978SDimitry Andric     // If GlobalLI has a prior segment, it must be live into the EBB. Otherwise
1770284c1978SDimitry Andric     // it would be a disconnected component in the live range.
177191bc56edSDimitry Andric     assert(std::prev(GlobalSegment)->start < LocalLI->beginIndex() &&
1772284c1978SDimitry Andric            "Disconnected LRG within the scheduling region.");
1773284c1978SDimitry Andric   }
1774284c1978SDimitry Andric   MachineInstr *GlobalDef = LIS->getInstructionFromIndex(GlobalSegment->start);
1775284c1978SDimitry Andric   if (!GlobalDef)
1776284c1978SDimitry Andric     return;
1777284c1978SDimitry Andric 
1778284c1978SDimitry Andric   SUnit *GlobalSU = DAG->getSUnit(GlobalDef);
1779284c1978SDimitry Andric   if (!GlobalSU)
1780284c1978SDimitry Andric     return;
1781284c1978SDimitry Andric 
1782284c1978SDimitry Andric   // GlobalDef is the bottom of the GlobalLI hole. Open the hole by
1783284c1978SDimitry Andric   // constraining the uses of the last local def to precede GlobalDef.
1784284c1978SDimitry Andric   SmallVector<SUnit*,8> LocalUses;
1785284c1978SDimitry Andric   const VNInfo *LastLocalVN = LocalLI->getVNInfoBefore(LocalLI->endIndex());
1786284c1978SDimitry Andric   MachineInstr *LastLocalDef = LIS->getInstructionFromIndex(LastLocalVN->def);
1787284c1978SDimitry Andric   SUnit *LastLocalSU = DAG->getSUnit(LastLocalDef);
1788edd7eaddSDimitry Andric   for (const SDep &Succ : LastLocalSU->Succs) {
1789edd7eaddSDimitry Andric     if (Succ.getKind() != SDep::Data || Succ.getReg() != LocalReg)
1790284c1978SDimitry Andric       continue;
1791edd7eaddSDimitry Andric     if (Succ.getSUnit() == GlobalSU)
1792284c1978SDimitry Andric       continue;
1793edd7eaddSDimitry Andric     if (!DAG->canAddEdge(GlobalSU, Succ.getSUnit()))
1794284c1978SDimitry Andric       return;
1795edd7eaddSDimitry Andric     LocalUses.push_back(Succ.getSUnit());
1796284c1978SDimitry Andric   }
1797284c1978SDimitry Andric   // Open the top of the GlobalLI hole by constraining any earlier global uses
1798284c1978SDimitry Andric   // to precede the start of LocalLI.
1799284c1978SDimitry Andric   SmallVector<SUnit*,8> GlobalUses;
1800284c1978SDimitry Andric   MachineInstr *FirstLocalDef =
1801284c1978SDimitry Andric     LIS->getInstructionFromIndex(LocalLI->beginIndex());
1802284c1978SDimitry Andric   SUnit *FirstLocalSU = DAG->getSUnit(FirstLocalDef);
1803edd7eaddSDimitry Andric   for (const SDep &Pred : GlobalSU->Preds) {
1804edd7eaddSDimitry Andric     if (Pred.getKind() != SDep::Anti || Pred.getReg() != GlobalReg)
1805284c1978SDimitry Andric       continue;
1806edd7eaddSDimitry Andric     if (Pred.getSUnit() == FirstLocalSU)
1807284c1978SDimitry Andric       continue;
1808edd7eaddSDimitry Andric     if (!DAG->canAddEdge(FirstLocalSU, Pred.getSUnit()))
1809284c1978SDimitry Andric       return;
1810edd7eaddSDimitry Andric     GlobalUses.push_back(Pred.getSUnit());
1811284c1978SDimitry Andric   }
18124ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Constraining copy SU(" << CopySU->NodeNum << ")\n");
1813284c1978SDimitry Andric   // Add the weak edges.
1814284c1978SDimitry Andric   for (SmallVectorImpl<SUnit*>::const_iterator
1815284c1978SDimitry Andric          I = LocalUses.begin(), E = LocalUses.end(); I != E; ++I) {
18164ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "  Local use SU(" << (*I)->NodeNum << ") -> SU("
1817284c1978SDimitry Andric                       << GlobalSU->NodeNum << ")\n");
1818284c1978SDimitry Andric     DAG->addEdge(GlobalSU, SDep(*I, SDep::Weak));
1819284c1978SDimitry Andric   }
1820284c1978SDimitry Andric   for (SmallVectorImpl<SUnit*>::const_iterator
1821284c1978SDimitry Andric          I = GlobalUses.begin(), E = GlobalUses.end(); I != E; ++I) {
18224ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "  Global use SU(" << (*I)->NodeNum << ") -> SU("
1823284c1978SDimitry Andric                       << FirstLocalSU->NodeNum << ")\n");
1824284c1978SDimitry Andric     DAG->addEdge(FirstLocalSU, SDep(*I, SDep::Weak));
1825284c1978SDimitry Andric   }
1826284c1978SDimitry Andric }
1827284c1978SDimitry Andric 
18284ba319b5SDimitry Andric /// Callback from DAG postProcessing to create weak edges to encourage
1829284c1978SDimitry Andric /// copy elimination.
apply(ScheduleDAGInstrs * DAGInstrs)18303ca95b02SDimitry Andric void CopyConstrain::apply(ScheduleDAGInstrs *DAGInstrs) {
18313ca95b02SDimitry Andric   ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs);
183291bc56edSDimitry Andric   assert(DAG->hasVRegLiveness() && "Expect VRegs with LiveIntervals");
183391bc56edSDimitry Andric 
1834284c1978SDimitry Andric   MachineBasicBlock::iterator FirstPos = nextIfDebug(DAG->begin(), DAG->end());
1835284c1978SDimitry Andric   if (FirstPos == DAG->end())
1836284c1978SDimitry Andric     return;
18373ca95b02SDimitry Andric   RegionBeginIdx = DAG->getLIS()->getInstructionIndex(*FirstPos);
1838284c1978SDimitry Andric   RegionEndIdx = DAG->getLIS()->getInstructionIndex(
18393ca95b02SDimitry Andric       *priorNonDebug(DAG->end(), DAG->begin()));
1840284c1978SDimitry Andric 
1841edd7eaddSDimitry Andric   for (SUnit &SU : DAG->SUnits) {
1842edd7eaddSDimitry Andric     if (!SU.getInstr()->isCopy())
1843284c1978SDimitry Andric       continue;
1844284c1978SDimitry Andric 
1845edd7eaddSDimitry Andric     constrainLocalCopy(&SU, static_cast<ScheduleDAGMILive*>(DAG));
1846284c1978SDimitry Andric   }
1847284c1978SDimitry Andric }
1848284c1978SDimitry Andric 
1849284c1978SDimitry Andric //===----------------------------------------------------------------------===//
185091bc56edSDimitry Andric // MachineSchedStrategy helpers used by GenericScheduler, GenericPostScheduler
185191bc56edSDimitry Andric // and possibly other custom schedulers.
1852dff0c46cSDimitry Andric //===----------------------------------------------------------------------===//
1853dff0c46cSDimitry Andric 
185491bc56edSDimitry Andric static const unsigned InvalidCycle = ~0U;
18553861d79fSDimitry Andric 
~SchedBoundary()185691bc56edSDimitry Andric SchedBoundary::~SchedBoundary() { delete HazardRec; }
18573861d79fSDimitry Andric 
18582cab237bSDimitry Andric /// Given a Count of resource usage and a Latency value, return true if a
18592cab237bSDimitry Andric /// SchedBoundary becomes resource limited.
checkResourceLimit(unsigned LFactor,unsigned Count,unsigned Latency)18602cab237bSDimitry Andric static bool checkResourceLimit(unsigned LFactor, unsigned Count,
18612cab237bSDimitry Andric                                unsigned Latency) {
18622cab237bSDimitry Andric   return (int)(Count - (Latency * LFactor)) > (int)LFactor;
18632cab237bSDimitry Andric }
18642cab237bSDimitry Andric 
reset()186591bc56edSDimitry Andric void SchedBoundary::reset() {
1866139f7f9bSDimitry Andric   // A new HazardRec is created for each DAG and owned by SchedBoundary.
1867f785676fSDimitry Andric   // Destroying and reconstructing it is very expensive though. So keep
1868f785676fSDimitry Andric   // invalid, placeholder HazardRecs.
1869f785676fSDimitry Andric   if (HazardRec && HazardRec->isEnabled()) {
1870139f7f9bSDimitry Andric     delete HazardRec;
187191bc56edSDimitry Andric     HazardRec = nullptr;
1872f785676fSDimitry Andric   }
18733861d79fSDimitry Andric   Available.clear();
18743861d79fSDimitry Andric   Pending.clear();
18753861d79fSDimitry Andric   CheckPending = false;
18763861d79fSDimitry Andric   CurrCycle = 0;
1877f785676fSDimitry Andric   CurrMOps = 0;
18787a7e6055SDimitry Andric   MinReadyCycle = std::numeric_limits<unsigned>::max();
18793861d79fSDimitry Andric   ExpectedLatency = 0;
1880f785676fSDimitry Andric   DependentLatency = 0;
1881f785676fSDimitry Andric   RetiredMOps = 0;
1882f785676fSDimitry Andric   MaxExecutedResCount = 0;
1883f785676fSDimitry Andric   ZoneCritResIdx = 0;
18843861d79fSDimitry Andric   IsResourceLimited = false;
188591bc56edSDimitry Andric   ReservedCycles.clear();
18863861d79fSDimitry Andric #ifndef NDEBUG
188791bc56edSDimitry Andric   // Track the maximum number of stall cycles that could arise either from the
188891bc56edSDimitry Andric   // latency of a DAG edge or the number of cycles that a processor resource is
188991bc56edSDimitry Andric   // reserved (SchedBoundary::ReservedCycles).
189091bc56edSDimitry Andric   MaxObservedStall = 0;
18913861d79fSDimitry Andric #endif
18923861d79fSDimitry Andric   // Reserve a zero-count for invalid CritResIdx.
1893f785676fSDimitry Andric   ExecutedResCounts.resize(1);
1894f785676fSDimitry Andric   assert(!ExecutedResCounts[0] && "nonzero count for bad resource");
18953861d79fSDimitry Andric }
18967ae0e2c9SDimitry Andric 
189791bc56edSDimitry Andric void SchedRemainder::
init(ScheduleDAGMI * DAG,const TargetSchedModel * SchedModel)18983861d79fSDimitry Andric init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
18993861d79fSDimitry Andric   reset();
19003861d79fSDimitry Andric   if (!SchedModel->hasInstrSchedModel())
19013861d79fSDimitry Andric     return;
19023861d79fSDimitry Andric   RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
1903edd7eaddSDimitry Andric   for (SUnit &SU : DAG->SUnits) {
1904edd7eaddSDimitry Andric     const MCSchedClassDesc *SC = DAG->getSchedClass(&SU);
1905edd7eaddSDimitry Andric     RemIssueCount += SchedModel->getNumMicroOps(SU.getInstr(), SC)
1906f785676fSDimitry Andric       * SchedModel->getMicroOpFactor();
19073861d79fSDimitry Andric     for (TargetSchedModel::ProcResIter
19083861d79fSDimitry Andric            PI = SchedModel->getWriteProcResBegin(SC),
19093861d79fSDimitry Andric            PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
19103861d79fSDimitry Andric       unsigned PIdx = PI->ProcResourceIdx;
19113861d79fSDimitry Andric       unsigned Factor = SchedModel->getResourceFactor(PIdx);
19123861d79fSDimitry Andric       RemainingCounts[PIdx] += (Factor * PI->Cycles);
19133861d79fSDimitry Andric     }
19143861d79fSDimitry Andric   }
19153861d79fSDimitry Andric }
19163861d79fSDimitry Andric 
191791bc56edSDimitry Andric void SchedBoundary::
init(ScheduleDAGMI * dag,const TargetSchedModel * smodel,SchedRemainder * rem)19183861d79fSDimitry Andric init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
19193861d79fSDimitry Andric   reset();
19203861d79fSDimitry Andric   DAG = dag;
19213861d79fSDimitry Andric   SchedModel = smodel;
19223861d79fSDimitry Andric   Rem = rem;
192391bc56edSDimitry Andric   if (SchedModel->hasInstrSchedModel()) {
1924f785676fSDimitry Andric     ExecutedResCounts.resize(SchedModel->getNumProcResourceKinds());
192591bc56edSDimitry Andric     ReservedCycles.resize(SchedModel->getNumProcResourceKinds(), InvalidCycle);
192691bc56edSDimitry Andric   }
192791bc56edSDimitry Andric }
192891bc56edSDimitry Andric 
192991bc56edSDimitry Andric /// Compute the stall cycles based on this SUnit's ready time. Heuristics treat
193091bc56edSDimitry Andric /// these "soft stalls" differently than the hard stall cycles based on CPU
193191bc56edSDimitry Andric /// resources and computed by checkHazard(). A fully in-order model
193291bc56edSDimitry Andric /// (MicroOpBufferSize==0) will not make use of this since instructions are not
193391bc56edSDimitry Andric /// available for scheduling until they are ready. However, a weaker in-order
193491bc56edSDimitry Andric /// model may use this for heuristics. For example, if a processor has in-order
193591bc56edSDimitry Andric /// behavior when reading certain resources, this may come into play.
getLatencyStallCycles(SUnit * SU)193691bc56edSDimitry Andric unsigned SchedBoundary::getLatencyStallCycles(SUnit *SU) {
193791bc56edSDimitry Andric   if (!SU->isUnbuffered)
193891bc56edSDimitry Andric     return 0;
193991bc56edSDimitry Andric 
194091bc56edSDimitry Andric   unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
194191bc56edSDimitry Andric   if (ReadyCycle > CurrCycle)
194291bc56edSDimitry Andric     return ReadyCycle - CurrCycle;
194391bc56edSDimitry Andric   return 0;
194491bc56edSDimitry Andric }
194591bc56edSDimitry Andric 
194691bc56edSDimitry Andric /// Compute the next cycle at which the given processor resource can be
194791bc56edSDimitry Andric /// scheduled.
194891bc56edSDimitry Andric unsigned SchedBoundary::
getNextResourceCycle(unsigned PIdx,unsigned Cycles)194991bc56edSDimitry Andric getNextResourceCycle(unsigned PIdx, unsigned Cycles) {
195091bc56edSDimitry Andric   unsigned NextUnreserved = ReservedCycles[PIdx];
195191bc56edSDimitry Andric   // If this resource has never been used, always return cycle zero.
195291bc56edSDimitry Andric   if (NextUnreserved == InvalidCycle)
195391bc56edSDimitry Andric     return 0;
195491bc56edSDimitry Andric   // For bottom-up scheduling add the cycles needed for the current operation.
195591bc56edSDimitry Andric   if (!isTop())
195691bc56edSDimitry Andric     NextUnreserved += Cycles;
195791bc56edSDimitry Andric   return NextUnreserved;
195891bc56edSDimitry Andric }
195991bc56edSDimitry Andric 
196091bc56edSDimitry Andric /// Does this SU have a hazard within the current instruction group.
196191bc56edSDimitry Andric ///
196291bc56edSDimitry Andric /// The scheduler supports two modes of hazard recognition. The first is the
196391bc56edSDimitry Andric /// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
196491bc56edSDimitry Andric /// supports highly complicated in-order reservation tables
19654ba319b5SDimitry Andric /// (ScoreboardHazardRecognizer) and arbitrary target-specific logic.
196691bc56edSDimitry Andric ///
196791bc56edSDimitry Andric /// The second is a streamlined mechanism that checks for hazards based on
196891bc56edSDimitry Andric /// simple counters that the scheduler itself maintains. It explicitly checks
196991bc56edSDimitry Andric /// for instruction dispatch limitations, including the number of micro-ops that
197091bc56edSDimitry Andric /// can dispatch per cycle.
197191bc56edSDimitry Andric ///
197291bc56edSDimitry Andric /// TODO: Also check whether the SU must start a new group.
checkHazard(SUnit * SU)197391bc56edSDimitry Andric bool SchedBoundary::checkHazard(SUnit *SU) {
197491bc56edSDimitry Andric   if (HazardRec->isEnabled()
197591bc56edSDimitry Andric       && HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard) {
197691bc56edSDimitry Andric     return true;
197791bc56edSDimitry Andric   }
19787a7e6055SDimitry Andric 
197991bc56edSDimitry Andric   unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
198091bc56edSDimitry Andric   if ((CurrMOps > 0) && (CurrMOps + uops > SchedModel->getIssueWidth())) {
19814ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "  SU(" << SU->NodeNum << ") uops="
198291bc56edSDimitry Andric                       << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
198391bc56edSDimitry Andric     return true;
198491bc56edSDimitry Andric   }
19857a7e6055SDimitry Andric 
19867a7e6055SDimitry Andric   if (CurrMOps > 0 &&
19877a7e6055SDimitry Andric       ((isTop() && SchedModel->mustBeginGroup(SU->getInstr())) ||
19887a7e6055SDimitry Andric        (!isTop() && SchedModel->mustEndGroup(SU->getInstr())))) {
19894ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "  hazard: SU(" << SU->NodeNum << ") must "
19907a7e6055SDimitry Andric                       << (isTop() ? "begin" : "end") << " group\n");
19917a7e6055SDimitry Andric     return true;
19927a7e6055SDimitry Andric   }
19937a7e6055SDimitry Andric 
199491bc56edSDimitry Andric   if (SchedModel->hasInstrSchedModel() && SU->hasReservedResource) {
199591bc56edSDimitry Andric     const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
19962cab237bSDimitry Andric     for (const MCWriteProcResEntry &PE :
19972cab237bSDimitry Andric           make_range(SchedModel->getWriteProcResBegin(SC),
19982cab237bSDimitry Andric                      SchedModel->getWriteProcResEnd(SC))) {
19992cab237bSDimitry Andric       unsigned ResIdx = PE.ProcResourceIdx;
20002cab237bSDimitry Andric       unsigned Cycles = PE.Cycles;
20012cab237bSDimitry Andric       unsigned NRCycle = getNextResourceCycle(ResIdx, Cycles);
200291bc56edSDimitry Andric       if (NRCycle > CurrCycle) {
200391bc56edSDimitry Andric #ifndef NDEBUG
20042cab237bSDimitry Andric         MaxObservedStall = std::max(Cycles, MaxObservedStall);
200591bc56edSDimitry Andric #endif
20064ba319b5SDimitry Andric         LLVM_DEBUG(dbgs() << "  SU(" << SU->NodeNum << ") "
20074ba319b5SDimitry Andric                           << SchedModel->getResourceName(ResIdx) << "="
20084ba319b5SDimitry Andric                           << NRCycle << "c\n");
200991bc56edSDimitry Andric         return true;
201091bc56edSDimitry Andric       }
201191bc56edSDimitry Andric     }
201291bc56edSDimitry Andric   }
201391bc56edSDimitry Andric   return false;
201491bc56edSDimitry Andric }
201591bc56edSDimitry Andric 
201691bc56edSDimitry Andric // Find the unscheduled node in ReadySUs with the highest latency.
201791bc56edSDimitry Andric unsigned SchedBoundary::
findMaxLatency(ArrayRef<SUnit * > ReadySUs)201891bc56edSDimitry Andric findMaxLatency(ArrayRef<SUnit*> ReadySUs) {
201991bc56edSDimitry Andric   SUnit *LateSU = nullptr;
202091bc56edSDimitry Andric   unsigned RemLatency = 0;
2021edd7eaddSDimitry Andric   for (SUnit *SU : ReadySUs) {
2022edd7eaddSDimitry Andric     unsigned L = getUnscheduledLatency(SU);
202391bc56edSDimitry Andric     if (L > RemLatency) {
202491bc56edSDimitry Andric       RemLatency = L;
2025edd7eaddSDimitry Andric       LateSU = SU;
202691bc56edSDimitry Andric     }
202791bc56edSDimitry Andric   }
202891bc56edSDimitry Andric   if (LateSU) {
20294ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << Available.getName() << " RemLatency SU("
203091bc56edSDimitry Andric                       << LateSU->NodeNum << ") " << RemLatency << "c\n");
203191bc56edSDimitry Andric   }
203291bc56edSDimitry Andric   return RemLatency;
203391bc56edSDimitry Andric }
203491bc56edSDimitry Andric 
203591bc56edSDimitry Andric // Count resources in this zone and the remaining unscheduled
203691bc56edSDimitry Andric // instruction. Return the max count, scaled. Set OtherCritIdx to the critical
203791bc56edSDimitry Andric // resource index, or zero if the zone is issue limited.
203891bc56edSDimitry Andric unsigned SchedBoundary::
getOtherResourceCount(unsigned & OtherCritIdx)203991bc56edSDimitry Andric getOtherResourceCount(unsigned &OtherCritIdx) {
204091bc56edSDimitry Andric   OtherCritIdx = 0;
204191bc56edSDimitry Andric   if (!SchedModel->hasInstrSchedModel())
204291bc56edSDimitry Andric     return 0;
204391bc56edSDimitry Andric 
204491bc56edSDimitry Andric   unsigned OtherCritCount = Rem->RemIssueCount
204591bc56edSDimitry Andric     + (RetiredMOps * SchedModel->getMicroOpFactor());
20464ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "  " << Available.getName() << " + Remain MOps: "
204791bc56edSDimitry Andric                     << OtherCritCount / SchedModel->getMicroOpFactor() << '\n');
204891bc56edSDimitry Andric   for (unsigned PIdx = 1, PEnd = SchedModel->getNumProcResourceKinds();
204991bc56edSDimitry Andric        PIdx != PEnd; ++PIdx) {
205091bc56edSDimitry Andric     unsigned OtherCount = getResourceCount(PIdx) + Rem->RemainingCounts[PIdx];
205191bc56edSDimitry Andric     if (OtherCount > OtherCritCount) {
205291bc56edSDimitry Andric       OtherCritCount = OtherCount;
205391bc56edSDimitry Andric       OtherCritIdx = PIdx;
205491bc56edSDimitry Andric     }
205591bc56edSDimitry Andric   }
205691bc56edSDimitry Andric   if (OtherCritIdx) {
20574ba319b5SDimitry Andric     LLVM_DEBUG(
20584ba319b5SDimitry Andric         dbgs() << "  " << Available.getName() << " + Remain CritRes: "
205991bc56edSDimitry Andric                << OtherCritCount / SchedModel->getResourceFactor(OtherCritIdx)
206091bc56edSDimitry Andric                << " " << SchedModel->getResourceName(OtherCritIdx) << "\n");
206191bc56edSDimitry Andric   }
206291bc56edSDimitry Andric   return OtherCritCount;
206391bc56edSDimitry Andric }
206491bc56edSDimitry Andric 
releaseNode(SUnit * SU,unsigned ReadyCycle)206591bc56edSDimitry Andric void SchedBoundary::releaseNode(SUnit *SU, unsigned ReadyCycle) {
206691bc56edSDimitry Andric   assert(SU->getInstr() && "Scheduled SUnit must have instr");
206791bc56edSDimitry Andric 
206891bc56edSDimitry Andric #ifndef NDEBUG
206991bc56edSDimitry Andric   // ReadyCycle was been bumped up to the CurrCycle when this node was
207091bc56edSDimitry Andric   // scheduled, but CurrCycle may have been eagerly advanced immediately after
207191bc56edSDimitry Andric   // scheduling, so may now be greater than ReadyCycle.
207291bc56edSDimitry Andric   if (ReadyCycle > CurrCycle)
207391bc56edSDimitry Andric     MaxObservedStall = std::max(ReadyCycle - CurrCycle, MaxObservedStall);
207491bc56edSDimitry Andric #endif
207591bc56edSDimitry Andric 
207691bc56edSDimitry Andric   if (ReadyCycle < MinReadyCycle)
207791bc56edSDimitry Andric     MinReadyCycle = ReadyCycle;
207891bc56edSDimitry Andric 
207991bc56edSDimitry Andric   // Check for interlocks first. For the purpose of other heuristics, an
208091bc56edSDimitry Andric   // instruction that cannot issue appears as if it's not in the ReadyQueue.
208191bc56edSDimitry Andric   bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
20823ca95b02SDimitry Andric   if ((!IsBuffered && ReadyCycle > CurrCycle) || checkHazard(SU) ||
20833ca95b02SDimitry Andric       Available.size() >= ReadyListLimit)
208491bc56edSDimitry Andric     Pending.push(SU);
208591bc56edSDimitry Andric   else
208691bc56edSDimitry Andric     Available.push(SU);
208791bc56edSDimitry Andric }
208891bc56edSDimitry Andric 
208991bc56edSDimitry Andric /// Move the boundary of scheduled code by one cycle.
bumpCycle(unsigned NextCycle)209091bc56edSDimitry Andric void SchedBoundary::bumpCycle(unsigned NextCycle) {
209191bc56edSDimitry Andric   if (SchedModel->getMicroOpBufferSize() == 0) {
20927a7e6055SDimitry Andric     assert(MinReadyCycle < std::numeric_limits<unsigned>::max() &&
20937a7e6055SDimitry Andric            "MinReadyCycle uninitialized");
209491bc56edSDimitry Andric     if (MinReadyCycle > NextCycle)
209591bc56edSDimitry Andric       NextCycle = MinReadyCycle;
209691bc56edSDimitry Andric   }
209791bc56edSDimitry Andric   // Update the current micro-ops, which will issue in the next cycle.
209891bc56edSDimitry Andric   unsigned DecMOps = SchedModel->getIssueWidth() * (NextCycle - CurrCycle);
209991bc56edSDimitry Andric   CurrMOps = (CurrMOps <= DecMOps) ? 0 : CurrMOps - DecMOps;
210091bc56edSDimitry Andric 
210191bc56edSDimitry Andric   // Decrement DependentLatency based on the next cycle.
210291bc56edSDimitry Andric   if ((NextCycle - CurrCycle) > DependentLatency)
210391bc56edSDimitry Andric     DependentLatency = 0;
210491bc56edSDimitry Andric   else
210591bc56edSDimitry Andric     DependentLatency -= (NextCycle - CurrCycle);
210691bc56edSDimitry Andric 
210791bc56edSDimitry Andric   if (!HazardRec->isEnabled()) {
210891bc56edSDimitry Andric     // Bypass HazardRec virtual calls.
210991bc56edSDimitry Andric     CurrCycle = NextCycle;
21103ca95b02SDimitry Andric   } else {
211191bc56edSDimitry Andric     // Bypass getHazardType calls in case of long latency.
211291bc56edSDimitry Andric     for (; CurrCycle != NextCycle; ++CurrCycle) {
211391bc56edSDimitry Andric       if (isTop())
211491bc56edSDimitry Andric         HazardRec->AdvanceCycle();
211591bc56edSDimitry Andric       else
211691bc56edSDimitry Andric         HazardRec->RecedeCycle();
211791bc56edSDimitry Andric     }
211891bc56edSDimitry Andric   }
211991bc56edSDimitry Andric   CheckPending = true;
212091bc56edSDimitry Andric   IsResourceLimited =
21212cab237bSDimitry Andric       checkResourceLimit(SchedModel->getLatencyFactor(), getCriticalCount(),
21222cab237bSDimitry Andric                          getScheduledLatency());
212391bc56edSDimitry Andric 
21244ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Cycle: " << CurrCycle << ' ' << Available.getName()
21254ba319b5SDimitry Andric                     << '\n');
212691bc56edSDimitry Andric }
212791bc56edSDimitry Andric 
incExecutedResources(unsigned PIdx,unsigned Count)212891bc56edSDimitry Andric void SchedBoundary::incExecutedResources(unsigned PIdx, unsigned Count) {
212991bc56edSDimitry Andric   ExecutedResCounts[PIdx] += Count;
213091bc56edSDimitry Andric   if (ExecutedResCounts[PIdx] > MaxExecutedResCount)
213191bc56edSDimitry Andric     MaxExecutedResCount = ExecutedResCounts[PIdx];
213291bc56edSDimitry Andric }
213391bc56edSDimitry Andric 
213491bc56edSDimitry Andric /// Add the given processor resource to this scheduled zone.
213591bc56edSDimitry Andric ///
213691bc56edSDimitry Andric /// \param Cycles indicates the number of consecutive (non-pipelined) cycles
213791bc56edSDimitry Andric /// during which this resource is consumed.
213891bc56edSDimitry Andric ///
213991bc56edSDimitry Andric /// \return the next cycle at which the instruction may execute without
214091bc56edSDimitry Andric /// oversubscribing resources.
214191bc56edSDimitry Andric unsigned SchedBoundary::
countResource(unsigned PIdx,unsigned Cycles,unsigned NextCycle)214291bc56edSDimitry Andric countResource(unsigned PIdx, unsigned Cycles, unsigned NextCycle) {
214391bc56edSDimitry Andric   unsigned Factor = SchedModel->getResourceFactor(PIdx);
214491bc56edSDimitry Andric   unsigned Count = Factor * Cycles;
21454ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "  " << SchedModel->getResourceName(PIdx) << " +"
21464ba319b5SDimitry Andric                     << Cycles << "x" << Factor << "u\n");
214791bc56edSDimitry Andric 
214891bc56edSDimitry Andric   // Update Executed resources counts.
214991bc56edSDimitry Andric   incExecutedResources(PIdx, Count);
215091bc56edSDimitry Andric   assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
215191bc56edSDimitry Andric   Rem->RemainingCounts[PIdx] -= Count;
215291bc56edSDimitry Andric 
215391bc56edSDimitry Andric   // Check if this resource exceeds the current critical resource. If so, it
215491bc56edSDimitry Andric   // becomes the critical resource.
215591bc56edSDimitry Andric   if (ZoneCritResIdx != PIdx && (getResourceCount(PIdx) > getCriticalCount())) {
215691bc56edSDimitry Andric     ZoneCritResIdx = PIdx;
21574ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "  *** Critical resource "
215891bc56edSDimitry Andric                       << SchedModel->getResourceName(PIdx) << ": "
21594ba319b5SDimitry Andric                       << getResourceCount(PIdx) / SchedModel->getLatencyFactor()
21604ba319b5SDimitry Andric                       << "c\n");
216191bc56edSDimitry Andric   }
216291bc56edSDimitry Andric   // For reserved resources, record the highest cycle using the resource.
216391bc56edSDimitry Andric   unsigned NextAvailable = getNextResourceCycle(PIdx, Cycles);
216491bc56edSDimitry Andric   if (NextAvailable > CurrCycle) {
21654ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "  Resource conflict: "
21664ba319b5SDimitry Andric                       << SchedModel->getProcResource(PIdx)->Name
21674ba319b5SDimitry Andric                       << " reserved until @" << NextAvailable << "\n");
216891bc56edSDimitry Andric   }
216991bc56edSDimitry Andric   return NextAvailable;
217091bc56edSDimitry Andric }
217191bc56edSDimitry Andric 
217291bc56edSDimitry Andric /// Move the boundary of scheduled code by one SUnit.
bumpNode(SUnit * SU)217391bc56edSDimitry Andric void SchedBoundary::bumpNode(SUnit *SU) {
217491bc56edSDimitry Andric   // Update the reservation table.
217591bc56edSDimitry Andric   if (HazardRec->isEnabled()) {
217691bc56edSDimitry Andric     if (!isTop() && SU->isCall) {
217791bc56edSDimitry Andric       // Calls are scheduled with their preceding instructions. For bottom-up
217891bc56edSDimitry Andric       // scheduling, clear the pipeline state before emitting.
217991bc56edSDimitry Andric       HazardRec->Reset();
218091bc56edSDimitry Andric     }
218191bc56edSDimitry Andric     HazardRec->EmitInstruction(SU);
218291bc56edSDimitry Andric   }
218391bc56edSDimitry Andric   // checkHazard should prevent scheduling multiple instructions per cycle that
218491bc56edSDimitry Andric   // exceed the issue width.
218591bc56edSDimitry Andric   const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
218691bc56edSDimitry Andric   unsigned IncMOps = SchedModel->getNumMicroOps(SU->getInstr());
218791bc56edSDimitry Andric   assert(
218891bc56edSDimitry Andric       (CurrMOps == 0 || (CurrMOps + IncMOps) <= SchedModel->getIssueWidth()) &&
218991bc56edSDimitry Andric       "Cannot schedule this instruction's MicroOps in the current cycle.");
219091bc56edSDimitry Andric 
219191bc56edSDimitry Andric   unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
21924ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "  Ready @" << ReadyCycle << "c\n");
219391bc56edSDimitry Andric 
219491bc56edSDimitry Andric   unsigned NextCycle = CurrCycle;
219591bc56edSDimitry Andric   switch (SchedModel->getMicroOpBufferSize()) {
219691bc56edSDimitry Andric   case 0:
219791bc56edSDimitry Andric     assert(ReadyCycle <= CurrCycle && "Broken PendingQueue");
219891bc56edSDimitry Andric     break;
219991bc56edSDimitry Andric   case 1:
220091bc56edSDimitry Andric     if (ReadyCycle > NextCycle) {
220191bc56edSDimitry Andric       NextCycle = ReadyCycle;
22024ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "  *** Stall until: " << ReadyCycle << "\n");
220391bc56edSDimitry Andric     }
220491bc56edSDimitry Andric     break;
220591bc56edSDimitry Andric   default:
220691bc56edSDimitry Andric     // We don't currently model the OOO reorder buffer, so consider all
220791bc56edSDimitry Andric     // scheduled MOps to be "retired". We do loosely model in-order resource
220891bc56edSDimitry Andric     // latency. If this instruction uses an in-order resource, account for any
220991bc56edSDimitry Andric     // likely stall cycles.
221091bc56edSDimitry Andric     if (SU->isUnbuffered && ReadyCycle > NextCycle)
221191bc56edSDimitry Andric       NextCycle = ReadyCycle;
221291bc56edSDimitry Andric     break;
221391bc56edSDimitry Andric   }
221491bc56edSDimitry Andric   RetiredMOps += IncMOps;
221591bc56edSDimitry Andric 
221691bc56edSDimitry Andric   // Update resource counts and critical resource.
221791bc56edSDimitry Andric   if (SchedModel->hasInstrSchedModel()) {
221891bc56edSDimitry Andric     unsigned DecRemIssue = IncMOps * SchedModel->getMicroOpFactor();
221991bc56edSDimitry Andric     assert(Rem->RemIssueCount >= DecRemIssue && "MOps double counted");
222091bc56edSDimitry Andric     Rem->RemIssueCount -= DecRemIssue;
222191bc56edSDimitry Andric     if (ZoneCritResIdx) {
222291bc56edSDimitry Andric       // Scale scheduled micro-ops for comparing with the critical resource.
222391bc56edSDimitry Andric       unsigned ScaledMOps =
222491bc56edSDimitry Andric         RetiredMOps * SchedModel->getMicroOpFactor();
222591bc56edSDimitry Andric 
222691bc56edSDimitry Andric       // If scaled micro-ops are now more than the previous critical resource by
222791bc56edSDimitry Andric       // a full cycle, then micro-ops issue becomes critical.
222891bc56edSDimitry Andric       if ((int)(ScaledMOps - getResourceCount(ZoneCritResIdx))
222991bc56edSDimitry Andric           >= (int)SchedModel->getLatencyFactor()) {
223091bc56edSDimitry Andric         ZoneCritResIdx = 0;
22314ba319b5SDimitry Andric         LLVM_DEBUG(dbgs() << "  *** Critical resource NumMicroOps: "
22324ba319b5SDimitry Andric                           << ScaledMOps / SchedModel->getLatencyFactor()
22334ba319b5SDimitry Andric                           << "c\n");
223491bc56edSDimitry Andric       }
223591bc56edSDimitry Andric     }
223691bc56edSDimitry Andric     for (TargetSchedModel::ProcResIter
223791bc56edSDimitry Andric            PI = SchedModel->getWriteProcResBegin(SC),
223891bc56edSDimitry Andric            PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
223991bc56edSDimitry Andric       unsigned RCycle =
224091bc56edSDimitry Andric         countResource(PI->ProcResourceIdx, PI->Cycles, NextCycle);
224191bc56edSDimitry Andric       if (RCycle > NextCycle)
224291bc56edSDimitry Andric         NextCycle = RCycle;
224391bc56edSDimitry Andric     }
224491bc56edSDimitry Andric     if (SU->hasReservedResource) {
224591bc56edSDimitry Andric       // For reserved resources, record the highest cycle using the resource.
224691bc56edSDimitry Andric       // For top-down scheduling, this is the cycle in which we schedule this
224791bc56edSDimitry Andric       // instruction plus the number of cycles the operations reserves the
224891bc56edSDimitry Andric       // resource. For bottom-up is it simply the instruction's cycle.
224991bc56edSDimitry Andric       for (TargetSchedModel::ProcResIter
225091bc56edSDimitry Andric              PI = SchedModel->getWriteProcResBegin(SC),
225191bc56edSDimitry Andric              PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
225291bc56edSDimitry Andric         unsigned PIdx = PI->ProcResourceIdx;
225391bc56edSDimitry Andric         if (SchedModel->getProcResource(PIdx)->BufferSize == 0) {
225491bc56edSDimitry Andric           if (isTop()) {
225591bc56edSDimitry Andric             ReservedCycles[PIdx] =
225691bc56edSDimitry Andric               std::max(getNextResourceCycle(PIdx, 0), NextCycle + PI->Cycles);
225791bc56edSDimitry Andric           }
225891bc56edSDimitry Andric           else
225991bc56edSDimitry Andric             ReservedCycles[PIdx] = NextCycle;
226091bc56edSDimitry Andric         }
226191bc56edSDimitry Andric       }
226291bc56edSDimitry Andric     }
226391bc56edSDimitry Andric   }
226491bc56edSDimitry Andric   // Update ExpectedLatency and DependentLatency.
226591bc56edSDimitry Andric   unsigned &TopLatency = isTop() ? ExpectedLatency : DependentLatency;
226691bc56edSDimitry Andric   unsigned &BotLatency = isTop() ? DependentLatency : ExpectedLatency;
226791bc56edSDimitry Andric   if (SU->getDepth() > TopLatency) {
226891bc56edSDimitry Andric     TopLatency = SU->getDepth();
22694ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "  " << Available.getName() << " TopLatency SU("
22704ba319b5SDimitry Andric                       << SU->NodeNum << ") " << TopLatency << "c\n");
227191bc56edSDimitry Andric   }
227291bc56edSDimitry Andric   if (SU->getHeight() > BotLatency) {
227391bc56edSDimitry Andric     BotLatency = SU->getHeight();
22744ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "  " << Available.getName() << " BotLatency SU("
22754ba319b5SDimitry Andric                       << SU->NodeNum << ") " << BotLatency << "c\n");
227691bc56edSDimitry Andric   }
227791bc56edSDimitry Andric   // If we stall for any reason, bump the cycle.
22782cab237bSDimitry Andric   if (NextCycle > CurrCycle)
227991bc56edSDimitry Andric     bumpCycle(NextCycle);
22802cab237bSDimitry Andric   else
228191bc56edSDimitry Andric     // After updating ZoneCritResIdx and ExpectedLatency, check if we're
228291bc56edSDimitry Andric     // resource limited. If a stall occurred, bumpCycle does this.
228391bc56edSDimitry Andric     IsResourceLimited =
22842cab237bSDimitry Andric         checkResourceLimit(SchedModel->getLatencyFactor(), getCriticalCount(),
22852cab237bSDimitry Andric                            getScheduledLatency());
22862cab237bSDimitry Andric 
228791bc56edSDimitry Andric   // Update CurrMOps after calling bumpCycle to handle stalls, since bumpCycle
228891bc56edSDimitry Andric   // resets CurrMOps. Loop to handle instructions with more MOps than issue in
228991bc56edSDimitry Andric   // one cycle.  Since we commonly reach the max MOps here, opportunistically
229091bc56edSDimitry Andric   // bump the cycle to avoid uselessly checking everything in the readyQ.
229191bc56edSDimitry Andric   CurrMOps += IncMOps;
22927a7e6055SDimitry Andric 
22937a7e6055SDimitry Andric   // Bump the cycle count for issue group constraints.
22947a7e6055SDimitry Andric   // This must be done after NextCycle has been adjust for all other stalls.
22957a7e6055SDimitry Andric   // Calling bumpCycle(X) will reduce CurrMOps by one issue group and set
22967a7e6055SDimitry Andric   // currCycle to X.
22977a7e6055SDimitry Andric   if ((isTop() &&  SchedModel->mustEndGroup(SU->getInstr())) ||
22987a7e6055SDimitry Andric       (!isTop() && SchedModel->mustBeginGroup(SU->getInstr()))) {
22994ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "  Bump cycle to " << (isTop() ? "end" : "begin")
23004ba319b5SDimitry Andric                       << " group\n");
23017a7e6055SDimitry Andric     bumpCycle(++NextCycle);
23027a7e6055SDimitry Andric   }
23037a7e6055SDimitry Andric 
230491bc56edSDimitry Andric   while (CurrMOps >= SchedModel->getIssueWidth()) {
23054ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "  *** Max MOps " << CurrMOps << " at cycle "
23064ba319b5SDimitry Andric                       << CurrCycle << '\n');
230791bc56edSDimitry Andric     bumpCycle(++NextCycle);
230891bc56edSDimitry Andric   }
23094ba319b5SDimitry Andric   LLVM_DEBUG(dumpScheduledState());
231091bc56edSDimitry Andric }
231191bc56edSDimitry Andric 
231291bc56edSDimitry Andric /// Release pending ready nodes in to the available queue. This makes them
231391bc56edSDimitry Andric /// visible to heuristics.
releasePending()231491bc56edSDimitry Andric void SchedBoundary::releasePending() {
231591bc56edSDimitry Andric   // If the available queue is empty, it is safe to reset MinReadyCycle.
231691bc56edSDimitry Andric   if (Available.empty())
23177a7e6055SDimitry Andric     MinReadyCycle = std::numeric_limits<unsigned>::max();
231891bc56edSDimitry Andric 
231991bc56edSDimitry Andric   // Check to see if any of the pending instructions are ready to issue.  If
232091bc56edSDimitry Andric   // so, add them to the available queue.
232191bc56edSDimitry Andric   bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
232291bc56edSDimitry Andric   for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
232391bc56edSDimitry Andric     SUnit *SU = *(Pending.begin()+i);
232491bc56edSDimitry Andric     unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
232591bc56edSDimitry Andric 
232691bc56edSDimitry Andric     if (ReadyCycle < MinReadyCycle)
232791bc56edSDimitry Andric       MinReadyCycle = ReadyCycle;
232891bc56edSDimitry Andric 
232991bc56edSDimitry Andric     if (!IsBuffered && ReadyCycle > CurrCycle)
233091bc56edSDimitry Andric       continue;
233191bc56edSDimitry Andric 
233291bc56edSDimitry Andric     if (checkHazard(SU))
233391bc56edSDimitry Andric       continue;
233491bc56edSDimitry Andric 
23353ca95b02SDimitry Andric     if (Available.size() >= ReadyListLimit)
23363ca95b02SDimitry Andric       break;
23373ca95b02SDimitry Andric 
233891bc56edSDimitry Andric     Available.push(SU);
233991bc56edSDimitry Andric     Pending.remove(Pending.begin()+i);
234091bc56edSDimitry Andric     --i; --e;
234191bc56edSDimitry Andric   }
234291bc56edSDimitry Andric   CheckPending = false;
234391bc56edSDimitry Andric }
234491bc56edSDimitry Andric 
234591bc56edSDimitry Andric /// Remove SU from the ready set for this boundary.
removeReady(SUnit * SU)234691bc56edSDimitry Andric void SchedBoundary::removeReady(SUnit *SU) {
234791bc56edSDimitry Andric   if (Available.isInQueue(SU))
234891bc56edSDimitry Andric     Available.remove(Available.find(SU));
234991bc56edSDimitry Andric   else {
235091bc56edSDimitry Andric     assert(Pending.isInQueue(SU) && "bad ready count");
235191bc56edSDimitry Andric     Pending.remove(Pending.find(SU));
235291bc56edSDimitry Andric   }
235391bc56edSDimitry Andric }
235491bc56edSDimitry Andric 
235591bc56edSDimitry Andric /// If this queue only has one ready candidate, return it. As a side effect,
235691bc56edSDimitry Andric /// defer any nodes that now hit a hazard, and advance the cycle until at least
235791bc56edSDimitry Andric /// one node is ready. If multiple instructions are ready, return NULL.
pickOnlyChoice()235891bc56edSDimitry Andric SUnit *SchedBoundary::pickOnlyChoice() {
235991bc56edSDimitry Andric   if (CheckPending)
236091bc56edSDimitry Andric     releasePending();
236191bc56edSDimitry Andric 
236291bc56edSDimitry Andric   if (CurrMOps > 0) {
236391bc56edSDimitry Andric     // Defer any ready instrs that now have a hazard.
236491bc56edSDimitry Andric     for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
236591bc56edSDimitry Andric       if (checkHazard(*I)) {
236691bc56edSDimitry Andric         Pending.push(*I);
236791bc56edSDimitry Andric         I = Available.remove(I);
236891bc56edSDimitry Andric         continue;
236991bc56edSDimitry Andric       }
237091bc56edSDimitry Andric       ++I;
237191bc56edSDimitry Andric     }
237291bc56edSDimitry Andric   }
237391bc56edSDimitry Andric   for (unsigned i = 0; Available.empty(); ++i) {
237491bc56edSDimitry Andric //  FIXME: Re-enable assert once PR20057 is resolved.
237591bc56edSDimitry Andric //    assert(i <= (HazardRec->getMaxLookAhead() + MaxObservedStall) &&
237691bc56edSDimitry Andric //           "permanent hazard");
237791bc56edSDimitry Andric     (void)i;
237891bc56edSDimitry Andric     bumpCycle(CurrCycle + 1);
237991bc56edSDimitry Andric     releasePending();
238091bc56edSDimitry Andric   }
23813ca95b02SDimitry Andric 
23824ba319b5SDimitry Andric   LLVM_DEBUG(Pending.dump());
23834ba319b5SDimitry Andric   LLVM_DEBUG(Available.dump());
23843ca95b02SDimitry Andric 
238591bc56edSDimitry Andric   if (Available.size() == 1)
238691bc56edSDimitry Andric     return *Available.begin();
238791bc56edSDimitry Andric   return nullptr;
238891bc56edSDimitry Andric }
238991bc56edSDimitry Andric 
23907a7e6055SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
239191bc56edSDimitry Andric // This is useful information to dump after bumpNode.
239291bc56edSDimitry Andric // Note that the Queue contents are more useful before pickNodeFromQueue.
dumpScheduledState() const2393edd7eaddSDimitry Andric LLVM_DUMP_METHOD void SchedBoundary::dumpScheduledState() const {
239491bc56edSDimitry Andric   unsigned ResFactor;
239591bc56edSDimitry Andric   unsigned ResCount;
239691bc56edSDimitry Andric   if (ZoneCritResIdx) {
239791bc56edSDimitry Andric     ResFactor = SchedModel->getResourceFactor(ZoneCritResIdx);
239891bc56edSDimitry Andric     ResCount = getResourceCount(ZoneCritResIdx);
23993ca95b02SDimitry Andric   } else {
240091bc56edSDimitry Andric     ResFactor = SchedModel->getMicroOpFactor();
24012cab237bSDimitry Andric     ResCount = RetiredMOps * ResFactor;
240291bc56edSDimitry Andric   }
240391bc56edSDimitry Andric   unsigned LFactor = SchedModel->getLatencyFactor();
240491bc56edSDimitry Andric   dbgs() << Available.getName() << " @" << CurrCycle << "c\n"
240591bc56edSDimitry Andric          << "  Retired: " << RetiredMOps;
240691bc56edSDimitry Andric   dbgs() << "\n  Executed: " << getExecutedCount() / LFactor << "c";
240791bc56edSDimitry Andric   dbgs() << "\n  Critical: " << ResCount / LFactor << "c, "
240891bc56edSDimitry Andric          << ResCount / ResFactor << " "
240991bc56edSDimitry Andric          << SchedModel->getResourceName(ZoneCritResIdx)
241091bc56edSDimitry Andric          << "\n  ExpectedLatency: " << ExpectedLatency << "c\n"
241191bc56edSDimitry Andric          << (IsResourceLimited ? "  - Resource" : "  - Latency")
241291bc56edSDimitry Andric          << " limited.\n";
241391bc56edSDimitry Andric }
241491bc56edSDimitry Andric #endif
241591bc56edSDimitry Andric 
241691bc56edSDimitry Andric //===----------------------------------------------------------------------===//
241791bc56edSDimitry Andric // GenericScheduler - Generic implementation of MachineSchedStrategy.
241891bc56edSDimitry Andric //===----------------------------------------------------------------------===//
241991bc56edSDimitry Andric 
242091bc56edSDimitry Andric void GenericSchedulerBase::SchedCandidate::
initResourceDelta(const ScheduleDAGMI * DAG,const TargetSchedModel * SchedModel)242191bc56edSDimitry Andric initResourceDelta(const ScheduleDAGMI *DAG,
242291bc56edSDimitry Andric                   const TargetSchedModel *SchedModel) {
242391bc56edSDimitry Andric   if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
242491bc56edSDimitry Andric     return;
242591bc56edSDimitry Andric 
242691bc56edSDimitry Andric   const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
242791bc56edSDimitry Andric   for (TargetSchedModel::ProcResIter
242891bc56edSDimitry Andric          PI = SchedModel->getWriteProcResBegin(SC),
242991bc56edSDimitry Andric          PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
243091bc56edSDimitry Andric     if (PI->ProcResourceIdx == Policy.ReduceResIdx)
243191bc56edSDimitry Andric       ResDelta.CritResources += PI->Cycles;
243291bc56edSDimitry Andric     if (PI->ProcResourceIdx == Policy.DemandResIdx)
243391bc56edSDimitry Andric       ResDelta.DemandedResources += PI->Cycles;
243491bc56edSDimitry Andric   }
243591bc56edSDimitry Andric }
243691bc56edSDimitry Andric 
2437*b5893f02SDimitry Andric /// Compute remaining latency. We need this both to determine whether the
2438*b5893f02SDimitry Andric /// overall schedule has become latency-limited and whether the instructions
2439*b5893f02SDimitry Andric /// outside this zone are resource or latency limited.
2440*b5893f02SDimitry Andric ///
2441*b5893f02SDimitry Andric /// The "dependent" latency is updated incrementally during scheduling as the
2442*b5893f02SDimitry Andric /// max height/depth of scheduled nodes minus the cycles since it was
2443*b5893f02SDimitry Andric /// scheduled:
2444*b5893f02SDimitry Andric ///   DLat = max (N.depth - (CurrCycle - N.ReadyCycle) for N in Zone
2445*b5893f02SDimitry Andric ///
2446*b5893f02SDimitry Andric /// The "independent" latency is the max ready queue depth:
2447*b5893f02SDimitry Andric ///   ILat = max N.depth for N in Available|Pending
2448*b5893f02SDimitry Andric ///
2449*b5893f02SDimitry Andric /// RemainingLatency is the greater of independent and dependent latency.
2450*b5893f02SDimitry Andric ///
2451*b5893f02SDimitry Andric /// These computations are expensive, especially in DAGs with many edges, so
2452*b5893f02SDimitry Andric /// only do them if necessary.
computeRemLatency(SchedBoundary & CurrZone)2453*b5893f02SDimitry Andric static unsigned computeRemLatency(SchedBoundary &CurrZone) {
2454*b5893f02SDimitry Andric   unsigned RemLatency = CurrZone.getDependentLatency();
2455*b5893f02SDimitry Andric   RemLatency = std::max(RemLatency,
2456*b5893f02SDimitry Andric                         CurrZone.findMaxLatency(CurrZone.Available.elements()));
2457*b5893f02SDimitry Andric   RemLatency = std::max(RemLatency,
2458*b5893f02SDimitry Andric                         CurrZone.findMaxLatency(CurrZone.Pending.elements()));
2459*b5893f02SDimitry Andric   return RemLatency;
2460*b5893f02SDimitry Andric }
2461*b5893f02SDimitry Andric 
2462*b5893f02SDimitry Andric /// Returns true if the current cycle plus remaning latency is greater than
2463*b5893f02SDimitry Andric /// the critical path in the scheduling region.
shouldReduceLatency(const CandPolicy & Policy,SchedBoundary & CurrZone,bool ComputeRemLatency,unsigned & RemLatency) const2464*b5893f02SDimitry Andric bool GenericSchedulerBase::shouldReduceLatency(const CandPolicy &Policy,
2465*b5893f02SDimitry Andric                                                SchedBoundary &CurrZone,
2466*b5893f02SDimitry Andric                                                bool ComputeRemLatency,
2467*b5893f02SDimitry Andric                                                unsigned &RemLatency) const {
2468*b5893f02SDimitry Andric   // The current cycle is already greater than the critical path, so we are
2469*b5893f02SDimitry Andric   // already latency limited and don't need to compute the remaining latency.
2470*b5893f02SDimitry Andric   if (CurrZone.getCurrCycle() > Rem.CriticalPath)
2471*b5893f02SDimitry Andric     return true;
2472*b5893f02SDimitry Andric 
2473*b5893f02SDimitry Andric   // If we haven't scheduled anything yet, then we aren't latency limited.
2474*b5893f02SDimitry Andric   if (CurrZone.getCurrCycle() == 0)
2475*b5893f02SDimitry Andric     return false;
2476*b5893f02SDimitry Andric 
2477*b5893f02SDimitry Andric   if (ComputeRemLatency)
2478*b5893f02SDimitry Andric     RemLatency = computeRemLatency(CurrZone);
2479*b5893f02SDimitry Andric 
2480*b5893f02SDimitry Andric   return RemLatency + CurrZone.getCurrCycle() > Rem.CriticalPath;
2481*b5893f02SDimitry Andric }
2482*b5893f02SDimitry Andric 
248391bc56edSDimitry Andric /// Set the CandPolicy given a scheduling zone given the current resources and
248491bc56edSDimitry Andric /// latencies inside and outside the zone.
setPolicy(CandPolicy & Policy,bool IsPostRA,SchedBoundary & CurrZone,SchedBoundary * OtherZone)24853ca95b02SDimitry Andric void GenericSchedulerBase::setPolicy(CandPolicy &Policy, bool IsPostRA,
248691bc56edSDimitry Andric                                      SchedBoundary &CurrZone,
248791bc56edSDimitry Andric                                      SchedBoundary *OtherZone) {
24888f0fd8f6SDimitry Andric   // Apply preemptive heuristics based on the total latency and resources
248991bc56edSDimitry Andric   // inside and outside this zone. Potential stalls should be considered before
249091bc56edSDimitry Andric   // following this policy.
249191bc56edSDimitry Andric 
249291bc56edSDimitry Andric   // Compute the critical resource outside the zone.
249391bc56edSDimitry Andric   unsigned OtherCritIdx = 0;
249491bc56edSDimitry Andric   unsigned OtherCount =
249591bc56edSDimitry Andric     OtherZone ? OtherZone->getOtherResourceCount(OtherCritIdx) : 0;
249691bc56edSDimitry Andric 
249791bc56edSDimitry Andric   bool OtherResLimited = false;
2498*b5893f02SDimitry Andric   unsigned RemLatency = 0;
2499*b5893f02SDimitry Andric   bool RemLatencyComputed = false;
2500*b5893f02SDimitry Andric   if (SchedModel->hasInstrSchedModel() && OtherCount != 0) {
2501*b5893f02SDimitry Andric     RemLatency = computeRemLatency(CurrZone);
2502*b5893f02SDimitry Andric     RemLatencyComputed = true;
25032cab237bSDimitry Andric     OtherResLimited = checkResourceLimit(SchedModel->getLatencyFactor(),
25042cab237bSDimitry Andric                                          OtherCount, RemLatency);
2505*b5893f02SDimitry Andric   }
25062cab237bSDimitry Andric 
250791bc56edSDimitry Andric   // Schedule aggressively for latency in PostRA mode. We don't check for
250891bc56edSDimitry Andric   // acyclic latency during PostRA, and highly out-of-order processors will
250991bc56edSDimitry Andric   // skip PostRA scheduling.
2510*b5893f02SDimitry Andric   if (!OtherResLimited &&
2511*b5893f02SDimitry Andric       (IsPostRA || shouldReduceLatency(Policy, CurrZone, !RemLatencyComputed,
2512*b5893f02SDimitry Andric                                        RemLatency))) {
251391bc56edSDimitry Andric     Policy.ReduceLatency |= true;
25144ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "  " << CurrZone.Available.getName()
251591bc56edSDimitry Andric                       << " RemainingLatency " << RemLatency << " + "
251691bc56edSDimitry Andric                       << CurrZone.getCurrCycle() << "c > CritPath "
251791bc56edSDimitry Andric                       << Rem.CriticalPath << "\n");
251891bc56edSDimitry Andric   }
251991bc56edSDimitry Andric   // If the same resource is limiting inside and outside the zone, do nothing.
252091bc56edSDimitry Andric   if (CurrZone.getZoneCritResIdx() == OtherCritIdx)
252191bc56edSDimitry Andric     return;
252291bc56edSDimitry Andric 
25234ba319b5SDimitry Andric   LLVM_DEBUG(if (CurrZone.isResourceLimited()) {
252491bc56edSDimitry Andric     dbgs() << "  " << CurrZone.Available.getName() << " ResourceLimited: "
25254ba319b5SDimitry Andric            << SchedModel->getResourceName(CurrZone.getZoneCritResIdx()) << "\n";
25264ba319b5SDimitry Andric   } if (OtherResLimited) dbgs()
25274ba319b5SDimitry Andric                  << "  RemainingLimit: "
252891bc56edSDimitry Andric                  << SchedModel->getResourceName(OtherCritIdx) << "\n";
25294ba319b5SDimitry Andric              if (!CurrZone.isResourceLimited() && !OtherResLimited) dbgs()
25304ba319b5SDimitry Andric              << "  Latency limited both directions.\n");
253191bc56edSDimitry Andric 
253291bc56edSDimitry Andric   if (CurrZone.isResourceLimited() && !Policy.ReduceResIdx)
253391bc56edSDimitry Andric     Policy.ReduceResIdx = CurrZone.getZoneCritResIdx();
253491bc56edSDimitry Andric 
253591bc56edSDimitry Andric   if (OtherResLimited)
253691bc56edSDimitry Andric     Policy.DemandResIdx = OtherCritIdx;
253791bc56edSDimitry Andric }
253891bc56edSDimitry Andric 
253991bc56edSDimitry Andric #ifndef NDEBUG
getReasonStr(GenericSchedulerBase::CandReason Reason)254091bc56edSDimitry Andric const char *GenericSchedulerBase::getReasonStr(
254191bc56edSDimitry Andric   GenericSchedulerBase::CandReason Reason) {
254291bc56edSDimitry Andric   switch (Reason) {
254391bc56edSDimitry Andric   case NoCand:         return "NOCAND    ";
25443ca95b02SDimitry Andric   case Only1:          return "ONLY1     ";
2545*b5893f02SDimitry Andric   case PhysReg:        return "PHYS-REG  ";
254691bc56edSDimitry Andric   case RegExcess:      return "REG-EXCESS";
254791bc56edSDimitry Andric   case RegCritical:    return "REG-CRIT  ";
254891bc56edSDimitry Andric   case Stall:          return "STALL     ";
254991bc56edSDimitry Andric   case Cluster:        return "CLUSTER   ";
255091bc56edSDimitry Andric   case Weak:           return "WEAK      ";
255191bc56edSDimitry Andric   case RegMax:         return "REG-MAX   ";
255291bc56edSDimitry Andric   case ResourceReduce: return "RES-REDUCE";
255391bc56edSDimitry Andric   case ResourceDemand: return "RES-DEMAND";
255491bc56edSDimitry Andric   case TopDepthReduce: return "TOP-DEPTH ";
255591bc56edSDimitry Andric   case TopPathReduce:  return "TOP-PATH  ";
255691bc56edSDimitry Andric   case BotHeightReduce:return "BOT-HEIGHT";
255791bc56edSDimitry Andric   case BotPathReduce:  return "BOT-PATH  ";
255891bc56edSDimitry Andric   case NextDefUse:     return "DEF-USE   ";
255991bc56edSDimitry Andric   case NodeOrder:      return "ORDER     ";
256091bc56edSDimitry Andric   };
256191bc56edSDimitry Andric   llvm_unreachable("Unknown reason!");
256291bc56edSDimitry Andric }
256391bc56edSDimitry Andric 
traceCandidate(const SchedCandidate & Cand)256491bc56edSDimitry Andric void GenericSchedulerBase::traceCandidate(const SchedCandidate &Cand) {
256591bc56edSDimitry Andric   PressureChange P;
256691bc56edSDimitry Andric   unsigned ResIdx = 0;
256791bc56edSDimitry Andric   unsigned Latency = 0;
256891bc56edSDimitry Andric   switch (Cand.Reason) {
256991bc56edSDimitry Andric   default:
257091bc56edSDimitry Andric     break;
257191bc56edSDimitry Andric   case RegExcess:
257291bc56edSDimitry Andric     P = Cand.RPDelta.Excess;
257391bc56edSDimitry Andric     break;
257491bc56edSDimitry Andric   case RegCritical:
257591bc56edSDimitry Andric     P = Cand.RPDelta.CriticalMax;
257691bc56edSDimitry Andric     break;
257791bc56edSDimitry Andric   case RegMax:
257891bc56edSDimitry Andric     P = Cand.RPDelta.CurrentMax;
257991bc56edSDimitry Andric     break;
258091bc56edSDimitry Andric   case ResourceReduce:
258191bc56edSDimitry Andric     ResIdx = Cand.Policy.ReduceResIdx;
258291bc56edSDimitry Andric     break;
258391bc56edSDimitry Andric   case ResourceDemand:
258491bc56edSDimitry Andric     ResIdx = Cand.Policy.DemandResIdx;
258591bc56edSDimitry Andric     break;
258691bc56edSDimitry Andric   case TopDepthReduce:
258791bc56edSDimitry Andric     Latency = Cand.SU->getDepth();
258891bc56edSDimitry Andric     break;
258991bc56edSDimitry Andric   case TopPathReduce:
259091bc56edSDimitry Andric     Latency = Cand.SU->getHeight();
259191bc56edSDimitry Andric     break;
259291bc56edSDimitry Andric   case BotHeightReduce:
259391bc56edSDimitry Andric     Latency = Cand.SU->getHeight();
259491bc56edSDimitry Andric     break;
259591bc56edSDimitry Andric   case BotPathReduce:
259691bc56edSDimitry Andric     Latency = Cand.SU->getDepth();
259791bc56edSDimitry Andric     break;
259891bc56edSDimitry Andric   }
25997d523365SDimitry Andric   dbgs() << "  Cand SU(" << Cand.SU->NodeNum << ") " << getReasonStr(Cand.Reason);
260091bc56edSDimitry Andric   if (P.isValid())
260191bc56edSDimitry Andric     dbgs() << " " << TRI->getRegPressureSetName(P.getPSet())
260291bc56edSDimitry Andric            << ":" << P.getUnitInc() << " ";
260391bc56edSDimitry Andric   else
260491bc56edSDimitry Andric     dbgs() << "      ";
260591bc56edSDimitry Andric   if (ResIdx)
260691bc56edSDimitry Andric     dbgs() << " " << SchedModel->getProcResource(ResIdx)->Name << " ";
260791bc56edSDimitry Andric   else
260891bc56edSDimitry Andric     dbgs() << "         ";
260991bc56edSDimitry Andric   if (Latency)
261091bc56edSDimitry Andric     dbgs() << " " << Latency << " cycles ";
261191bc56edSDimitry Andric   else
261291bc56edSDimitry Andric     dbgs() << "          ";
261391bc56edSDimitry Andric   dbgs() << '\n';
261491bc56edSDimitry Andric }
261591bc56edSDimitry Andric #endif
261691bc56edSDimitry Andric 
26174ba319b5SDimitry Andric namespace llvm {
261891bc56edSDimitry Andric /// Return true if this heuristic determines order.
tryLess(int TryVal,int CandVal,GenericSchedulerBase::SchedCandidate & TryCand,GenericSchedulerBase::SchedCandidate & Cand,GenericSchedulerBase::CandReason Reason)26194ba319b5SDimitry Andric bool tryLess(int TryVal, int CandVal,
262091bc56edSDimitry Andric              GenericSchedulerBase::SchedCandidate &TryCand,
262191bc56edSDimitry Andric              GenericSchedulerBase::SchedCandidate &Cand,
262291bc56edSDimitry Andric              GenericSchedulerBase::CandReason Reason) {
262391bc56edSDimitry Andric   if (TryVal < CandVal) {
262491bc56edSDimitry Andric     TryCand.Reason = Reason;
262591bc56edSDimitry Andric     return true;
262691bc56edSDimitry Andric   }
262791bc56edSDimitry Andric   if (TryVal > CandVal) {
262891bc56edSDimitry Andric     if (Cand.Reason > Reason)
262991bc56edSDimitry Andric       Cand.Reason = Reason;
263091bc56edSDimitry Andric     return true;
263191bc56edSDimitry Andric   }
263291bc56edSDimitry Andric   return false;
263391bc56edSDimitry Andric }
263491bc56edSDimitry Andric 
tryGreater(int TryVal,int CandVal,GenericSchedulerBase::SchedCandidate & TryCand,GenericSchedulerBase::SchedCandidate & Cand,GenericSchedulerBase::CandReason Reason)26354ba319b5SDimitry Andric bool tryGreater(int TryVal, int CandVal,
263691bc56edSDimitry Andric                 GenericSchedulerBase::SchedCandidate &TryCand,
263791bc56edSDimitry Andric                 GenericSchedulerBase::SchedCandidate &Cand,
263891bc56edSDimitry Andric                 GenericSchedulerBase::CandReason Reason) {
263991bc56edSDimitry Andric   if (TryVal > CandVal) {
264091bc56edSDimitry Andric     TryCand.Reason = Reason;
264191bc56edSDimitry Andric     return true;
264291bc56edSDimitry Andric   }
264391bc56edSDimitry Andric   if (TryVal < CandVal) {
264491bc56edSDimitry Andric     if (Cand.Reason > Reason)
264591bc56edSDimitry Andric       Cand.Reason = Reason;
264691bc56edSDimitry Andric     return true;
264791bc56edSDimitry Andric   }
264891bc56edSDimitry Andric   return false;
264991bc56edSDimitry Andric }
265091bc56edSDimitry Andric 
tryLatency(GenericSchedulerBase::SchedCandidate & TryCand,GenericSchedulerBase::SchedCandidate & Cand,SchedBoundary & Zone)26514ba319b5SDimitry Andric bool tryLatency(GenericSchedulerBase::SchedCandidate &TryCand,
265291bc56edSDimitry Andric                 GenericSchedulerBase::SchedCandidate &Cand,
265391bc56edSDimitry Andric                 SchedBoundary &Zone) {
265491bc56edSDimitry Andric   if (Zone.isTop()) {
265591bc56edSDimitry Andric     if (Cand.SU->getDepth() > Zone.getScheduledLatency()) {
265691bc56edSDimitry Andric       if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
265791bc56edSDimitry Andric                   TryCand, Cand, GenericSchedulerBase::TopDepthReduce))
265891bc56edSDimitry Andric         return true;
265991bc56edSDimitry Andric     }
266091bc56edSDimitry Andric     if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
266191bc56edSDimitry Andric                    TryCand, Cand, GenericSchedulerBase::TopPathReduce))
266291bc56edSDimitry Andric       return true;
26633ca95b02SDimitry Andric   } else {
266491bc56edSDimitry Andric     if (Cand.SU->getHeight() > Zone.getScheduledLatency()) {
266591bc56edSDimitry Andric       if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
266691bc56edSDimitry Andric                   TryCand, Cand, GenericSchedulerBase::BotHeightReduce))
266791bc56edSDimitry Andric         return true;
266891bc56edSDimitry Andric     }
266991bc56edSDimitry Andric     if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
267091bc56edSDimitry Andric                    TryCand, Cand, GenericSchedulerBase::BotPathReduce))
267191bc56edSDimitry Andric       return true;
267291bc56edSDimitry Andric   }
267391bc56edSDimitry Andric   return false;
267491bc56edSDimitry Andric }
26754ba319b5SDimitry Andric } // end namespace llvm
267691bc56edSDimitry Andric 
tracePick(GenericSchedulerBase::CandReason Reason,bool IsTop)26773ca95b02SDimitry Andric static void tracePick(GenericSchedulerBase::CandReason Reason, bool IsTop) {
26784ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Pick " << (IsTop ? "Top " : "Bot ")
26793ca95b02SDimitry Andric                     << GenericSchedulerBase::getReasonStr(Reason) << '\n');
26803ca95b02SDimitry Andric }
26813ca95b02SDimitry Andric 
tracePick(const GenericSchedulerBase::SchedCandidate & Cand)26823ca95b02SDimitry Andric static void tracePick(const GenericSchedulerBase::SchedCandidate &Cand) {
26833ca95b02SDimitry Andric   tracePick(Cand.Reason, Cand.AtTop);
268491bc56edSDimitry Andric }
268591bc56edSDimitry Andric 
initialize(ScheduleDAGMI * dag)268691bc56edSDimitry Andric void GenericScheduler::initialize(ScheduleDAGMI *dag) {
268791bc56edSDimitry Andric   assert(dag->hasVRegLiveness() &&
268891bc56edSDimitry Andric          "(PreRA)GenericScheduler needs vreg liveness");
268991bc56edSDimitry Andric   DAG = static_cast<ScheduleDAGMILive*>(dag);
269091bc56edSDimitry Andric   SchedModel = DAG->getSchedModel();
269191bc56edSDimitry Andric   TRI = DAG->TRI;
269291bc56edSDimitry Andric 
269391bc56edSDimitry Andric   Rem.init(DAG, SchedModel);
269491bc56edSDimitry Andric   Top.init(DAG, SchedModel, &Rem);
269591bc56edSDimitry Andric   Bot.init(DAG, SchedModel, &Rem);
269691bc56edSDimitry Andric 
269791bc56edSDimitry Andric   // Initialize resource counts.
269891bc56edSDimitry Andric 
269991bc56edSDimitry Andric   // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
270091bc56edSDimitry Andric   // are disabled, then these HazardRecs will be disabled.
270191bc56edSDimitry Andric   const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
270291bc56edSDimitry Andric   if (!Top.HazardRec) {
270391bc56edSDimitry Andric     Top.HazardRec =
270439d628a0SDimitry Andric         DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
270539d628a0SDimitry Andric             Itin, DAG);
270691bc56edSDimitry Andric   }
270791bc56edSDimitry Andric   if (!Bot.HazardRec) {
270891bc56edSDimitry Andric     Bot.HazardRec =
270939d628a0SDimitry Andric         DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
271039d628a0SDimitry Andric             Itin, DAG);
271191bc56edSDimitry Andric   }
27123ca95b02SDimitry Andric   TopCand.SU = nullptr;
27133ca95b02SDimitry Andric   BotCand.SU = nullptr;
27143861d79fSDimitry Andric }
27153861d79fSDimitry Andric 
2716f785676fSDimitry Andric /// Initialize the per-region scheduling policy.
initPolicy(MachineBasicBlock::iterator Begin,MachineBasicBlock::iterator End,unsigned NumRegionInstrs)2717f785676fSDimitry Andric void GenericScheduler::initPolicy(MachineBasicBlock::iterator Begin,
2718f785676fSDimitry Andric                                   MachineBasicBlock::iterator End,
2719f785676fSDimitry Andric                                   unsigned NumRegionInstrs) {
27202cab237bSDimitry Andric   const MachineFunction &MF = *Begin->getMF();
272139d628a0SDimitry Andric   const TargetLowering *TLI = MF.getSubtarget().getTargetLowering();
2722f785676fSDimitry Andric 
2723f785676fSDimitry Andric   // Avoid setting up the register pressure tracker for small regions to save
2724f785676fSDimitry Andric   // compile time. As a rough heuristic, only track pressure when the number of
2725f785676fSDimitry Andric   // schedulable instructions exceeds half the integer register file.
272691bc56edSDimitry Andric   RegionPolicy.ShouldTrackPressure = true;
272791bc56edSDimitry Andric   for (unsigned VT = MVT::i32; VT > (unsigned)MVT::i1; --VT) {
272891bc56edSDimitry Andric     MVT::SimpleValueType LegalIntVT = (MVT::SimpleValueType)VT;
272991bc56edSDimitry Andric     if (TLI->isTypeLegal(LegalIntVT)) {
2730f785676fSDimitry Andric       unsigned NIntRegs = Context->RegClassInfo->getNumAllocatableRegs(
273191bc56edSDimitry Andric         TLI->getRegClassFor(LegalIntVT));
2732f785676fSDimitry Andric       RegionPolicy.ShouldTrackPressure = NumRegionInstrs > (NIntRegs / 2);
273391bc56edSDimitry Andric     }
273491bc56edSDimitry Andric   }
2735f785676fSDimitry Andric 
2736f785676fSDimitry Andric   // For generic targets, we default to bottom-up, because it's simpler and more
2737f785676fSDimitry Andric   // compile-time optimizations have been implemented in that direction.
2738f785676fSDimitry Andric   RegionPolicy.OnlyBottomUp = true;
2739f785676fSDimitry Andric 
2740f785676fSDimitry Andric   // Allow the subtarget to override default policy.
27413ca95b02SDimitry Andric   MF.getSubtarget().overrideSchedPolicy(RegionPolicy, NumRegionInstrs);
2742f785676fSDimitry Andric 
2743f785676fSDimitry Andric   // After subtarget overrides, apply command line options.
2744f785676fSDimitry Andric   if (!EnableRegPressure)
2745f785676fSDimitry Andric     RegionPolicy.ShouldTrackPressure = false;
2746f785676fSDimitry Andric 
2747f785676fSDimitry Andric   // Check -misched-topdown/bottomup can force or unforce scheduling direction.
2748f785676fSDimitry Andric   // e.g. -misched-bottomup=false allows scheduling in both directions.
2749f785676fSDimitry Andric   assert((!ForceTopDown || !ForceBottomUp) &&
2750f785676fSDimitry Andric          "-misched-topdown incompatible with -misched-bottomup");
2751f785676fSDimitry Andric   if (ForceBottomUp.getNumOccurrences() > 0) {
2752f785676fSDimitry Andric     RegionPolicy.OnlyBottomUp = ForceBottomUp;
2753f785676fSDimitry Andric     if (RegionPolicy.OnlyBottomUp)
2754f785676fSDimitry Andric       RegionPolicy.OnlyTopDown = false;
2755f785676fSDimitry Andric   }
2756f785676fSDimitry Andric   if (ForceTopDown.getNumOccurrences() > 0) {
2757f785676fSDimitry Andric     RegionPolicy.OnlyTopDown = ForceTopDown;
2758f785676fSDimitry Andric     if (RegionPolicy.OnlyTopDown)
2759f785676fSDimitry Andric       RegionPolicy.OnlyBottomUp = false;
2760f785676fSDimitry Andric   }
2761f785676fSDimitry Andric }
2762f785676fSDimitry Andric 
dumpPolicy() const2763edd7eaddSDimitry Andric void GenericScheduler::dumpPolicy() const {
27647a7e6055SDimitry Andric   // Cannot completely remove virtual function even in release mode.
27657a7e6055SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
27667d523365SDimitry Andric   dbgs() << "GenericScheduler RegionPolicy: "
27677d523365SDimitry Andric          << " ShouldTrackPressure=" << RegionPolicy.ShouldTrackPressure
27687d523365SDimitry Andric          << " OnlyTopDown=" << RegionPolicy.OnlyTopDown
27697d523365SDimitry Andric          << " OnlyBottomUp=" << RegionPolicy.OnlyBottomUp
27707d523365SDimitry Andric          << "\n";
27717a7e6055SDimitry Andric #endif
27727d523365SDimitry Andric }
27737d523365SDimitry Andric 
2774f785676fSDimitry Andric /// Set IsAcyclicLatencyLimited if the acyclic path is longer than the cyclic
2775f785676fSDimitry Andric /// critical path by more cycles than it takes to drain the instruction buffer.
2776f785676fSDimitry Andric /// We estimate an upper bounds on in-flight instructions as:
2777f785676fSDimitry Andric ///
2778f785676fSDimitry Andric /// CyclesPerIteration = max( CyclicPath, Loop-Resource-Height )
2779f785676fSDimitry Andric /// InFlightIterations = AcyclicPath / CyclesPerIteration
2780f785676fSDimitry Andric /// InFlightResources = InFlightIterations * LoopResources
2781f785676fSDimitry Andric ///
2782f785676fSDimitry Andric /// TODO: Check execution resources in addition to IssueCount.
checkAcyclicLatency()2783f785676fSDimitry Andric void GenericScheduler::checkAcyclicLatency() {
2784f785676fSDimitry Andric   if (Rem.CyclicCritPath == 0 || Rem.CyclicCritPath >= Rem.CriticalPath)
2785f785676fSDimitry Andric     return;
2786f785676fSDimitry Andric 
2787f785676fSDimitry Andric   // Scaled number of cycles per loop iteration.
2788f785676fSDimitry Andric   unsigned IterCount =
2789f785676fSDimitry Andric     std::max(Rem.CyclicCritPath * SchedModel->getLatencyFactor(),
2790f785676fSDimitry Andric              Rem.RemIssueCount);
2791f785676fSDimitry Andric   // Scaled acyclic critical path.
2792f785676fSDimitry Andric   unsigned AcyclicCount = Rem.CriticalPath * SchedModel->getLatencyFactor();
2793f785676fSDimitry Andric   // InFlightCount = (AcyclicPath / IterCycles) * InstrPerLoop
2794f785676fSDimitry Andric   unsigned InFlightCount =
2795f785676fSDimitry Andric     (AcyclicCount * Rem.RemIssueCount + IterCount-1) / IterCount;
2796f785676fSDimitry Andric   unsigned BufferLimit =
2797f785676fSDimitry Andric     SchedModel->getMicroOpBufferSize() * SchedModel->getMicroOpFactor();
2798f785676fSDimitry Andric 
2799f785676fSDimitry Andric   Rem.IsAcyclicLatencyLimited = InFlightCount > BufferLimit;
2800f785676fSDimitry Andric 
28014ba319b5SDimitry Andric   LLVM_DEBUG(
28024ba319b5SDimitry Andric       dbgs() << "IssueCycles="
2803f785676fSDimitry Andric              << Rem.RemIssueCount / SchedModel->getLatencyFactor() << "c "
2804f785676fSDimitry Andric              << "IterCycles=" << IterCount / SchedModel->getLatencyFactor()
2805f785676fSDimitry Andric              << "c NumIters=" << (AcyclicCount + IterCount - 1) / IterCount
2806f785676fSDimitry Andric              << " InFlight=" << InFlightCount / SchedModel->getMicroOpFactor()
2807f785676fSDimitry Andric              << "m BufferLim=" << SchedModel->getMicroOpBufferSize() << "m\n";
28084ba319b5SDimitry Andric       if (Rem.IsAcyclicLatencyLimited) dbgs() << "  ACYCLIC LATENCY LIMIT\n");
2809f785676fSDimitry Andric }
2810f785676fSDimitry Andric 
registerRoots()2811f785676fSDimitry Andric void GenericScheduler::registerRoots() {
28123861d79fSDimitry Andric   Rem.CriticalPath = DAG->ExitSU.getDepth();
2813f785676fSDimitry Andric 
28143861d79fSDimitry Andric   // Some roots may not feed into ExitSU. Check all of them in case.
2815edd7eaddSDimitry Andric   for (const SUnit *SU : Bot.Available) {
2816edd7eaddSDimitry Andric     if (SU->getDepth() > Rem.CriticalPath)
2817edd7eaddSDimitry Andric       Rem.CriticalPath = SU->getDepth();
28183861d79fSDimitry Andric   }
28194ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << '\n');
282039d628a0SDimitry Andric   if (DumpCriticalPathLength) {
282139d628a0SDimitry Andric     errs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << " \n";
282239d628a0SDimitry Andric   }
2823f785676fSDimitry Andric 
28247a7e6055SDimitry Andric   if (EnableCyclicPath && SchedModel->getMicroOpBufferSize() > 0) {
2825f785676fSDimitry Andric     Rem.CyclicCritPath = DAG->computeCyclicCriticalPath();
2826f785676fSDimitry Andric     checkAcyclicLatency();
2827f785676fSDimitry Andric   }
28283861d79fSDimitry Andric }
28293861d79fSDimitry Andric 
28304ba319b5SDimitry Andric namespace llvm {
tryPressure(const PressureChange & TryP,const PressureChange & CandP,GenericSchedulerBase::SchedCandidate & TryCand,GenericSchedulerBase::SchedCandidate & Cand,GenericSchedulerBase::CandReason Reason,const TargetRegisterInfo * TRI,const MachineFunction & MF)28314ba319b5SDimitry Andric bool tryPressure(const PressureChange &TryP,
2832f785676fSDimitry Andric                  const PressureChange &CandP,
283391bc56edSDimitry Andric                  GenericSchedulerBase::SchedCandidate &TryCand,
283491bc56edSDimitry Andric                  GenericSchedulerBase::SchedCandidate &Cand,
28357d523365SDimitry Andric                  GenericSchedulerBase::CandReason Reason,
28367d523365SDimitry Andric                  const TargetRegisterInfo *TRI,
28377d523365SDimitry Andric                  const MachineFunction &MF) {
2838f785676fSDimitry Andric   // If one candidate decreases and the other increases, go with it.
2839f785676fSDimitry Andric   // Invalid candidates have UnitInc==0.
284039d628a0SDimitry Andric   if (tryGreater(TryP.getUnitInc() < 0, CandP.getUnitInc() < 0, TryCand, Cand,
2841f785676fSDimitry Andric                  Reason)) {
2842f785676fSDimitry Andric     return true;
2843f785676fSDimitry Andric   }
28443ca95b02SDimitry Andric   // Do not compare the magnitude of pressure changes between top and bottom
28453ca95b02SDimitry Andric   // boundary.
28463ca95b02SDimitry Andric   if (Cand.AtTop != TryCand.AtTop)
28473ca95b02SDimitry Andric     return false;
28483ca95b02SDimitry Andric 
28493ca95b02SDimitry Andric   // If both candidates affect the same set in the same boundary, go with the
28503ca95b02SDimitry Andric   // smallest increase.
28513ca95b02SDimitry Andric   unsigned TryPSet = TryP.getPSetOrMax();
28523ca95b02SDimitry Andric   unsigned CandPSet = CandP.getPSetOrMax();
28533ca95b02SDimitry Andric   if (TryPSet == CandPSet) {
28543ca95b02SDimitry Andric     return tryLess(TryP.getUnitInc(), CandP.getUnitInc(), TryCand, Cand,
28553ca95b02SDimitry Andric                    Reason);
28563ca95b02SDimitry Andric   }
28577d523365SDimitry Andric 
28587d523365SDimitry Andric   int TryRank = TryP.isValid() ? TRI->getRegPressureSetScore(MF, TryPSet) :
28597d523365SDimitry Andric                                  std::numeric_limits<int>::max();
28607d523365SDimitry Andric 
28617d523365SDimitry Andric   int CandRank = CandP.isValid() ? TRI->getRegPressureSetScore(MF, CandPSet) :
28627d523365SDimitry Andric                                    std::numeric_limits<int>::max();
28637d523365SDimitry Andric 
2864f785676fSDimitry Andric   // If the candidates are decreasing pressure, reverse priority.
2865f785676fSDimitry Andric   if (TryP.getUnitInc() < 0)
2866f785676fSDimitry Andric     std::swap(TryRank, CandRank);
2867f785676fSDimitry Andric   return tryGreater(TryRank, CandRank, TryCand, Cand, Reason);
2868f785676fSDimitry Andric }
2869f785676fSDimitry Andric 
getWeakLeft(const SUnit * SU,bool isTop)28704ba319b5SDimitry Andric unsigned getWeakLeft(const SUnit *SU, bool isTop) {
2871139f7f9bSDimitry Andric   return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
2872139f7f9bSDimitry Andric }
2873139f7f9bSDimitry Andric 
2874284c1978SDimitry Andric /// Minimize physical register live ranges. Regalloc wants them adjacent to
2875284c1978SDimitry Andric /// their physreg def/use.
2876284c1978SDimitry Andric ///
2877284c1978SDimitry Andric /// FIXME: This is an unnecessary check on the critical path. Most are root/leaf
2878284c1978SDimitry Andric /// copies which can be prescheduled. The rest (e.g. x86 MUL) could be bundled
2879284c1978SDimitry Andric /// with the operation that produces or consumes the physreg. We'll do this when
2880284c1978SDimitry Andric /// regalloc has support for parallel copies.
biasPhysReg(const SUnit * SU,bool isTop)2881*b5893f02SDimitry Andric int biasPhysReg(const SUnit *SU, bool isTop) {
2882284c1978SDimitry Andric   const MachineInstr *MI = SU->getInstr();
2883284c1978SDimitry Andric 
2884*b5893f02SDimitry Andric   if (MI->isCopy()) {
2885284c1978SDimitry Andric     unsigned ScheduledOper = isTop ? 1 : 0;
2886284c1978SDimitry Andric     unsigned UnscheduledOper = isTop ? 0 : 1;
2887284c1978SDimitry Andric     // If we have already scheduled the physreg produce/consumer, immediately
2888284c1978SDimitry Andric     // schedule the copy.
2889284c1978SDimitry Andric     if (TargetRegisterInfo::isPhysicalRegister(
2890284c1978SDimitry Andric             MI->getOperand(ScheduledOper).getReg()))
2891284c1978SDimitry Andric       return 1;
2892284c1978SDimitry Andric     // If the physreg is at the boundary, defer it. Otherwise schedule it
2893284c1978SDimitry Andric     // immediately to free the dependent. We can hoist the copy later.
2894284c1978SDimitry Andric     bool AtBoundary = isTop ? !SU->NumSuccsLeft : !SU->NumPredsLeft;
2895284c1978SDimitry Andric     if (TargetRegisterInfo::isPhysicalRegister(
2896284c1978SDimitry Andric             MI->getOperand(UnscheduledOper).getReg()))
2897284c1978SDimitry Andric       return AtBoundary ? -1 : 1;
2898*b5893f02SDimitry Andric   }
2899*b5893f02SDimitry Andric 
2900*b5893f02SDimitry Andric   if (MI->isMoveImmediate()) {
2901*b5893f02SDimitry Andric     // If we have a move immediate and all successors have been assigned, bias
2902*b5893f02SDimitry Andric     // towards scheduling this later. Make sure all register defs are to
2903*b5893f02SDimitry Andric     // physical registers.
2904*b5893f02SDimitry Andric     bool DoBias = true;
2905*b5893f02SDimitry Andric     for (const MachineOperand &Op : MI->defs()) {
2906*b5893f02SDimitry Andric       if (Op.isReg() && !TargetRegisterInfo::isPhysicalRegister(Op.getReg())) {
2907*b5893f02SDimitry Andric         DoBias = false;
2908*b5893f02SDimitry Andric         break;
2909*b5893f02SDimitry Andric       }
2910*b5893f02SDimitry Andric     }
2911*b5893f02SDimitry Andric 
2912*b5893f02SDimitry Andric     if (DoBias)
2913*b5893f02SDimitry Andric       return isTop ? -1 : 1;
2914*b5893f02SDimitry Andric   }
2915*b5893f02SDimitry Andric 
2916284c1978SDimitry Andric   return 0;
2917284c1978SDimitry Andric }
29184ba319b5SDimitry Andric } // end namespace llvm
2919284c1978SDimitry Andric 
initCandidate(SchedCandidate & Cand,SUnit * SU,bool AtTop,const RegPressureTracker & RPTracker,RegPressureTracker & TempTracker)29203ca95b02SDimitry Andric void GenericScheduler::initCandidate(SchedCandidate &Cand, SUnit *SU,
29213ca95b02SDimitry Andric                                      bool AtTop,
29223ca95b02SDimitry Andric                                      const RegPressureTracker &RPTracker,
29233ca95b02SDimitry Andric                                      RegPressureTracker &TempTracker) {
29243ca95b02SDimitry Andric   Cand.SU = SU;
29253ca95b02SDimitry Andric   Cand.AtTop = AtTop;
29263ca95b02SDimitry Andric   if (DAG->isTrackingPressure()) {
29273ca95b02SDimitry Andric     if (AtTop) {
29283ca95b02SDimitry Andric       TempTracker.getMaxDownwardPressureDelta(
29293ca95b02SDimitry Andric         Cand.SU->getInstr(),
29303ca95b02SDimitry Andric         Cand.RPDelta,
29313ca95b02SDimitry Andric         DAG->getRegionCriticalPSets(),
29323ca95b02SDimitry Andric         DAG->getRegPressure().MaxSetPressure);
29333ca95b02SDimitry Andric     } else {
29343ca95b02SDimitry Andric       if (VerifyScheduling) {
29353ca95b02SDimitry Andric         TempTracker.getMaxUpwardPressureDelta(
29363ca95b02SDimitry Andric           Cand.SU->getInstr(),
29373ca95b02SDimitry Andric           &DAG->getPressureDiff(Cand.SU),
29383ca95b02SDimitry Andric           Cand.RPDelta,
29393ca95b02SDimitry Andric           DAG->getRegionCriticalPSets(),
29403ca95b02SDimitry Andric           DAG->getRegPressure().MaxSetPressure);
29413ca95b02SDimitry Andric       } else {
29423ca95b02SDimitry Andric         RPTracker.getUpwardPressureDelta(
29433ca95b02SDimitry Andric           Cand.SU->getInstr(),
29443ca95b02SDimitry Andric           DAG->getPressureDiff(Cand.SU),
29453ca95b02SDimitry Andric           Cand.RPDelta,
29463ca95b02SDimitry Andric           DAG->getRegionCriticalPSets(),
29473ca95b02SDimitry Andric           DAG->getRegPressure().MaxSetPressure);
29483ca95b02SDimitry Andric       }
29493ca95b02SDimitry Andric     }
29503ca95b02SDimitry Andric   }
29514ba319b5SDimitry Andric   LLVM_DEBUG(if (Cand.RPDelta.Excess.isValid()) dbgs()
29524ba319b5SDimitry Andric              << "  Try  SU(" << Cand.SU->NodeNum << ") "
29534ba319b5SDimitry Andric              << TRI->getRegPressureSetName(Cand.RPDelta.Excess.getPSet()) << ":"
29544ba319b5SDimitry Andric              << Cand.RPDelta.Excess.getUnitInc() << "\n");
29553ca95b02SDimitry Andric }
29563ca95b02SDimitry Andric 
29574ba319b5SDimitry Andric /// Apply a set of heuristics to a new candidate. Heuristics are currently
29583861d79fSDimitry Andric /// hierarchical. This may be more efficient than a graduated cost model because
29593861d79fSDimitry Andric /// we don't need to evaluate all aspects of the model for each node in the
29603861d79fSDimitry Andric /// queue. But it's really done to make the heuristics easier to debug and
29613861d79fSDimitry Andric /// statistically analyze.
29623861d79fSDimitry Andric ///
29633861d79fSDimitry Andric /// \param Cand provides the policy and current best candidate.
29643861d79fSDimitry Andric /// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
29653ca95b02SDimitry Andric /// \param Zone describes the scheduled zone that we are extending, or nullptr
29663ca95b02SDimitry Andric //              if Cand is from a different zone than TryCand.
tryCandidate(SchedCandidate & Cand,SchedCandidate & TryCand,SchedBoundary * Zone) const2967f785676fSDimitry Andric void GenericScheduler::tryCandidate(SchedCandidate &Cand,
29683861d79fSDimitry Andric                                     SchedCandidate &TryCand,
29694ba319b5SDimitry Andric                                     SchedBoundary *Zone) const {
29703861d79fSDimitry Andric   // Initialize the candidate if needed.
29713861d79fSDimitry Andric   if (!Cand.isValid()) {
29723861d79fSDimitry Andric     TryCand.Reason = NodeOrder;
29733861d79fSDimitry Andric     return;
29743861d79fSDimitry Andric   }
2975284c1978SDimitry Andric 
2976*b5893f02SDimitry Andric   // Bias PhysReg Defs and copies to their uses and defined respectively.
2977*b5893f02SDimitry Andric   if (tryGreater(biasPhysReg(TryCand.SU, TryCand.AtTop),
2978*b5893f02SDimitry Andric                  biasPhysReg(Cand.SU, Cand.AtTop), TryCand, Cand, PhysReg))
2979284c1978SDimitry Andric     return;
2980284c1978SDimitry Andric 
2981ff0cc061SDimitry Andric   // Avoid exceeding the target's limit.
2982f785676fSDimitry Andric   if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.Excess,
2983f785676fSDimitry Andric                                                Cand.RPDelta.Excess,
29847d523365SDimitry Andric                                                TryCand, Cand, RegExcess, TRI,
29857d523365SDimitry Andric                                                DAG->MF))
29863861d79fSDimitry Andric     return;
29873861d79fSDimitry Andric 
29883861d79fSDimitry Andric   // Avoid increasing the max critical pressure in the scheduled region.
2989f785676fSDimitry Andric   if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CriticalMax,
2990f785676fSDimitry Andric                                                Cand.RPDelta.CriticalMax,
29917d523365SDimitry Andric                                                TryCand, Cand, RegCritical, TRI,
29927d523365SDimitry Andric                                                DAG->MF))
29933861d79fSDimitry Andric     return;
2994f785676fSDimitry Andric 
29953ca95b02SDimitry Andric   // We only compare a subset of features when comparing nodes between
29963ca95b02SDimitry Andric   // Top and Bottom boundary. Some properties are simply incomparable, in many
29973ca95b02SDimitry Andric   // other instances we should only override the other boundary if something
29983ca95b02SDimitry Andric   // is a clear good pick on one boundary. Skip heuristics that are more
29993ca95b02SDimitry Andric   // "tie-breaking" in nature.
30003ca95b02SDimitry Andric   bool SameBoundary = Zone != nullptr;
30013ca95b02SDimitry Andric   if (SameBoundary) {
30023ca95b02SDimitry Andric     // For loops that are acyclic path limited, aggressively schedule for
3003d88c1a5aSDimitry Andric     // latency. Within an single cycle, whenever CurrMOps > 0, allow normal
3004d88c1a5aSDimitry Andric     // heuristics to take precedence.
30053ca95b02SDimitry Andric     if (Rem.IsAcyclicLatencyLimited && !Zone->getCurrMOps() &&
30063ca95b02SDimitry Andric         tryLatency(TryCand, Cand, *Zone))
3007f785676fSDimitry Andric       return;
30083861d79fSDimitry Andric 
300991bc56edSDimitry Andric     // Prioritize instructions that read unbuffered resources by stall cycles.
30103ca95b02SDimitry Andric     if (tryLess(Zone->getLatencyStallCycles(TryCand.SU),
30113ca95b02SDimitry Andric                 Zone->getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
301291bc56edSDimitry Andric       return;
30133ca95b02SDimitry Andric   }
301491bc56edSDimitry Andric 
3015139f7f9bSDimitry Andric   // Keep clustered nodes together to encourage downstream peephole
3016139f7f9bSDimitry Andric   // optimizations which may reduce resource requirements.
3017139f7f9bSDimitry Andric   //
3018139f7f9bSDimitry Andric   // This is a best effort to set things up for a post-RA pass. Optimizations
3019139f7f9bSDimitry Andric   // like generating loads of multiple registers should ideally be done within
3020139f7f9bSDimitry Andric   // the scheduler pass by combining the loads during DAG postprocessing.
30213ca95b02SDimitry Andric   const SUnit *CandNextClusterSU =
30223ca95b02SDimitry Andric     Cand.AtTop ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
30233ca95b02SDimitry Andric   const SUnit *TryCandNextClusterSU =
30243ca95b02SDimitry Andric     TryCand.AtTop ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
30253ca95b02SDimitry Andric   if (tryGreater(TryCand.SU == TryCandNextClusterSU,
30263ca95b02SDimitry Andric                  Cand.SU == CandNextClusterSU,
3027139f7f9bSDimitry Andric                  TryCand, Cand, Cluster))
3028139f7f9bSDimitry Andric     return;
3029284c1978SDimitry Andric 
30303ca95b02SDimitry Andric   if (SameBoundary) {
3031284c1978SDimitry Andric     // Weak edges are for clustering and other constraints.
30323ca95b02SDimitry Andric     if (tryLess(getWeakLeft(TryCand.SU, TryCand.AtTop),
30333ca95b02SDimitry Andric                 getWeakLeft(Cand.SU, Cand.AtTop),
30343ca95b02SDimitry Andric                 TryCand, Cand, Weak))
3035139f7f9bSDimitry Andric       return;
3036139f7f9bSDimitry Andric   }
30373ca95b02SDimitry Andric 
3038f785676fSDimitry Andric   // Avoid increasing the max pressure of the entire region.
3039f785676fSDimitry Andric   if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CurrentMax,
3040f785676fSDimitry Andric                                                Cand.RPDelta.CurrentMax,
30417d523365SDimitry Andric                                                TryCand, Cand, RegMax, TRI,
30427d523365SDimitry Andric                                                DAG->MF))
3043f785676fSDimitry Andric     return;
3044f785676fSDimitry Andric 
30453ca95b02SDimitry Andric   if (SameBoundary) {
30463861d79fSDimitry Andric     // Avoid critical resource consumption and balance the schedule.
30473861d79fSDimitry Andric     TryCand.initResourceDelta(DAG, SchedModel);
30483861d79fSDimitry Andric     if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
30493861d79fSDimitry Andric                 TryCand, Cand, ResourceReduce))
30503861d79fSDimitry Andric       return;
30513861d79fSDimitry Andric     if (tryGreater(TryCand.ResDelta.DemandedResources,
30523861d79fSDimitry Andric                    Cand.ResDelta.DemandedResources,
30533861d79fSDimitry Andric                    TryCand, Cand, ResourceDemand))
30543861d79fSDimitry Andric       return;
30553861d79fSDimitry Andric 
30563861d79fSDimitry Andric     // Avoid serializing long latency dependence chains.
3057f785676fSDimitry Andric     // For acyclic path limited loops, latency was already checked above.
30583ca95b02SDimitry Andric     if (!RegionPolicy.DisableLatencyHeuristic && TryCand.Policy.ReduceLatency &&
30593ca95b02SDimitry Andric         !Rem.IsAcyclicLatencyLimited && tryLatency(TryCand, Cand, *Zone))
30603861d79fSDimitry Andric       return;
30613861d79fSDimitry Andric 
30623861d79fSDimitry Andric     // Fall through to original instruction order.
30633ca95b02SDimitry Andric     if ((Zone->isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
30643ca95b02SDimitry Andric         || (!Zone->isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
30653861d79fSDimitry Andric       TryCand.Reason = NodeOrder;
30663861d79fSDimitry Andric     }
30673861d79fSDimitry Andric   }
30683ca95b02SDimitry Andric }
30697ae0e2c9SDimitry Andric 
3070f785676fSDimitry Andric /// Pick the best candidate from the queue.
30717ae0e2c9SDimitry Andric ///
30727ae0e2c9SDimitry Andric /// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
30737ae0e2c9SDimitry Andric /// DAG building. To adjust for the current scheduling location we need to
30747ae0e2c9SDimitry Andric /// maintain the number of vreg uses remaining to be top-scheduled.
pickNodeFromQueue(SchedBoundary & Zone,const CandPolicy & ZonePolicy,const RegPressureTracker & RPTracker,SchedCandidate & Cand)3075f785676fSDimitry Andric void GenericScheduler::pickNodeFromQueue(SchedBoundary &Zone,
30763ca95b02SDimitry Andric                                          const CandPolicy &ZonePolicy,
30773861d79fSDimitry Andric                                          const RegPressureTracker &RPTracker,
30783861d79fSDimitry Andric                                          SchedCandidate &Cand) {
30797ae0e2c9SDimitry Andric   // getMaxPressureDelta temporarily modifies the tracker.
30807ae0e2c9SDimitry Andric   RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
30817ae0e2c9SDimitry Andric 
30823ca95b02SDimitry Andric   ReadyQueue &Q = Zone.Available;
3083edd7eaddSDimitry Andric   for (SUnit *SU : Q) {
30847ae0e2c9SDimitry Andric 
30853ca95b02SDimitry Andric     SchedCandidate TryCand(ZonePolicy);
3086edd7eaddSDimitry Andric     initCandidate(TryCand, SU, Zone.isTop(), RPTracker, TempTracker);
30873ca95b02SDimitry Andric     // Pass SchedBoundary only when comparing nodes from the same boundary.
30883ca95b02SDimitry Andric     SchedBoundary *ZoneArg = Cand.AtTop == TryCand.AtTop ? &Zone : nullptr;
30893ca95b02SDimitry Andric     tryCandidate(Cand, TryCand, ZoneArg);
30903861d79fSDimitry Andric     if (TryCand.Reason != NoCand) {
30913861d79fSDimitry Andric       // Initialize resource delta if needed in case future heuristics query it.
30923861d79fSDimitry Andric       if (TryCand.ResDelta == SchedResourceDelta())
30933861d79fSDimitry Andric         TryCand.initResourceDelta(DAG, SchedModel);
30943861d79fSDimitry Andric       Cand.setBest(TryCand);
30954ba319b5SDimitry Andric       LLVM_DEBUG(traceCandidate(Cand));
30967ae0e2c9SDimitry Andric     }
30977ae0e2c9SDimitry Andric   }
30983861d79fSDimitry Andric }
30997ae0e2c9SDimitry Andric 
31007ae0e2c9SDimitry Andric /// Pick the best candidate node from either the top or bottom queue.
pickNodeBidirectional(bool & IsTopNode)3101f785676fSDimitry Andric SUnit *GenericScheduler::pickNodeBidirectional(bool &IsTopNode) {
31027ae0e2c9SDimitry Andric   // Schedule as far as possible in the direction of no choice. This is most
31037ae0e2c9SDimitry Andric   // efficient, but also provides the best heuristics for CriticalPSets.
31047ae0e2c9SDimitry Andric   if (SUnit *SU = Bot.pickOnlyChoice()) {
31057ae0e2c9SDimitry Andric     IsTopNode = false;
31063ca95b02SDimitry Andric     tracePick(Only1, false);
31077ae0e2c9SDimitry Andric     return SU;
31087ae0e2c9SDimitry Andric   }
31097ae0e2c9SDimitry Andric   if (SUnit *SU = Top.pickOnlyChoice()) {
31107ae0e2c9SDimitry Andric     IsTopNode = true;
31113ca95b02SDimitry Andric     tracePick(Only1, true);
31127ae0e2c9SDimitry Andric     return SU;
31137ae0e2c9SDimitry Andric   }
311491bc56edSDimitry Andric   // Set the bottom-up policy based on the state of the current bottom zone and
311591bc56edSDimitry Andric   // the instructions outside the zone, including the top zone.
31163ca95b02SDimitry Andric   CandPolicy BotPolicy;
31173ca95b02SDimitry Andric   setPolicy(BotPolicy, /*IsPostRA=*/false, Bot, &Top);
311891bc56edSDimitry Andric   // Set the top-down policy based on the state of the current top zone and
311991bc56edSDimitry Andric   // the instructions outside the zone, including the bottom zone.
31203ca95b02SDimitry Andric   CandPolicy TopPolicy;
31213ca95b02SDimitry Andric   setPolicy(TopPolicy, /*IsPostRA=*/false, Top, &Bot);
31223861d79fSDimitry Andric 
31233ca95b02SDimitry Andric   // See if BotCand is still valid (because we previously scheduled from Top).
31244ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Picking from Bot:\n");
31253ca95b02SDimitry Andric   if (!BotCand.isValid() || BotCand.SU->isScheduled ||
31263ca95b02SDimitry Andric       BotCand.Policy != BotPolicy) {
31273ca95b02SDimitry Andric     BotCand.reset(CandPolicy());
31283ca95b02SDimitry Andric     pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), BotCand);
31293861d79fSDimitry Andric     assert(BotCand.Reason != NoCand && "failed to find the first candidate");
31303ca95b02SDimitry Andric   } else {
31314ba319b5SDimitry Andric     LLVM_DEBUG(traceCandidate(BotCand));
31323ca95b02SDimitry Andric #ifndef NDEBUG
31333ca95b02SDimitry Andric     if (VerifyScheduling) {
31343ca95b02SDimitry Andric       SchedCandidate TCand;
31353ca95b02SDimitry Andric       TCand.reset(CandPolicy());
31363ca95b02SDimitry Andric       pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), TCand);
31373ca95b02SDimitry Andric       assert(TCand.SU == BotCand.SU &&
31383ca95b02SDimitry Andric              "Last pick result should correspond to re-picking right now");
31397ae0e2c9SDimitry Andric     }
31403ca95b02SDimitry Andric #endif
31413ca95b02SDimitry Andric   }
31423ca95b02SDimitry Andric 
31437ae0e2c9SDimitry Andric   // Check if the top Q has a better candidate.
31444ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Picking from Top:\n");
31453ca95b02SDimitry Andric   if (!TopCand.isValid() || TopCand.SU->isScheduled ||
31463ca95b02SDimitry Andric       TopCand.Policy != TopPolicy) {
31473ca95b02SDimitry Andric     TopCand.reset(CandPolicy());
31483ca95b02SDimitry Andric     pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TopCand);
31493861d79fSDimitry Andric     assert(TopCand.Reason != NoCand && "failed to find the first candidate");
31503ca95b02SDimitry Andric   } else {
31514ba319b5SDimitry Andric     LLVM_DEBUG(traceCandidate(TopCand));
31523ca95b02SDimitry Andric #ifndef NDEBUG
31533ca95b02SDimitry Andric     if (VerifyScheduling) {
31543ca95b02SDimitry Andric       SchedCandidate TCand;
31553ca95b02SDimitry Andric       TCand.reset(CandPolicy());
31563ca95b02SDimitry Andric       pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TCand);
31573ca95b02SDimitry Andric       assert(TCand.SU == TopCand.SU &&
31583ca95b02SDimitry Andric            "Last pick result should correspond to re-picking right now");
31597ae0e2c9SDimitry Andric     }
31603ca95b02SDimitry Andric #endif
31613ca95b02SDimitry Andric   }
31623ca95b02SDimitry Andric 
31633ca95b02SDimitry Andric   // Pick best from BotCand and TopCand.
31643ca95b02SDimitry Andric   assert(BotCand.isValid());
31653ca95b02SDimitry Andric   assert(TopCand.isValid());
31663ca95b02SDimitry Andric   SchedCandidate Cand = BotCand;
31673ca95b02SDimitry Andric   TopCand.Reason = NoCand;
31683ca95b02SDimitry Andric   tryCandidate(Cand, TopCand, nullptr);
31693ca95b02SDimitry Andric   if (TopCand.Reason != NoCand) {
31703ca95b02SDimitry Andric     Cand.setBest(TopCand);
31714ba319b5SDimitry Andric     LLVM_DEBUG(traceCandidate(Cand));
31723ca95b02SDimitry Andric   }
31733ca95b02SDimitry Andric 
31743ca95b02SDimitry Andric   IsTopNode = Cand.AtTop;
31753ca95b02SDimitry Andric   tracePick(Cand);
31763ca95b02SDimitry Andric   return Cand.SU;
31777ae0e2c9SDimitry Andric }
31787ae0e2c9SDimitry Andric 
31797ae0e2c9SDimitry Andric /// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
pickNode(bool & IsTopNode)3180f785676fSDimitry Andric SUnit *GenericScheduler::pickNode(bool &IsTopNode) {
31817ae0e2c9SDimitry Andric   if (DAG->top() == DAG->bottom()) {
31827ae0e2c9SDimitry Andric     assert(Top.Available.empty() && Top.Pending.empty() &&
31837ae0e2c9SDimitry Andric            Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
318491bc56edSDimitry Andric     return nullptr;
31857ae0e2c9SDimitry Andric   }
31867ae0e2c9SDimitry Andric   SUnit *SU;
31873861d79fSDimitry Andric   do {
3188f785676fSDimitry Andric     if (RegionPolicy.OnlyTopDown) {
31897ae0e2c9SDimitry Andric       SU = Top.pickOnlyChoice();
31907ae0e2c9SDimitry Andric       if (!SU) {
31913861d79fSDimitry Andric         CandPolicy NoPolicy;
31923ca95b02SDimitry Andric         TopCand.reset(NoPolicy);
31933ca95b02SDimitry Andric         pickNodeFromQueue(Top, NoPolicy, DAG->getTopRPTracker(), TopCand);
3194f785676fSDimitry Andric         assert(TopCand.Reason != NoCand && "failed to find a candidate");
31953ca95b02SDimitry Andric         tracePick(TopCand);
31967ae0e2c9SDimitry Andric         SU = TopCand.SU;
31977ae0e2c9SDimitry Andric       }
31987ae0e2c9SDimitry Andric       IsTopNode = true;
31993ca95b02SDimitry Andric     } else if (RegionPolicy.OnlyBottomUp) {
32007ae0e2c9SDimitry Andric       SU = Bot.pickOnlyChoice();
32017ae0e2c9SDimitry Andric       if (!SU) {
32023861d79fSDimitry Andric         CandPolicy NoPolicy;
32033ca95b02SDimitry Andric         BotCand.reset(NoPolicy);
32043ca95b02SDimitry Andric         pickNodeFromQueue(Bot, NoPolicy, DAG->getBotRPTracker(), BotCand);
3205f785676fSDimitry Andric         assert(BotCand.Reason != NoCand && "failed to find a candidate");
32063ca95b02SDimitry Andric         tracePick(BotCand);
32077ae0e2c9SDimitry Andric         SU = BotCand.SU;
32087ae0e2c9SDimitry Andric       }
3209dff0c46cSDimitry Andric       IsTopNode = false;
32103ca95b02SDimitry Andric     } else {
32113861d79fSDimitry Andric       SU = pickNodeBidirectional(IsTopNode);
3212dff0c46cSDimitry Andric     }
32133861d79fSDimitry Andric   } while (SU->isScheduled);
32143861d79fSDimitry Andric 
32157ae0e2c9SDimitry Andric   if (SU->isTopReady())
32167ae0e2c9SDimitry Andric     Top.removeReady(SU);
32177ae0e2c9SDimitry Andric   if (SU->isBottomReady())
32187ae0e2c9SDimitry Andric     Bot.removeReady(SU);
32197ae0e2c9SDimitry Andric 
32204ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") "
32214ba319b5SDimitry Andric                     << *SU->getInstr());
3222dff0c46cSDimitry Andric   return SU;
3223dff0c46cSDimitry Andric }
3224dff0c46cSDimitry Andric 
reschedulePhysReg(SUnit * SU,bool isTop)3225*b5893f02SDimitry Andric void GenericScheduler::reschedulePhysReg(SUnit *SU, bool isTop) {
3226284c1978SDimitry Andric   MachineBasicBlock::iterator InsertPos = SU->getInstr();
3227284c1978SDimitry Andric   if (!isTop)
3228284c1978SDimitry Andric     ++InsertPos;
3229284c1978SDimitry Andric   SmallVectorImpl<SDep> &Deps = isTop ? SU->Preds : SU->Succs;
3230284c1978SDimitry Andric 
3231284c1978SDimitry Andric   // Find already scheduled copies with a single physreg dependence and move
3232284c1978SDimitry Andric   // them just above the scheduled instruction.
3233edd7eaddSDimitry Andric   for (SDep &Dep : Deps) {
3234edd7eaddSDimitry Andric     if (Dep.getKind() != SDep::Data || !TRI->isPhysicalRegister(Dep.getReg()))
3235284c1978SDimitry Andric       continue;
3236edd7eaddSDimitry Andric     SUnit *DepSU = Dep.getSUnit();
3237284c1978SDimitry Andric     if (isTop ? DepSU->Succs.size() > 1 : DepSU->Preds.size() > 1)
3238284c1978SDimitry Andric       continue;
3239284c1978SDimitry Andric     MachineInstr *Copy = DepSU->getInstr();
3240*b5893f02SDimitry Andric     if (!Copy->isCopy() && !Copy->isMoveImmediate())
3241284c1978SDimitry Andric       continue;
32424ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "  Rescheduling physreg copy ";
3243*b5893f02SDimitry Andric                DAG->dumpNode(*Dep.getSUnit()));
3244284c1978SDimitry Andric     DAG->moveInstruction(Copy, InsertPos);
3245284c1978SDimitry Andric   }
3246284c1978SDimitry Andric }
3247284c1978SDimitry Andric 
32487ae0e2c9SDimitry Andric /// Update the scheduler's state after scheduling a node. This is the same node
324991bc56edSDimitry Andric /// that was just returned by pickNode(). However, ScheduleDAGMILive needs to
325091bc56edSDimitry Andric /// update it's state based on the current cycle before MachineSchedStrategy
325191bc56edSDimitry Andric /// does.
3252284c1978SDimitry Andric ///
3253284c1978SDimitry Andric /// FIXME: Eventually, we may bundle physreg copies rather than rescheduling
3254*b5893f02SDimitry Andric /// them here. See comments in biasPhysReg.
schedNode(SUnit * SU,bool IsTopNode)3255f785676fSDimitry Andric void GenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
32567ae0e2c9SDimitry Andric   if (IsTopNode) {
325791bc56edSDimitry Andric     SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
32587ae0e2c9SDimitry Andric     Top.bumpNode(SU);
3259284c1978SDimitry Andric     if (SU->hasPhysRegUses)
3260*b5893f02SDimitry Andric       reschedulePhysReg(SU, true);
32613ca95b02SDimitry Andric   } else {
326291bc56edSDimitry Andric     SU->BotReadyCycle = std::max(SU->BotReadyCycle, Bot.getCurrCycle());
32637ae0e2c9SDimitry Andric     Bot.bumpNode(SU);
3264284c1978SDimitry Andric     if (SU->hasPhysRegDefs)
3265*b5893f02SDimitry Andric       reschedulePhysReg(SU, false);
3266dff0c46cSDimitry Andric   }
32677ae0e2c9SDimitry Andric }
3268dff0c46cSDimitry Andric 
3269dff0c46cSDimitry Andric /// Create the standard converging machine scheduler. This will be used as the
3270dff0c46cSDimitry Andric /// default scheduler if the target does not set a default.
createGenericSchedLive(MachineSchedContext * C)3271d88c1a5aSDimitry Andric ScheduleDAGMILive *llvm::createGenericSchedLive(MachineSchedContext *C) {
32727a7e6055SDimitry Andric   ScheduleDAGMILive *DAG =
32737a7e6055SDimitry Andric       new ScheduleDAGMILive(C, llvm::make_unique<GenericScheduler>(C));
3274139f7f9bSDimitry Andric   // Register DAG post-processors.
3275284c1978SDimitry Andric   //
3276284c1978SDimitry Andric   // FIXME: extend the mutation API to allow earlier mutations to instantiate
3277284c1978SDimitry Andric   // data and pass it to later mutations. Have a single mutation that gathers
3278284c1978SDimitry Andric   // the interesting nodes in one pass.
3279d88c1a5aSDimitry Andric   DAG->addMutation(createCopyConstrainDAGMutation(DAG->TII, DAG->TRI));
3280139f7f9bSDimitry Andric   return DAG;
3281dff0c46cSDimitry Andric }
328291bc56edSDimitry Andric 
createConveringSched(MachineSchedContext * C)3283d88c1a5aSDimitry Andric static ScheduleDAGInstrs *createConveringSched(MachineSchedContext *C) {
3284d88c1a5aSDimitry Andric   return createGenericSchedLive(C);
3285d88c1a5aSDimitry Andric }
3286d88c1a5aSDimitry Andric 
3287dff0c46cSDimitry Andric static MachineSchedRegistry
3288f785676fSDimitry Andric GenericSchedRegistry("converge", "Standard converging scheduler.",
3289d88c1a5aSDimitry Andric                      createConveringSched);
329091bc56edSDimitry Andric 
329191bc56edSDimitry Andric //===----------------------------------------------------------------------===//
329291bc56edSDimitry Andric // PostGenericScheduler - Generic PostRA implementation of MachineSchedStrategy.
329391bc56edSDimitry Andric //===----------------------------------------------------------------------===//
329491bc56edSDimitry Andric 
initialize(ScheduleDAGMI * Dag)329591bc56edSDimitry Andric void PostGenericScheduler::initialize(ScheduleDAGMI *Dag) {
329691bc56edSDimitry Andric   DAG = Dag;
329791bc56edSDimitry Andric   SchedModel = DAG->getSchedModel();
329891bc56edSDimitry Andric   TRI = DAG->TRI;
329991bc56edSDimitry Andric 
330091bc56edSDimitry Andric   Rem.init(DAG, SchedModel);
330191bc56edSDimitry Andric   Top.init(DAG, SchedModel, &Rem);
330291bc56edSDimitry Andric   BotRoots.clear();
330391bc56edSDimitry Andric 
330491bc56edSDimitry Andric   // Initialize the HazardRecognizers. If itineraries don't exist, are empty,
330591bc56edSDimitry Andric   // or are disabled, then these HazardRecs will be disabled.
330691bc56edSDimitry Andric   const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
330791bc56edSDimitry Andric   if (!Top.HazardRec) {
330891bc56edSDimitry Andric     Top.HazardRec =
330939d628a0SDimitry Andric         DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
331039d628a0SDimitry Andric             Itin, DAG);
331191bc56edSDimitry Andric   }
331291bc56edSDimitry Andric }
331391bc56edSDimitry Andric 
registerRoots()331491bc56edSDimitry Andric void PostGenericScheduler::registerRoots() {
331591bc56edSDimitry Andric   Rem.CriticalPath = DAG->ExitSU.getDepth();
331691bc56edSDimitry Andric 
331791bc56edSDimitry Andric   // Some roots may not feed into ExitSU. Check all of them in case.
3318edd7eaddSDimitry Andric   for (const SUnit *SU : BotRoots) {
3319edd7eaddSDimitry Andric     if (SU->getDepth() > Rem.CriticalPath)
3320edd7eaddSDimitry Andric       Rem.CriticalPath = SU->getDepth();
332191bc56edSDimitry Andric   }
33224ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Critical Path: (PGS-RR) " << Rem.CriticalPath << '\n');
332339d628a0SDimitry Andric   if (DumpCriticalPathLength) {
332439d628a0SDimitry Andric     errs() << "Critical Path(PGS-RR ): " << Rem.CriticalPath << " \n";
332539d628a0SDimitry Andric   }
332691bc56edSDimitry Andric }
332791bc56edSDimitry Andric 
33284ba319b5SDimitry Andric /// Apply a set of heuristics to a new candidate for PostRA scheduling.
332991bc56edSDimitry Andric ///
333091bc56edSDimitry Andric /// \param Cand provides the policy and current best candidate.
333191bc56edSDimitry Andric /// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
tryCandidate(SchedCandidate & Cand,SchedCandidate & TryCand)333291bc56edSDimitry Andric void PostGenericScheduler::tryCandidate(SchedCandidate &Cand,
333391bc56edSDimitry Andric                                         SchedCandidate &TryCand) {
333491bc56edSDimitry Andric   // Initialize the candidate if needed.
333591bc56edSDimitry Andric   if (!Cand.isValid()) {
333691bc56edSDimitry Andric     TryCand.Reason = NodeOrder;
333791bc56edSDimitry Andric     return;
333891bc56edSDimitry Andric   }
333991bc56edSDimitry Andric 
334091bc56edSDimitry Andric   // Prioritize instructions that read unbuffered resources by stall cycles.
334191bc56edSDimitry Andric   if (tryLess(Top.getLatencyStallCycles(TryCand.SU),
334291bc56edSDimitry Andric               Top.getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
334391bc56edSDimitry Andric     return;
334491bc56edSDimitry Andric 
3345302affcbSDimitry Andric   // Keep clustered nodes together.
3346302affcbSDimitry Andric   if (tryGreater(TryCand.SU == DAG->getNextClusterSucc(),
3347302affcbSDimitry Andric                  Cand.SU == DAG->getNextClusterSucc(),
3348302affcbSDimitry Andric                  TryCand, Cand, Cluster))
3349302affcbSDimitry Andric     return;
3350302affcbSDimitry Andric 
335191bc56edSDimitry Andric   // Avoid critical resource consumption and balance the schedule.
335291bc56edSDimitry Andric   if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
335391bc56edSDimitry Andric               TryCand, Cand, ResourceReduce))
335491bc56edSDimitry Andric     return;
335591bc56edSDimitry Andric   if (tryGreater(TryCand.ResDelta.DemandedResources,
335691bc56edSDimitry Andric                  Cand.ResDelta.DemandedResources,
335791bc56edSDimitry Andric                  TryCand, Cand, ResourceDemand))
335891bc56edSDimitry Andric     return;
335991bc56edSDimitry Andric 
336091bc56edSDimitry Andric   // Avoid serializing long latency dependence chains.
336191bc56edSDimitry Andric   if (Cand.Policy.ReduceLatency && tryLatency(TryCand, Cand, Top)) {
336291bc56edSDimitry Andric     return;
336391bc56edSDimitry Andric   }
336491bc56edSDimitry Andric 
336591bc56edSDimitry Andric   // Fall through to original instruction order.
336691bc56edSDimitry Andric   if (TryCand.SU->NodeNum < Cand.SU->NodeNum)
336791bc56edSDimitry Andric     TryCand.Reason = NodeOrder;
336891bc56edSDimitry Andric }
336991bc56edSDimitry Andric 
pickNodeFromQueue(SchedCandidate & Cand)337091bc56edSDimitry Andric void PostGenericScheduler::pickNodeFromQueue(SchedCandidate &Cand) {
337191bc56edSDimitry Andric   ReadyQueue &Q = Top.Available;
3372edd7eaddSDimitry Andric   for (SUnit *SU : Q) {
337391bc56edSDimitry Andric     SchedCandidate TryCand(Cand.Policy);
3374edd7eaddSDimitry Andric     TryCand.SU = SU;
33753ca95b02SDimitry Andric     TryCand.AtTop = true;
337691bc56edSDimitry Andric     TryCand.initResourceDelta(DAG, SchedModel);
337791bc56edSDimitry Andric     tryCandidate(Cand, TryCand);
337891bc56edSDimitry Andric     if (TryCand.Reason != NoCand) {
337991bc56edSDimitry Andric       Cand.setBest(TryCand);
33804ba319b5SDimitry Andric       LLVM_DEBUG(traceCandidate(Cand));
338191bc56edSDimitry Andric     }
338291bc56edSDimitry Andric   }
338391bc56edSDimitry Andric }
338491bc56edSDimitry Andric 
338591bc56edSDimitry Andric /// Pick the next node to schedule.
pickNode(bool & IsTopNode)338691bc56edSDimitry Andric SUnit *PostGenericScheduler::pickNode(bool &IsTopNode) {
338791bc56edSDimitry Andric   if (DAG->top() == DAG->bottom()) {
338891bc56edSDimitry Andric     assert(Top.Available.empty() && Top.Pending.empty() && "ReadyQ garbage");
338991bc56edSDimitry Andric     return nullptr;
339091bc56edSDimitry Andric   }
339191bc56edSDimitry Andric   SUnit *SU;
339291bc56edSDimitry Andric   do {
339391bc56edSDimitry Andric     SU = Top.pickOnlyChoice();
33943ca95b02SDimitry Andric     if (SU) {
33953ca95b02SDimitry Andric       tracePick(Only1, true);
33963ca95b02SDimitry Andric     } else {
339791bc56edSDimitry Andric       CandPolicy NoPolicy;
339891bc56edSDimitry Andric       SchedCandidate TopCand(NoPolicy);
339991bc56edSDimitry Andric       // Set the top-down policy based on the state of the current top zone and
340091bc56edSDimitry Andric       // the instructions outside the zone, including the bottom zone.
340191bc56edSDimitry Andric       setPolicy(TopCand.Policy, /*IsPostRA=*/true, Top, nullptr);
340291bc56edSDimitry Andric       pickNodeFromQueue(TopCand);
340391bc56edSDimitry Andric       assert(TopCand.Reason != NoCand && "failed to find a candidate");
34043ca95b02SDimitry Andric       tracePick(TopCand);
340591bc56edSDimitry Andric       SU = TopCand.SU;
340691bc56edSDimitry Andric     }
340791bc56edSDimitry Andric   } while (SU->isScheduled);
340891bc56edSDimitry Andric 
340991bc56edSDimitry Andric   IsTopNode = true;
341091bc56edSDimitry Andric   Top.removeReady(SU);
341191bc56edSDimitry Andric 
34124ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") "
34134ba319b5SDimitry Andric                     << *SU->getInstr());
341491bc56edSDimitry Andric   return SU;
341591bc56edSDimitry Andric }
341691bc56edSDimitry Andric 
341791bc56edSDimitry Andric /// Called after ScheduleDAGMI has scheduled an instruction and updated
341891bc56edSDimitry Andric /// scheduled/remaining flags in the DAG nodes.
schedNode(SUnit * SU,bool IsTopNode)341991bc56edSDimitry Andric void PostGenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
342091bc56edSDimitry Andric   SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
342191bc56edSDimitry Andric   Top.bumpNode(SU);
342291bc56edSDimitry Andric }
342391bc56edSDimitry Andric 
createGenericSchedPostRA(MachineSchedContext * C)3424d88c1a5aSDimitry Andric ScheduleDAGMI *llvm::createGenericSchedPostRA(MachineSchedContext *C) {
34257a7e6055SDimitry Andric   return new ScheduleDAGMI(C, llvm::make_unique<PostGenericScheduler>(C),
3426d88c1a5aSDimitry Andric                            /*RemoveKillFlags=*/true);
342791bc56edSDimitry Andric }
3428dff0c46cSDimitry Andric 
3429dff0c46cSDimitry Andric //===----------------------------------------------------------------------===//
34303861d79fSDimitry Andric // ILP Scheduler. Currently for experimental analysis of heuristics.
34313861d79fSDimitry Andric //===----------------------------------------------------------------------===//
34323861d79fSDimitry Andric 
34333861d79fSDimitry Andric namespace {
34347a7e6055SDimitry Andric 
34354ba319b5SDimitry Andric /// Order nodes by the ILP metric.
34363861d79fSDimitry Andric struct ILPOrder {
34377a7e6055SDimitry Andric   const SchedDFSResult *DFSResult = nullptr;
34387a7e6055SDimitry Andric   const BitVector *ScheduledTrees = nullptr;
34393861d79fSDimitry Andric   bool MaximizeILP;
34403861d79fSDimitry Andric 
ILPOrder__anon1997d06d0511::ILPOrder34417a7e6055SDimitry Andric   ILPOrder(bool MaxILP) : MaximizeILP(MaxILP) {}
34423861d79fSDimitry Andric 
34434ba319b5SDimitry Andric   /// Apply a less-than relation on node priority.
3444139f7f9bSDimitry Andric   ///
3445139f7f9bSDimitry Andric   /// (Return true if A comes after B in the Q.)
operator ()__anon1997d06d0511::ILPOrder34463861d79fSDimitry Andric   bool operator()(const SUnit *A, const SUnit *B) const {
3447139f7f9bSDimitry Andric     unsigned SchedTreeA = DFSResult->getSubtreeID(A);
3448139f7f9bSDimitry Andric     unsigned SchedTreeB = DFSResult->getSubtreeID(B);
3449139f7f9bSDimitry Andric     if (SchedTreeA != SchedTreeB) {
3450139f7f9bSDimitry Andric       // Unscheduled trees have lower priority.
3451139f7f9bSDimitry Andric       if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
3452139f7f9bSDimitry Andric         return ScheduledTrees->test(SchedTreeB);
3453139f7f9bSDimitry Andric 
3454139f7f9bSDimitry Andric       // Trees with shallower connections have have lower priority.
3455139f7f9bSDimitry Andric       if (DFSResult->getSubtreeLevel(SchedTreeA)
3456139f7f9bSDimitry Andric           != DFSResult->getSubtreeLevel(SchedTreeB)) {
3457139f7f9bSDimitry Andric         return DFSResult->getSubtreeLevel(SchedTreeA)
3458139f7f9bSDimitry Andric           < DFSResult->getSubtreeLevel(SchedTreeB);
3459139f7f9bSDimitry Andric       }
3460139f7f9bSDimitry Andric     }
34613861d79fSDimitry Andric     if (MaximizeILP)
3462139f7f9bSDimitry Andric       return DFSResult->getILP(A) < DFSResult->getILP(B);
34633861d79fSDimitry Andric     else
3464139f7f9bSDimitry Andric       return DFSResult->getILP(A) > DFSResult->getILP(B);
34653861d79fSDimitry Andric   }
34663861d79fSDimitry Andric };
34673861d79fSDimitry Andric 
34684ba319b5SDimitry Andric /// Schedule based on the ILP metric.
34693861d79fSDimitry Andric class ILPScheduler : public MachineSchedStrategy {
34707a7e6055SDimitry Andric   ScheduleDAGMILive *DAG = nullptr;
34713861d79fSDimitry Andric   ILPOrder Cmp;
34723861d79fSDimitry Andric 
34733861d79fSDimitry Andric   std::vector<SUnit*> ReadyQ;
34747a7e6055SDimitry Andric 
34753861d79fSDimitry Andric public:
ILPScheduler(bool MaximizeILP)34767a7e6055SDimitry Andric   ILPScheduler(bool MaximizeILP) : Cmp(MaximizeILP) {}
34773861d79fSDimitry Andric 
initialize(ScheduleDAGMI * dag)347891bc56edSDimitry Andric   void initialize(ScheduleDAGMI *dag) override {
347991bc56edSDimitry Andric     assert(dag->hasVRegLiveness() && "ILPScheduler needs vreg liveness");
348091bc56edSDimitry Andric     DAG = static_cast<ScheduleDAGMILive*>(dag);
3481139f7f9bSDimitry Andric     DAG->computeDFSResult();
3482139f7f9bSDimitry Andric     Cmp.DFSResult = DAG->getDFSResult();
3483139f7f9bSDimitry Andric     Cmp.ScheduledTrees = &DAG->getScheduledTrees();
34843861d79fSDimitry Andric     ReadyQ.clear();
34853861d79fSDimitry Andric   }
34863861d79fSDimitry Andric 
registerRoots()348791bc56edSDimitry Andric   void registerRoots() override {
3488139f7f9bSDimitry Andric     // Restore the heap in ReadyQ with the updated DFS results.
3489139f7f9bSDimitry Andric     std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
34903861d79fSDimitry Andric   }
34913861d79fSDimitry Andric 
34923861d79fSDimitry Andric   /// Implement MachineSchedStrategy interface.
34933861d79fSDimitry Andric   /// -----------------------------------------
34943861d79fSDimitry Andric 
3495139f7f9bSDimitry Andric   /// Callback to select the highest priority node from the ready Q.
pickNode(bool & IsTopNode)349691bc56edSDimitry Andric   SUnit *pickNode(bool &IsTopNode) override {
349791bc56edSDimitry Andric     if (ReadyQ.empty()) return nullptr;
3498139f7f9bSDimitry Andric     std::pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
34993861d79fSDimitry Andric     SUnit *SU = ReadyQ.back();
35003861d79fSDimitry Andric     ReadyQ.pop_back();
35013861d79fSDimitry Andric     IsTopNode = false;
35024ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Pick node "
35034ba319b5SDimitry Andric                       << "SU(" << SU->NodeNum << ") "
3504139f7f9bSDimitry Andric                       << " ILP: " << DAG->getDFSResult()->getILP(SU)
35054ba319b5SDimitry Andric                       << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU)
35064ba319b5SDimitry Andric                       << " @"
3507139f7f9bSDimitry Andric                       << DAG->getDFSResult()->getSubtreeLevel(
35084ba319b5SDimitry Andric                              DAG->getDFSResult()->getSubtreeID(SU))
35094ba319b5SDimitry Andric                       << '\n'
3510284c1978SDimitry Andric                       << "Scheduling " << *SU->getInstr());
35113861d79fSDimitry Andric     return SU;
35123861d79fSDimitry Andric   }
35133861d79fSDimitry Andric 
35144ba319b5SDimitry Andric   /// Scheduler callback to notify that a new subtree is scheduled.
scheduleTree(unsigned SubtreeID)351591bc56edSDimitry Andric   void scheduleTree(unsigned SubtreeID) override {
3516139f7f9bSDimitry Andric     std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3517139f7f9bSDimitry Andric   }
3518139f7f9bSDimitry Andric 
3519139f7f9bSDimitry Andric   /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
3520139f7f9bSDimitry Andric   /// DFSResults, and resort the priority Q.
schedNode(SUnit * SU,bool IsTopNode)352191bc56edSDimitry Andric   void schedNode(SUnit *SU, bool IsTopNode) override {
3522139f7f9bSDimitry Andric     assert(!IsTopNode && "SchedDFSResult needs bottom-up");
3523139f7f9bSDimitry Andric   }
35243861d79fSDimitry Andric 
releaseTopNode(SUnit *)352591bc56edSDimitry Andric   void releaseTopNode(SUnit *) override { /*only called for top roots*/ }
35263861d79fSDimitry Andric 
releaseBottomNode(SUnit * SU)352791bc56edSDimitry Andric   void releaseBottomNode(SUnit *SU) override {
35283861d79fSDimitry Andric     ReadyQ.push_back(SU);
35293861d79fSDimitry Andric     std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
35303861d79fSDimitry Andric   }
35313861d79fSDimitry Andric };
35327a7e6055SDimitry Andric 
35337a7e6055SDimitry Andric } // end anonymous namespace
35343861d79fSDimitry Andric 
createILPMaxScheduler(MachineSchedContext * C)35353861d79fSDimitry Andric static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
35367a7e6055SDimitry Andric   return new ScheduleDAGMILive(C, llvm::make_unique<ILPScheduler>(true));
35373861d79fSDimitry Andric }
createILPMinScheduler(MachineSchedContext * C)35383861d79fSDimitry Andric static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
35397a7e6055SDimitry Andric   return new ScheduleDAGMILive(C, llvm::make_unique<ILPScheduler>(false));
35403861d79fSDimitry Andric }
35417a7e6055SDimitry Andric 
35423861d79fSDimitry Andric static MachineSchedRegistry ILPMaxRegistry(
35433861d79fSDimitry Andric   "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
35443861d79fSDimitry Andric static MachineSchedRegistry ILPMinRegistry(
35453861d79fSDimitry Andric   "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
35463861d79fSDimitry Andric 
35473861d79fSDimitry Andric //===----------------------------------------------------------------------===//
3548dff0c46cSDimitry Andric // Machine Instruction Shuffler for Correctness Testing
3549dff0c46cSDimitry Andric //===----------------------------------------------------------------------===//
3550dff0c46cSDimitry Andric 
3551dff0c46cSDimitry Andric #ifndef NDEBUG
3552dff0c46cSDimitry Andric namespace {
35537a7e6055SDimitry Andric 
3554dff0c46cSDimitry Andric /// Apply a less-than relation on the node order, which corresponds to the
3555dff0c46cSDimitry Andric /// instruction order prior to scheduling. IsReverse implements greater-than.
3556dff0c46cSDimitry Andric template<bool IsReverse>
3557dff0c46cSDimitry Andric struct SUnitOrder {
operator ()__anon1997d06d0611::SUnitOrder3558dff0c46cSDimitry Andric   bool operator()(SUnit *A, SUnit *B) const {
3559dff0c46cSDimitry Andric     if (IsReverse)
3560dff0c46cSDimitry Andric       return A->NodeNum > B->NodeNum;
3561dff0c46cSDimitry Andric     else
3562dff0c46cSDimitry Andric       return A->NodeNum < B->NodeNum;
3563dff0c46cSDimitry Andric   }
3564dff0c46cSDimitry Andric };
3565dff0c46cSDimitry Andric 
3566dff0c46cSDimitry Andric /// Reorder instructions as much as possible.
3567dff0c46cSDimitry Andric class InstructionShuffler : public MachineSchedStrategy {
3568dff0c46cSDimitry Andric   bool IsAlternating;
3569dff0c46cSDimitry Andric   bool IsTopDown;
3570dff0c46cSDimitry Andric 
3571dff0c46cSDimitry Andric   // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
3572dff0c46cSDimitry Andric   // gives nodes with a higher number higher priority causing the latest
3573dff0c46cSDimitry Andric   // instructions to be scheduled first.
3574dff0c46cSDimitry Andric   PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false>>
3575dff0c46cSDimitry Andric     TopQ;
35762cab237bSDimitry Andric 
3577dff0c46cSDimitry Andric   // When scheduling bottom-up, use greater-than as the queue priority.
3578dff0c46cSDimitry Andric   PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true>>
3579dff0c46cSDimitry Andric     BottomQ;
35807a7e6055SDimitry Andric 
3581dff0c46cSDimitry Andric public:
InstructionShuffler(bool alternate,bool topdown)3582dff0c46cSDimitry Andric   InstructionShuffler(bool alternate, bool topdown)
3583dff0c46cSDimitry Andric     : IsAlternating(alternate), IsTopDown(topdown) {}
3584dff0c46cSDimitry Andric 
initialize(ScheduleDAGMI *)358591bc56edSDimitry Andric   void initialize(ScheduleDAGMI*) override {
3586dff0c46cSDimitry Andric     TopQ.clear();
3587dff0c46cSDimitry Andric     BottomQ.clear();
3588dff0c46cSDimitry Andric   }
3589dff0c46cSDimitry Andric 
3590dff0c46cSDimitry Andric   /// Implement MachineSchedStrategy interface.
3591dff0c46cSDimitry Andric   /// -----------------------------------------
3592dff0c46cSDimitry Andric 
pickNode(bool & IsTopNode)359391bc56edSDimitry Andric   SUnit *pickNode(bool &IsTopNode) override {
3594dff0c46cSDimitry Andric     SUnit *SU;
3595dff0c46cSDimitry Andric     if (IsTopDown) {
3596dff0c46cSDimitry Andric       do {
359791bc56edSDimitry Andric         if (TopQ.empty()) return nullptr;
3598dff0c46cSDimitry Andric         SU = TopQ.top();
3599dff0c46cSDimitry Andric         TopQ.pop();
3600dff0c46cSDimitry Andric       } while (SU->isScheduled);
3601dff0c46cSDimitry Andric       IsTopNode = true;
36023ca95b02SDimitry Andric     } else {
3603dff0c46cSDimitry Andric       do {
360491bc56edSDimitry Andric         if (BottomQ.empty()) return nullptr;
3605dff0c46cSDimitry Andric         SU = BottomQ.top();
3606dff0c46cSDimitry Andric         BottomQ.pop();
3607dff0c46cSDimitry Andric       } while (SU->isScheduled);
3608dff0c46cSDimitry Andric       IsTopNode = false;
3609dff0c46cSDimitry Andric     }
3610dff0c46cSDimitry Andric     if (IsAlternating)
3611dff0c46cSDimitry Andric       IsTopDown = !IsTopDown;
3612dff0c46cSDimitry Andric     return SU;
3613dff0c46cSDimitry Andric   }
3614dff0c46cSDimitry Andric 
schedNode(SUnit * SU,bool IsTopNode)361591bc56edSDimitry Andric   void schedNode(SUnit *SU, bool IsTopNode) override {}
36167ae0e2c9SDimitry Andric 
releaseTopNode(SUnit * SU)361791bc56edSDimitry Andric   void releaseTopNode(SUnit *SU) override {
3618dff0c46cSDimitry Andric     TopQ.push(SU);
3619dff0c46cSDimitry Andric   }
releaseBottomNode(SUnit * SU)362091bc56edSDimitry Andric   void releaseBottomNode(SUnit *SU) override {
3621dff0c46cSDimitry Andric     BottomQ.push(SU);
3622dff0c46cSDimitry Andric   }
3623dff0c46cSDimitry Andric };
36247a7e6055SDimitry Andric 
36257a7e6055SDimitry Andric } // end anonymous namespace
3626dff0c46cSDimitry Andric 
createInstructionShuffler(MachineSchedContext * C)3627dff0c46cSDimitry Andric static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
3628dff0c46cSDimitry Andric   bool Alternate = !ForceTopDown && !ForceBottomUp;
3629dff0c46cSDimitry Andric   bool TopDown = !ForceBottomUp;
3630dff0c46cSDimitry Andric   assert((TopDown || !ForceTopDown) &&
3631dff0c46cSDimitry Andric          "-misched-topdown incompatible with -misched-bottomup");
36327a7e6055SDimitry Andric   return new ScheduleDAGMILive(
36337a7e6055SDimitry Andric       C, llvm::make_unique<InstructionShuffler>(Alternate, TopDown));
3634dff0c46cSDimitry Andric }
36357a7e6055SDimitry Andric 
3636dff0c46cSDimitry Andric static MachineSchedRegistry ShufflerRegistry(
3637dff0c46cSDimitry Andric   "shuffle", "Shuffle machine instructions alternating directions",
3638dff0c46cSDimitry Andric   createInstructionShuffler);
3639dff0c46cSDimitry Andric #endif // !NDEBUG
3640139f7f9bSDimitry Andric 
3641139f7f9bSDimitry Andric //===----------------------------------------------------------------------===//
364291bc56edSDimitry Andric // GraphWriter support for ScheduleDAGMILive.
3643139f7f9bSDimitry Andric //===----------------------------------------------------------------------===//
3644139f7f9bSDimitry Andric 
3645139f7f9bSDimitry Andric #ifndef NDEBUG
3646139f7f9bSDimitry Andric namespace llvm {
3647139f7f9bSDimitry Andric 
3648139f7f9bSDimitry Andric template<> struct GraphTraits<
3649139f7f9bSDimitry Andric   ScheduleDAGMI*> : public GraphTraits<ScheduleDAG*> {};
3650139f7f9bSDimitry Andric 
3651139f7f9bSDimitry Andric template<>
3652139f7f9bSDimitry Andric struct DOTGraphTraits<ScheduleDAGMI*> : public DefaultDOTGraphTraits {
DOTGraphTraitsllvm::DOTGraphTraits3653139f7f9bSDimitry Andric   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
3654139f7f9bSDimitry Andric 
getGraphNamellvm::DOTGraphTraits3655139f7f9bSDimitry Andric   static std::string getGraphName(const ScheduleDAG *G) {
3656139f7f9bSDimitry Andric     return G->MF.getName();
3657139f7f9bSDimitry Andric   }
3658139f7f9bSDimitry Andric 
renderGraphFromBottomUpllvm::DOTGraphTraits3659139f7f9bSDimitry Andric   static bool renderGraphFromBottomUp() {
3660139f7f9bSDimitry Andric     return true;
3661139f7f9bSDimitry Andric   }
3662139f7f9bSDimitry Andric 
isNodeHiddenllvm::DOTGraphTraits3663139f7f9bSDimitry Andric   static bool isNodeHidden(const SUnit *Node) {
36647d523365SDimitry Andric     if (ViewMISchedCutoff == 0)
3665139f7f9bSDimitry Andric       return false;
36667d523365SDimitry Andric     return (Node->Preds.size() > ViewMISchedCutoff
36677d523365SDimitry Andric          || Node->Succs.size() > ViewMISchedCutoff);
3668139f7f9bSDimitry Andric   }
3669139f7f9bSDimitry Andric 
3670139f7f9bSDimitry Andric   /// If you want to override the dot attributes printed for a particular
3671139f7f9bSDimitry Andric   /// edge, override this method.
getEdgeAttributesllvm::DOTGraphTraits3672139f7f9bSDimitry Andric   static std::string getEdgeAttributes(const SUnit *Node,
3673139f7f9bSDimitry Andric                                        SUnitIterator EI,
3674139f7f9bSDimitry Andric                                        const ScheduleDAG *Graph) {
3675139f7f9bSDimitry Andric     if (EI.isArtificialDep())
3676139f7f9bSDimitry Andric       return "color=cyan,style=dashed";
3677139f7f9bSDimitry Andric     if (EI.isCtrlDep())
3678139f7f9bSDimitry Andric       return "color=blue,style=dashed";
3679139f7f9bSDimitry Andric     return "";
3680139f7f9bSDimitry Andric   }
3681139f7f9bSDimitry Andric 
getNodeLabelllvm::DOTGraphTraits3682139f7f9bSDimitry Andric   static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) {
3683139f7f9bSDimitry Andric     std::string Str;
3684139f7f9bSDimitry Andric     raw_string_ostream SS(Str);
368591bc56edSDimitry Andric     const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
368691bc56edSDimitry Andric     const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
368791bc56edSDimitry Andric       static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
3688f785676fSDimitry Andric     SS << "SU:" << SU->NodeNum;
3689f785676fSDimitry Andric     if (DFS)
3690f785676fSDimitry Andric       SS << " I:" << DFS->getNumInstrs(SU);
3691139f7f9bSDimitry Andric     return SS.str();
3692139f7f9bSDimitry Andric   }
36932cab237bSDimitry Andric 
getNodeDescriptionllvm::DOTGraphTraits3694139f7f9bSDimitry Andric   static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G) {
3695139f7f9bSDimitry Andric     return G->getGraphNodeLabel(SU);
3696139f7f9bSDimitry Andric   }
3697139f7f9bSDimitry Andric 
getNodeAttributesllvm::DOTGraphTraits369891bc56edSDimitry Andric   static std::string getNodeAttributes(const SUnit *N, const ScheduleDAG *G) {
3699139f7f9bSDimitry Andric     std::string Str("shape=Mrecord");
370091bc56edSDimitry Andric     const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
370191bc56edSDimitry Andric     const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
370291bc56edSDimitry Andric       static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
3703139f7f9bSDimitry Andric     if (DFS) {
3704139f7f9bSDimitry Andric       Str += ",style=filled,fillcolor=\"#";
3705139f7f9bSDimitry Andric       Str += DOT::getColorString(DFS->getSubtreeID(N));
3706139f7f9bSDimitry Andric       Str += '"';
3707139f7f9bSDimitry Andric     }
3708139f7f9bSDimitry Andric     return Str;
3709139f7f9bSDimitry Andric   }
3710139f7f9bSDimitry Andric };
37117a7e6055SDimitry Andric 
37127a7e6055SDimitry Andric } // end namespace llvm
3713139f7f9bSDimitry Andric #endif // NDEBUG
3714139f7f9bSDimitry Andric 
3715139f7f9bSDimitry Andric /// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
3716139f7f9bSDimitry Andric /// rendered using 'dot'.
viewGraph(const Twine & Name,const Twine & Title)3717139f7f9bSDimitry Andric void ScheduleDAGMI::viewGraph(const Twine &Name, const Twine &Title) {
3718139f7f9bSDimitry Andric #ifndef NDEBUG
3719139f7f9bSDimitry Andric   ViewGraph(this, Name, false, Title);
3720139f7f9bSDimitry Andric #else
3721139f7f9bSDimitry Andric   errs() << "ScheduleDAGMI::viewGraph is only available in debug builds on "
3722139f7f9bSDimitry Andric          << "systems with Graphviz or gv!\n";
3723139f7f9bSDimitry Andric #endif  // NDEBUG
3724139f7f9bSDimitry Andric }
3725139f7f9bSDimitry Andric 
3726139f7f9bSDimitry Andric /// Out-of-line implementation with no arguments is handy for gdb.
viewGraph()3727139f7f9bSDimitry Andric void ScheduleDAGMI::viewGraph() {
3728139f7f9bSDimitry Andric   viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName());
3729139f7f9bSDimitry Andric }
3730