10b57cec5SDimitry Andric //===- MachineScheduler.cpp - Machine Instruction Scheduler ---------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // MachineScheduler schedules machine instructions after phi elimination. It
100b57cec5SDimitry Andric // preserves LiveIntervals so it can be invoked before register allocation.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
130b57cec5SDimitry Andric 
140b57cec5SDimitry Andric #include "llvm/CodeGen/MachineScheduler.h"
150b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
160b57cec5SDimitry Andric #include "llvm/ADT/BitVector.h"
170b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
180b57cec5SDimitry Andric #include "llvm/ADT/PriorityQueue.h"
190b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
200b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
21e8d8bef9SDimitry Andric #include "llvm/ADT/Statistic.h"
220b57cec5SDimitry Andric #include "llvm/ADT/iterator_range.h"
230b57cec5SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
240b57cec5SDimitry Andric #include "llvm/CodeGen/LiveInterval.h"
250b57cec5SDimitry Andric #include "llvm/CodeGen/LiveIntervals.h"
260b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
270b57cec5SDimitry Andric #include "llvm/CodeGen/MachineDominators.h"
280b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
290b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
300b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
310b57cec5SDimitry Andric #include "llvm/CodeGen/MachineLoopInfo.h"
320b57cec5SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
330b57cec5SDimitry Andric #include "llvm/CodeGen/MachinePassRegistry.h"
340b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
35fe013be4SDimitry Andric #include "llvm/CodeGen/MachineValueType.h"
360b57cec5SDimitry Andric #include "llvm/CodeGen/RegisterClassInfo.h"
370b57cec5SDimitry Andric #include "llvm/CodeGen/RegisterPressure.h"
380b57cec5SDimitry Andric #include "llvm/CodeGen/ScheduleDAG.h"
390b57cec5SDimitry Andric #include "llvm/CodeGen/ScheduleDAGInstrs.h"
400b57cec5SDimitry Andric #include "llvm/CodeGen/ScheduleDAGMutation.h"
410b57cec5SDimitry Andric #include "llvm/CodeGen/ScheduleDFS.h"
420b57cec5SDimitry Andric #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
430b57cec5SDimitry Andric #include "llvm/CodeGen/SlotIndexes.h"
440b57cec5SDimitry Andric #include "llvm/CodeGen/TargetFrameLowering.h"
450b57cec5SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
460b57cec5SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
470b57cec5SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
480b57cec5SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
490b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSchedule.h"
500b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
510b57cec5SDimitry Andric #include "llvm/Config/llvm-config.h"
52480093f4SDimitry Andric #include "llvm/InitializePasses.h"
530b57cec5SDimitry Andric #include "llvm/MC/LaneBitmask.h"
540b57cec5SDimitry Andric #include "llvm/Pass.h"
550b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
560b57cec5SDimitry Andric #include "llvm/Support/Compiler.h"
570b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
580b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
590b57cec5SDimitry Andric #include "llvm/Support/GraphWriter.h"
600b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
610b57cec5SDimitry Andric #include <algorithm>
620b57cec5SDimitry Andric #include <cassert>
630b57cec5SDimitry Andric #include <cstdint>
640b57cec5SDimitry Andric #include <iterator>
650b57cec5SDimitry Andric #include <limits>
660b57cec5SDimitry Andric #include <memory>
670b57cec5SDimitry Andric #include <string>
680b57cec5SDimitry Andric #include <tuple>
690b57cec5SDimitry Andric #include <utility>
700b57cec5SDimitry Andric #include <vector>
710b57cec5SDimitry Andric 
720b57cec5SDimitry Andric using namespace llvm;
730b57cec5SDimitry Andric 
740b57cec5SDimitry Andric #define DEBUG_TYPE "machine-scheduler"
750b57cec5SDimitry Andric 
76e8d8bef9SDimitry Andric STATISTIC(NumClustered, "Number of load/store pairs clustered");
77e8d8bef9SDimitry Andric 
780b57cec5SDimitry Andric namespace llvm {
790b57cec5SDimitry Andric 
800b57cec5SDimitry Andric cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
810b57cec5SDimitry Andric                            cl::desc("Force top-down list scheduling"));
820b57cec5SDimitry Andric cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
830b57cec5SDimitry Andric                             cl::desc("Force bottom-up list scheduling"));
840b57cec5SDimitry Andric cl::opt<bool>
850b57cec5SDimitry Andric DumpCriticalPathLength("misched-dcpl", cl::Hidden,
860b57cec5SDimitry Andric                        cl::desc("Print critical path length to stdout"));
870b57cec5SDimitry Andric 
888bcb0991SDimitry Andric cl::opt<bool> VerifyScheduling(
898bcb0991SDimitry Andric     "verify-misched", cl::Hidden,
908bcb0991SDimitry Andric     cl::desc("Verify machine instrs before and after machine scheduling"));
918bcb0991SDimitry Andric 
920eae32dcSDimitry Andric #ifndef NDEBUG
930eae32dcSDimitry Andric cl::opt<bool> ViewMISchedDAGs(
940eae32dcSDimitry Andric     "view-misched-dags", cl::Hidden,
950eae32dcSDimitry Andric     cl::desc("Pop up a window to show MISched dags after they are processed"));
96753f127fSDimitry Andric cl::opt<bool> PrintDAGs("misched-print-dags", cl::Hidden,
97753f127fSDimitry Andric                         cl::desc("Print schedule DAGs"));
98bdd1243dSDimitry Andric cl::opt<bool> MISchedDumpReservedCycles(
99bdd1243dSDimitry Andric     "misched-dump-reserved-cycles", cl::Hidden, cl::init(false),
100bdd1243dSDimitry Andric     cl::desc("Dump resource usage at schedule boundary."));
101fe013be4SDimitry Andric cl::opt<bool> MischedDetailResourceBooking(
102fe013be4SDimitry Andric     "misched-detail-resource-booking", cl::Hidden, cl::init(false),
103fe013be4SDimitry Andric     cl::desc("Show details of invoking getNextResoufceCycle."));
1040eae32dcSDimitry Andric #else
1050eae32dcSDimitry Andric const bool ViewMISchedDAGs = false;
106753f127fSDimitry Andric const bool PrintDAGs = false;
107fe013be4SDimitry Andric const bool MischedDetailResourceBooking = false;
108bdd1243dSDimitry Andric #ifdef LLVM_ENABLE_DUMP
109bdd1243dSDimitry Andric const bool MISchedDumpReservedCycles = false;
110bdd1243dSDimitry Andric #endif // LLVM_ENABLE_DUMP
1110eae32dcSDimitry Andric #endif // NDEBUG
1120eae32dcSDimitry Andric 
1130b57cec5SDimitry Andric } // end namespace llvm
1140b57cec5SDimitry Andric 
1150b57cec5SDimitry Andric #ifndef NDEBUG
1160b57cec5SDimitry Andric /// In some situations a few uninteresting nodes depend on nearly all other
1170b57cec5SDimitry Andric /// nodes in the graph, provide a cutoff to hide them.
1180b57cec5SDimitry Andric static cl::opt<unsigned> ViewMISchedCutoff("view-misched-cutoff", cl::Hidden,
1190b57cec5SDimitry Andric   cl::desc("Hide nodes with more predecessor/successor than cutoff"));
1200b57cec5SDimitry Andric 
1210b57cec5SDimitry Andric static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
1220b57cec5SDimitry Andric   cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
1230b57cec5SDimitry Andric 
1240b57cec5SDimitry Andric static cl::opt<std::string> SchedOnlyFunc("misched-only-func", cl::Hidden,
1250b57cec5SDimitry Andric   cl::desc("Only schedule this function"));
1260b57cec5SDimitry Andric static cl::opt<unsigned> SchedOnlyBlock("misched-only-block", cl::Hidden,
1270b57cec5SDimitry Andric                                         cl::desc("Only schedule this MBB#"));
1280b57cec5SDimitry Andric #endif // NDEBUG
1290b57cec5SDimitry Andric 
1300b57cec5SDimitry Andric /// Avoid quadratic complexity in unusually large basic blocks by limiting the
1310b57cec5SDimitry Andric /// size of the ready lists.
1320b57cec5SDimitry Andric static cl::opt<unsigned> ReadyListLimit("misched-limit", cl::Hidden,
1330b57cec5SDimitry Andric   cl::desc("Limit ready list to N instructions"), cl::init(256));
1340b57cec5SDimitry Andric 
1350b57cec5SDimitry Andric static cl::opt<bool> EnableRegPressure("misched-regpressure", cl::Hidden,
1360b57cec5SDimitry Andric   cl::desc("Enable register pressure scheduling."), cl::init(true));
1370b57cec5SDimitry Andric 
1380b57cec5SDimitry Andric static cl::opt<bool> EnableCyclicPath("misched-cyclicpath", cl::Hidden,
1390b57cec5SDimitry Andric   cl::desc("Enable cyclic critical path analysis."), cl::init(true));
1400b57cec5SDimitry Andric 
1410b57cec5SDimitry Andric static cl::opt<bool> EnableMemOpCluster("misched-cluster", cl::Hidden,
1420b57cec5SDimitry Andric                                         cl::desc("Enable memop clustering."),
1430b57cec5SDimitry Andric                                         cl::init(true));
144e8d8bef9SDimitry Andric static cl::opt<bool>
145e8d8bef9SDimitry Andric     ForceFastCluster("force-fast-cluster", cl::Hidden,
146e8d8bef9SDimitry Andric                      cl::desc("Switch to fast cluster algorithm with the lost "
147e8d8bef9SDimitry Andric                               "of some fusion opportunities"),
148e8d8bef9SDimitry Andric                      cl::init(false));
149e8d8bef9SDimitry Andric static cl::opt<unsigned>
150e8d8bef9SDimitry Andric     FastClusterThreshold("fast-cluster-threshold", cl::Hidden,
151e8d8bef9SDimitry Andric                          cl::desc("The threshold for fast cluster"),
152e8d8bef9SDimitry Andric                          cl::init(1000));
1530b57cec5SDimitry Andric 
154fe013be4SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
155fe013be4SDimitry Andric static cl::opt<bool> MISchedDumpScheduleTrace(
156fe013be4SDimitry Andric     "misched-dump-schedule-trace", cl::Hidden, cl::init(false),
157fe013be4SDimitry Andric     cl::desc("Dump resource usage at schedule boundary."));
158fe013be4SDimitry Andric static cl::opt<unsigned>
159fe013be4SDimitry Andric     HeaderColWidth("misched-dump-schedule-trace-col-header-width", cl::Hidden,
160fe013be4SDimitry Andric                    cl::desc("Set width of the columns with "
161fe013be4SDimitry Andric                             "the resources and schedule units"),
162fe013be4SDimitry Andric                    cl::init(19));
163fe013be4SDimitry Andric static cl::opt<unsigned>
164fe013be4SDimitry Andric     ColWidth("misched-dump-schedule-trace-col-width", cl::Hidden,
165fe013be4SDimitry Andric              cl::desc("Set width of the columns showing resource booking."),
166fe013be4SDimitry Andric              cl::init(5));
167fe013be4SDimitry Andric static cl::opt<bool> MISchedSortResourcesInTrace(
168fe013be4SDimitry Andric     "misched-sort-resources-in-trace", cl::Hidden, cl::init(true),
169fe013be4SDimitry Andric     cl::desc("Sort the resources printed in the dump trace"));
170fe013be4SDimitry Andric #endif
171fe013be4SDimitry Andric 
172fe013be4SDimitry Andric static cl::opt<unsigned>
173fe013be4SDimitry Andric     MIResourceCutOff("misched-resource-cutoff", cl::Hidden,
174fe013be4SDimitry Andric                      cl::desc("Number of intervals to track"), cl::init(10));
175fe013be4SDimitry Andric 
1760b57cec5SDimitry Andric // DAG subtrees must have at least this many nodes.
1770b57cec5SDimitry Andric static const unsigned MinSubtreeSize = 8;
1780b57cec5SDimitry Andric 
1790b57cec5SDimitry Andric // Pin the vtables to this file.
anchor()1800b57cec5SDimitry Andric void MachineSchedStrategy::anchor() {}
1810b57cec5SDimitry Andric 
anchor()1820b57cec5SDimitry Andric void ScheduleDAGMutation::anchor() {}
1830b57cec5SDimitry Andric 
1840b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1850b57cec5SDimitry Andric // Machine Instruction Scheduling Pass and Registry
1860b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1870b57cec5SDimitry Andric 
MachineSchedContext()1880b57cec5SDimitry Andric MachineSchedContext::MachineSchedContext() {
1890b57cec5SDimitry Andric   RegClassInfo = new RegisterClassInfo();
1900b57cec5SDimitry Andric }
1910b57cec5SDimitry Andric 
~MachineSchedContext()1920b57cec5SDimitry Andric MachineSchedContext::~MachineSchedContext() {
1930b57cec5SDimitry Andric   delete RegClassInfo;
1940b57cec5SDimitry Andric }
1950b57cec5SDimitry Andric 
1960b57cec5SDimitry Andric namespace {
1970b57cec5SDimitry Andric 
1980b57cec5SDimitry Andric /// Base class for a machine scheduler class that can run at any point.
1990b57cec5SDimitry Andric class MachineSchedulerBase : public MachineSchedContext,
2000b57cec5SDimitry Andric                              public MachineFunctionPass {
2010b57cec5SDimitry Andric public:
MachineSchedulerBase(char & ID)2020b57cec5SDimitry Andric   MachineSchedulerBase(char &ID): MachineFunctionPass(ID) {}
2030b57cec5SDimitry Andric 
2040b57cec5SDimitry Andric   void print(raw_ostream &O, const Module* = nullptr) const override;
2050b57cec5SDimitry Andric 
2060b57cec5SDimitry Andric protected:
2070b57cec5SDimitry Andric   void scheduleRegions(ScheduleDAGInstrs &Scheduler, bool FixKillFlags);
2080b57cec5SDimitry Andric };
2090b57cec5SDimitry Andric 
2100b57cec5SDimitry Andric /// MachineScheduler runs after coalescing and before register allocation.
2110b57cec5SDimitry Andric class MachineScheduler : public MachineSchedulerBase {
2120b57cec5SDimitry Andric public:
2130b57cec5SDimitry Andric   MachineScheduler();
2140b57cec5SDimitry Andric 
2150b57cec5SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override;
2160b57cec5SDimitry Andric 
2170b57cec5SDimitry Andric   bool runOnMachineFunction(MachineFunction&) override;
2180b57cec5SDimitry Andric 
2190b57cec5SDimitry Andric   static char ID; // Class identification, replacement for typeinfo
2200b57cec5SDimitry Andric 
2210b57cec5SDimitry Andric protected:
2220b57cec5SDimitry Andric   ScheduleDAGInstrs *createMachineScheduler();
2230b57cec5SDimitry Andric };
2240b57cec5SDimitry Andric 
2250b57cec5SDimitry Andric /// PostMachineScheduler runs after shortly before code emission.
2260b57cec5SDimitry Andric class PostMachineScheduler : public MachineSchedulerBase {
2270b57cec5SDimitry Andric public:
2280b57cec5SDimitry Andric   PostMachineScheduler();
2290b57cec5SDimitry Andric 
2300b57cec5SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override;
2310b57cec5SDimitry Andric 
2320b57cec5SDimitry Andric   bool runOnMachineFunction(MachineFunction&) override;
2330b57cec5SDimitry Andric 
2340b57cec5SDimitry Andric   static char ID; // Class identification, replacement for typeinfo
2350b57cec5SDimitry Andric 
2360b57cec5SDimitry Andric protected:
2370b57cec5SDimitry Andric   ScheduleDAGInstrs *createPostMachineScheduler();
2380b57cec5SDimitry Andric };
2390b57cec5SDimitry Andric 
2400b57cec5SDimitry Andric } // end anonymous namespace
2410b57cec5SDimitry Andric 
2420b57cec5SDimitry Andric char MachineScheduler::ID = 0;
2430b57cec5SDimitry Andric 
2440b57cec5SDimitry Andric char &llvm::MachineSchedulerID = MachineScheduler::ID;
2450b57cec5SDimitry Andric 
2460b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(MachineScheduler, DEBUG_TYPE,
2470b57cec5SDimitry Andric                       "Machine Instruction Scheduler", false, false)
INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)2480b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
2498bcb0991SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
2500b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
2510b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
2520b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
2530b57cec5SDimitry Andric INITIALIZE_PASS_END(MachineScheduler, DEBUG_TYPE,
2540b57cec5SDimitry Andric                     "Machine Instruction Scheduler", false, false)
2550b57cec5SDimitry Andric 
2560b57cec5SDimitry Andric MachineScheduler::MachineScheduler() : MachineSchedulerBase(ID) {
2570b57cec5SDimitry Andric   initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
2580b57cec5SDimitry Andric }
2590b57cec5SDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const2600b57cec5SDimitry Andric void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
2610b57cec5SDimitry Andric   AU.setPreservesCFG();
2628bcb0991SDimitry Andric   AU.addRequired<MachineDominatorTree>();
2630b57cec5SDimitry Andric   AU.addRequired<MachineLoopInfo>();
2640b57cec5SDimitry Andric   AU.addRequired<AAResultsWrapperPass>();
2650b57cec5SDimitry Andric   AU.addRequired<TargetPassConfig>();
2660b57cec5SDimitry Andric   AU.addRequired<SlotIndexes>();
2670b57cec5SDimitry Andric   AU.addPreserved<SlotIndexes>();
2680b57cec5SDimitry Andric   AU.addRequired<LiveIntervals>();
2690b57cec5SDimitry Andric   AU.addPreserved<LiveIntervals>();
2700b57cec5SDimitry Andric   MachineFunctionPass::getAnalysisUsage(AU);
2710b57cec5SDimitry Andric }
2720b57cec5SDimitry Andric 
2730b57cec5SDimitry Andric char PostMachineScheduler::ID = 0;
2740b57cec5SDimitry Andric 
2750b57cec5SDimitry Andric char &llvm::PostMachineSchedulerID = PostMachineScheduler::ID;
2760b57cec5SDimitry Andric 
277e8d8bef9SDimitry Andric INITIALIZE_PASS_BEGIN(PostMachineScheduler, "postmisched",
278e8d8bef9SDimitry Andric                       "PostRA Machine Instruction Scheduler", false, false)
INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)279e8d8bef9SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
280e8d8bef9SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
281e8d8bef9SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
282e8d8bef9SDimitry Andric INITIALIZE_PASS_END(PostMachineScheduler, "postmisched",
2830b57cec5SDimitry Andric                     "PostRA Machine Instruction Scheduler", false, false)
2840b57cec5SDimitry Andric 
2850b57cec5SDimitry Andric PostMachineScheduler::PostMachineScheduler() : MachineSchedulerBase(ID) {
2860b57cec5SDimitry Andric   initializePostMachineSchedulerPass(*PassRegistry::getPassRegistry());
2870b57cec5SDimitry Andric }
2880b57cec5SDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const2890b57cec5SDimitry Andric void PostMachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
2900b57cec5SDimitry Andric   AU.setPreservesCFG();
2918bcb0991SDimitry Andric   AU.addRequired<MachineDominatorTree>();
2920b57cec5SDimitry Andric   AU.addRequired<MachineLoopInfo>();
293480093f4SDimitry Andric   AU.addRequired<AAResultsWrapperPass>();
2940b57cec5SDimitry Andric   AU.addRequired<TargetPassConfig>();
2950b57cec5SDimitry Andric   MachineFunctionPass::getAnalysisUsage(AU);
2960b57cec5SDimitry Andric }
2970b57cec5SDimitry Andric 
2980b57cec5SDimitry Andric MachinePassRegistry<MachineSchedRegistry::ScheduleDAGCtor>
2990b57cec5SDimitry Andric     MachineSchedRegistry::Registry;
3000b57cec5SDimitry Andric 
3010b57cec5SDimitry Andric /// A dummy default scheduler factory indicates whether the scheduler
3020b57cec5SDimitry Andric /// is overridden on the command line.
useDefaultMachineSched(MachineSchedContext * C)3030b57cec5SDimitry Andric static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
3040b57cec5SDimitry Andric   return nullptr;
3050b57cec5SDimitry Andric }
3060b57cec5SDimitry Andric 
3070b57cec5SDimitry Andric /// MachineSchedOpt allows command line selection of the scheduler.
3080b57cec5SDimitry Andric static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
3090b57cec5SDimitry Andric                RegisterPassParser<MachineSchedRegistry>>
3100b57cec5SDimitry Andric MachineSchedOpt("misched",
3110b57cec5SDimitry Andric                 cl::init(&useDefaultMachineSched), cl::Hidden,
3120b57cec5SDimitry Andric                 cl::desc("Machine instruction scheduler to use"));
3130b57cec5SDimitry Andric 
3140b57cec5SDimitry Andric static MachineSchedRegistry
3150b57cec5SDimitry Andric DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
3160b57cec5SDimitry Andric                      useDefaultMachineSched);
3170b57cec5SDimitry Andric 
3180b57cec5SDimitry Andric static cl::opt<bool> EnableMachineSched(
3190b57cec5SDimitry Andric     "enable-misched",
3200b57cec5SDimitry Andric     cl::desc("Enable the machine instruction scheduling pass."), cl::init(true),
3210b57cec5SDimitry Andric     cl::Hidden);
3220b57cec5SDimitry Andric 
3230b57cec5SDimitry Andric static cl::opt<bool> EnablePostRAMachineSched(
3240b57cec5SDimitry Andric     "enable-post-misched",
3250b57cec5SDimitry Andric     cl::desc("Enable the post-ra machine instruction scheduling pass."),
3260b57cec5SDimitry Andric     cl::init(true), cl::Hidden);
3270b57cec5SDimitry Andric 
3280b57cec5SDimitry Andric /// Decrement this iterator until reaching the top or a non-debug instr.
3290b57cec5SDimitry Andric static MachineBasicBlock::const_iterator
priorNonDebug(MachineBasicBlock::const_iterator I,MachineBasicBlock::const_iterator Beg)3300b57cec5SDimitry Andric priorNonDebug(MachineBasicBlock::const_iterator I,
3310b57cec5SDimitry Andric               MachineBasicBlock::const_iterator Beg) {
3320b57cec5SDimitry Andric   assert(I != Beg && "reached the top of the region, cannot decrement");
3330b57cec5SDimitry Andric   while (--I != Beg) {
334fe6060f1SDimitry Andric     if (!I->isDebugOrPseudoInstr())
3350b57cec5SDimitry Andric       break;
3360b57cec5SDimitry Andric   }
3370b57cec5SDimitry Andric   return I;
3380b57cec5SDimitry Andric }
3390b57cec5SDimitry Andric 
3400b57cec5SDimitry Andric /// Non-const version.
3410b57cec5SDimitry Andric static MachineBasicBlock::iterator
priorNonDebug(MachineBasicBlock::iterator I,MachineBasicBlock::const_iterator Beg)3420b57cec5SDimitry Andric priorNonDebug(MachineBasicBlock::iterator I,
3430b57cec5SDimitry Andric               MachineBasicBlock::const_iterator Beg) {
3440b57cec5SDimitry Andric   return priorNonDebug(MachineBasicBlock::const_iterator(I), Beg)
3450b57cec5SDimitry Andric       .getNonConstIterator();
3460b57cec5SDimitry Andric }
3470b57cec5SDimitry Andric 
3480b57cec5SDimitry Andric /// If this iterator is a debug value, increment until reaching the End or a
3490b57cec5SDimitry Andric /// non-debug instruction.
3500b57cec5SDimitry Andric static MachineBasicBlock::const_iterator
nextIfDebug(MachineBasicBlock::const_iterator I,MachineBasicBlock::const_iterator End)3510b57cec5SDimitry Andric nextIfDebug(MachineBasicBlock::const_iterator I,
3520b57cec5SDimitry Andric             MachineBasicBlock::const_iterator End) {
3530b57cec5SDimitry Andric   for(; I != End; ++I) {
354fe6060f1SDimitry Andric     if (!I->isDebugOrPseudoInstr())
3550b57cec5SDimitry Andric       break;
3560b57cec5SDimitry Andric   }
3570b57cec5SDimitry Andric   return I;
3580b57cec5SDimitry Andric }
3590b57cec5SDimitry Andric 
3600b57cec5SDimitry Andric /// Non-const version.
3610b57cec5SDimitry Andric static MachineBasicBlock::iterator
nextIfDebug(MachineBasicBlock::iterator I,MachineBasicBlock::const_iterator End)3620b57cec5SDimitry Andric nextIfDebug(MachineBasicBlock::iterator I,
3630b57cec5SDimitry Andric             MachineBasicBlock::const_iterator End) {
3640b57cec5SDimitry Andric   return nextIfDebug(MachineBasicBlock::const_iterator(I), End)
3650b57cec5SDimitry Andric       .getNonConstIterator();
3660b57cec5SDimitry Andric }
3670b57cec5SDimitry Andric 
3680b57cec5SDimitry Andric /// Instantiate a ScheduleDAGInstrs that will be owned by the caller.
createMachineScheduler()3690b57cec5SDimitry Andric ScheduleDAGInstrs *MachineScheduler::createMachineScheduler() {
3700b57cec5SDimitry Andric   // Select the scheduler, or set the default.
3710b57cec5SDimitry Andric   MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
3720b57cec5SDimitry Andric   if (Ctor != useDefaultMachineSched)
3730b57cec5SDimitry Andric     return Ctor(this);
3740b57cec5SDimitry Andric 
3750b57cec5SDimitry Andric   // Get the default scheduler set by the target for this function.
3760b57cec5SDimitry Andric   ScheduleDAGInstrs *Scheduler = PassConfig->createMachineScheduler(this);
3770b57cec5SDimitry Andric   if (Scheduler)
3780b57cec5SDimitry Andric     return Scheduler;
3790b57cec5SDimitry Andric 
3800b57cec5SDimitry Andric   // Default to GenericScheduler.
3810b57cec5SDimitry Andric   return createGenericSchedLive(this);
3820b57cec5SDimitry Andric }
3830b57cec5SDimitry Andric 
3840b57cec5SDimitry Andric /// Instantiate a ScheduleDAGInstrs for PostRA scheduling that will be owned by
3850b57cec5SDimitry Andric /// the caller. We don't have a command line option to override the postRA
3860b57cec5SDimitry Andric /// scheduler. The Target must configure it.
createPostMachineScheduler()3870b57cec5SDimitry Andric ScheduleDAGInstrs *PostMachineScheduler::createPostMachineScheduler() {
3880b57cec5SDimitry Andric   // Get the postRA scheduler set by the target for this function.
3890b57cec5SDimitry Andric   ScheduleDAGInstrs *Scheduler = PassConfig->createPostMachineScheduler(this);
3900b57cec5SDimitry Andric   if (Scheduler)
3910b57cec5SDimitry Andric     return Scheduler;
3920b57cec5SDimitry Andric 
3930b57cec5SDimitry Andric   // Default to GenericScheduler.
3940b57cec5SDimitry Andric   return createGenericSchedPostRA(this);
3950b57cec5SDimitry Andric }
3960b57cec5SDimitry Andric 
3970b57cec5SDimitry Andric /// Top-level MachineScheduler pass driver.
3980b57cec5SDimitry Andric ///
3990b57cec5SDimitry Andric /// Visit blocks in function order. Divide each block into scheduling regions
4000b57cec5SDimitry Andric /// and visit them bottom-up. Visiting regions bottom-up is not required, but is
4010b57cec5SDimitry Andric /// consistent with the DAG builder, which traverses the interior of the
4020b57cec5SDimitry Andric /// scheduling regions bottom-up.
4030b57cec5SDimitry Andric ///
4040b57cec5SDimitry Andric /// This design avoids exposing scheduling boundaries to the DAG builder,
4050b57cec5SDimitry Andric /// simplifying the DAG builder's support for "special" target instructions.
4060b57cec5SDimitry Andric /// At the same time the design allows target schedulers to operate across
4070b57cec5SDimitry Andric /// scheduling boundaries, for example to bundle the boundary instructions
4080b57cec5SDimitry Andric /// without reordering them. This creates complexity, because the target
4090b57cec5SDimitry Andric /// scheduler must update the RegionBegin and RegionEnd positions cached by
4100b57cec5SDimitry Andric /// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
4110b57cec5SDimitry Andric /// design would be to split blocks at scheduling boundaries, but LLVM has a
4120b57cec5SDimitry Andric /// general bias against block splitting purely for implementation simplicity.
runOnMachineFunction(MachineFunction & mf)4130b57cec5SDimitry Andric bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
4140b57cec5SDimitry Andric   if (skipFunction(mf.getFunction()))
4150b57cec5SDimitry Andric     return false;
4160b57cec5SDimitry Andric 
4170b57cec5SDimitry Andric   if (EnableMachineSched.getNumOccurrences()) {
4180b57cec5SDimitry Andric     if (!EnableMachineSched)
4190b57cec5SDimitry Andric       return false;
4200b57cec5SDimitry Andric   } else if (!mf.getSubtarget().enableMachineScheduler())
4210b57cec5SDimitry Andric     return false;
4220b57cec5SDimitry Andric 
4230b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Before MISched:\n"; mf.print(dbgs()));
4240b57cec5SDimitry Andric 
4250b57cec5SDimitry Andric   // Initialize the context of the pass.
4260b57cec5SDimitry Andric   MF = &mf;
4270b57cec5SDimitry Andric   MLI = &getAnalysis<MachineLoopInfo>();
4280b57cec5SDimitry Andric   MDT = &getAnalysis<MachineDominatorTree>();
4290b57cec5SDimitry Andric   PassConfig = &getAnalysis<TargetPassConfig>();
4300b57cec5SDimitry Andric   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
4310b57cec5SDimitry Andric 
4320b57cec5SDimitry Andric   LIS = &getAnalysis<LiveIntervals>();
4330b57cec5SDimitry Andric 
4340b57cec5SDimitry Andric   if (VerifyScheduling) {
4350b57cec5SDimitry Andric     LLVM_DEBUG(LIS->dump());
4360b57cec5SDimitry Andric     MF->verify(this, "Before machine scheduling.");
4370b57cec5SDimitry Andric   }
4380b57cec5SDimitry Andric   RegClassInfo->runOnMachineFunction(*MF);
4390b57cec5SDimitry Andric 
4400b57cec5SDimitry Andric   // Instantiate the selected scheduler for this target, function, and
4410b57cec5SDimitry Andric   // optimization level.
4420b57cec5SDimitry Andric   std::unique_ptr<ScheduleDAGInstrs> Scheduler(createMachineScheduler());
4430b57cec5SDimitry Andric   scheduleRegions(*Scheduler, false);
4440b57cec5SDimitry Andric 
4450b57cec5SDimitry Andric   LLVM_DEBUG(LIS->dump());
4460b57cec5SDimitry Andric   if (VerifyScheduling)
4470b57cec5SDimitry Andric     MF->verify(this, "After machine scheduling.");
4480b57cec5SDimitry Andric   return true;
4490b57cec5SDimitry Andric }
4500b57cec5SDimitry Andric 
runOnMachineFunction(MachineFunction & mf)4510b57cec5SDimitry Andric bool PostMachineScheduler::runOnMachineFunction(MachineFunction &mf) {
4520b57cec5SDimitry Andric   if (skipFunction(mf.getFunction()))
4530b57cec5SDimitry Andric     return false;
4540b57cec5SDimitry Andric 
4550b57cec5SDimitry Andric   if (EnablePostRAMachineSched.getNumOccurrences()) {
4560b57cec5SDimitry Andric     if (!EnablePostRAMachineSched)
4570b57cec5SDimitry Andric       return false;
458480093f4SDimitry Andric   } else if (!mf.getSubtarget().enablePostRAMachineScheduler()) {
4590b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Subtarget disables post-MI-sched.\n");
4600b57cec5SDimitry Andric     return false;
4610b57cec5SDimitry Andric   }
4620b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Before post-MI-sched:\n"; mf.print(dbgs()));
4630b57cec5SDimitry Andric 
4640b57cec5SDimitry Andric   // Initialize the context of the pass.
4650b57cec5SDimitry Andric   MF = &mf;
4660b57cec5SDimitry Andric   MLI = &getAnalysis<MachineLoopInfo>();
4670b57cec5SDimitry Andric   PassConfig = &getAnalysis<TargetPassConfig>();
468480093f4SDimitry Andric   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
4690b57cec5SDimitry Andric 
4700b57cec5SDimitry Andric   if (VerifyScheduling)
4710b57cec5SDimitry Andric     MF->verify(this, "Before post machine scheduling.");
4720b57cec5SDimitry Andric 
4730b57cec5SDimitry Andric   // Instantiate the selected scheduler for this target, function, and
4740b57cec5SDimitry Andric   // optimization level.
4750b57cec5SDimitry Andric   std::unique_ptr<ScheduleDAGInstrs> Scheduler(createPostMachineScheduler());
4760b57cec5SDimitry Andric   scheduleRegions(*Scheduler, true);
4770b57cec5SDimitry Andric 
4780b57cec5SDimitry Andric   if (VerifyScheduling)
4790b57cec5SDimitry Andric     MF->verify(this, "After post machine scheduling.");
4800b57cec5SDimitry Andric   return true;
4810b57cec5SDimitry Andric }
4820b57cec5SDimitry Andric 
4830b57cec5SDimitry Andric /// Return true of the given instruction should not be included in a scheduling
4840b57cec5SDimitry Andric /// region.
4850b57cec5SDimitry Andric ///
4860b57cec5SDimitry Andric /// MachineScheduler does not currently support scheduling across calls. To
4870b57cec5SDimitry Andric /// handle calls, the DAG builder needs to be modified to create register
4880b57cec5SDimitry Andric /// anti/output dependencies on the registers clobbered by the call's regmask
4890b57cec5SDimitry Andric /// operand. In PreRA scheduling, the stack pointer adjustment already prevents
4900b57cec5SDimitry Andric /// scheduling across calls. In PostRA scheduling, we need the isCall to enforce
4910b57cec5SDimitry Andric /// the boundary, but there would be no benefit to postRA scheduling across
4920b57cec5SDimitry Andric /// calls this late anyway.
isSchedBoundary(MachineBasicBlock::iterator MI,MachineBasicBlock * MBB,MachineFunction * MF,const TargetInstrInfo * TII)4930b57cec5SDimitry Andric static bool isSchedBoundary(MachineBasicBlock::iterator MI,
4940b57cec5SDimitry Andric                             MachineBasicBlock *MBB,
4950b57cec5SDimitry Andric                             MachineFunction *MF,
4960b57cec5SDimitry Andric                             const TargetInstrInfo *TII) {
4970b57cec5SDimitry Andric   return MI->isCall() || TII->isSchedulingBoundary(*MI, MBB, *MF);
4980b57cec5SDimitry Andric }
4990b57cec5SDimitry Andric 
5000b57cec5SDimitry Andric /// A region of an MBB for scheduling.
5010b57cec5SDimitry Andric namespace {
5020b57cec5SDimitry Andric struct SchedRegion {
5030b57cec5SDimitry Andric   /// RegionBegin is the first instruction in the scheduling region, and
5040b57cec5SDimitry Andric   /// RegionEnd is either MBB->end() or the scheduling boundary after the
5050b57cec5SDimitry Andric   /// last instruction in the scheduling region. These iterators cannot refer
5060b57cec5SDimitry Andric   /// to instructions outside of the identified scheduling region because
5070b57cec5SDimitry Andric   /// those may be reordered before scheduling this region.
5080b57cec5SDimitry Andric   MachineBasicBlock::iterator RegionBegin;
5090b57cec5SDimitry Andric   MachineBasicBlock::iterator RegionEnd;
5100b57cec5SDimitry Andric   unsigned NumRegionInstrs;
5110b57cec5SDimitry Andric 
SchedRegion__anon83be91fe0211::SchedRegion5120b57cec5SDimitry Andric   SchedRegion(MachineBasicBlock::iterator B, MachineBasicBlock::iterator E,
5130b57cec5SDimitry Andric               unsigned N) :
5140b57cec5SDimitry Andric     RegionBegin(B), RegionEnd(E), NumRegionInstrs(N) {}
5150b57cec5SDimitry Andric };
5160b57cec5SDimitry Andric } // end anonymous namespace
5170b57cec5SDimitry Andric 
5180b57cec5SDimitry Andric using MBBRegionsVector = SmallVector<SchedRegion, 16>;
5190b57cec5SDimitry Andric 
5200b57cec5SDimitry Andric static void
getSchedRegions(MachineBasicBlock * MBB,MBBRegionsVector & Regions,bool RegionsTopDown)5210b57cec5SDimitry Andric getSchedRegions(MachineBasicBlock *MBB,
5220b57cec5SDimitry Andric                 MBBRegionsVector &Regions,
5230b57cec5SDimitry Andric                 bool RegionsTopDown) {
5240b57cec5SDimitry Andric   MachineFunction *MF = MBB->getParent();
5250b57cec5SDimitry Andric   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
5260b57cec5SDimitry Andric 
5270b57cec5SDimitry Andric   MachineBasicBlock::iterator I = nullptr;
5280b57cec5SDimitry Andric   for(MachineBasicBlock::iterator RegionEnd = MBB->end();
5290b57cec5SDimitry Andric       RegionEnd != MBB->begin(); RegionEnd = I) {
5300b57cec5SDimitry Andric 
5310b57cec5SDimitry Andric     // Avoid decrementing RegionEnd for blocks with no terminator.
5320b57cec5SDimitry Andric     if (RegionEnd != MBB->end() ||
5330b57cec5SDimitry Andric         isSchedBoundary(&*std::prev(RegionEnd), &*MBB, MF, TII)) {
5340b57cec5SDimitry Andric       --RegionEnd;
5350b57cec5SDimitry Andric     }
5360b57cec5SDimitry Andric 
5370b57cec5SDimitry Andric     // The next region starts above the previous region. Look backward in the
5380b57cec5SDimitry Andric     // instruction stream until we find the nearest boundary.
5390b57cec5SDimitry Andric     unsigned NumRegionInstrs = 0;
5400b57cec5SDimitry Andric     I = RegionEnd;
5410b57cec5SDimitry Andric     for (;I != MBB->begin(); --I) {
5420b57cec5SDimitry Andric       MachineInstr &MI = *std::prev(I);
5430b57cec5SDimitry Andric       if (isSchedBoundary(&MI, &*MBB, MF, TII))
5440b57cec5SDimitry Andric         break;
545fe6060f1SDimitry Andric       if (!MI.isDebugOrPseudoInstr()) {
5460b57cec5SDimitry Andric         // MBB::size() uses instr_iterator to count. Here we need a bundle to
5470b57cec5SDimitry Andric         // count as a single instruction.
5480b57cec5SDimitry Andric         ++NumRegionInstrs;
5490b57cec5SDimitry Andric       }
5500b57cec5SDimitry Andric     }
5510b57cec5SDimitry Andric 
5520b57cec5SDimitry Andric     // It's possible we found a scheduling region that only has debug
5530b57cec5SDimitry Andric     // instructions. Don't bother scheduling these.
5540b57cec5SDimitry Andric     if (NumRegionInstrs != 0)
5550b57cec5SDimitry Andric       Regions.push_back(SchedRegion(I, RegionEnd, NumRegionInstrs));
5560b57cec5SDimitry Andric   }
5570b57cec5SDimitry Andric 
5580b57cec5SDimitry Andric   if (RegionsTopDown)
5590b57cec5SDimitry Andric     std::reverse(Regions.begin(), Regions.end());
5600b57cec5SDimitry Andric }
5610b57cec5SDimitry Andric 
5620b57cec5SDimitry Andric /// Main driver for both MachineScheduler and PostMachineScheduler.
scheduleRegions(ScheduleDAGInstrs & Scheduler,bool FixKillFlags)5630b57cec5SDimitry Andric void MachineSchedulerBase::scheduleRegions(ScheduleDAGInstrs &Scheduler,
5640b57cec5SDimitry Andric                                            bool FixKillFlags) {
5650b57cec5SDimitry Andric   // Visit all machine basic blocks.
5660b57cec5SDimitry Andric   //
5670b57cec5SDimitry Andric   // TODO: Visit blocks in global postorder or postorder within the bottom-up
5680b57cec5SDimitry Andric   // loop tree. Then we can optionally compute global RegPressure.
5690b57cec5SDimitry Andric   for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
5700b57cec5SDimitry Andric        MBB != MBBEnd; ++MBB) {
5710b57cec5SDimitry Andric 
5720b57cec5SDimitry Andric     Scheduler.startBlock(&*MBB);
5730b57cec5SDimitry Andric 
5740b57cec5SDimitry Andric #ifndef NDEBUG
5750b57cec5SDimitry Andric     if (SchedOnlyFunc.getNumOccurrences() && SchedOnlyFunc != MF->getName())
5760b57cec5SDimitry Andric       continue;
5770b57cec5SDimitry Andric     if (SchedOnlyBlock.getNumOccurrences()
5780b57cec5SDimitry Andric         && (int)SchedOnlyBlock != MBB->getNumber())
5790b57cec5SDimitry Andric       continue;
5800b57cec5SDimitry Andric #endif
5810b57cec5SDimitry Andric 
5820b57cec5SDimitry Andric     // Break the block into scheduling regions [I, RegionEnd). RegionEnd
5830b57cec5SDimitry Andric     // points to the scheduling boundary at the bottom of the region. The DAG
5840b57cec5SDimitry Andric     // does not include RegionEnd, but the region does (i.e. the next
5850b57cec5SDimitry Andric     // RegionEnd is above the previous RegionBegin). If the current block has
5860b57cec5SDimitry Andric     // no terminator then RegionEnd == MBB->end() for the bottom region.
5870b57cec5SDimitry Andric     //
5880b57cec5SDimitry Andric     // All the regions of MBB are first found and stored in MBBRegions, which
5890b57cec5SDimitry Andric     // will be processed (MBB) top-down if initialized with true.
5900b57cec5SDimitry Andric     //
5910b57cec5SDimitry Andric     // The Scheduler may insert instructions during either schedule() or
5920b57cec5SDimitry Andric     // exitRegion(), even for empty regions. So the local iterators 'I' and
5930b57cec5SDimitry Andric     // 'RegionEnd' are invalid across these calls. Instructions must not be
5940b57cec5SDimitry Andric     // added to other regions than the current one without updating MBBRegions.
5950b57cec5SDimitry Andric 
5960b57cec5SDimitry Andric     MBBRegionsVector MBBRegions;
5970b57cec5SDimitry Andric     getSchedRegions(&*MBB, MBBRegions, Scheduler.doMBBSchedRegionsTopDown());
5980eae32dcSDimitry Andric     for (const SchedRegion &R : MBBRegions) {
5990eae32dcSDimitry Andric       MachineBasicBlock::iterator I = R.RegionBegin;
6000eae32dcSDimitry Andric       MachineBasicBlock::iterator RegionEnd = R.RegionEnd;
6010eae32dcSDimitry Andric       unsigned NumRegionInstrs = R.NumRegionInstrs;
6020b57cec5SDimitry Andric 
6030b57cec5SDimitry Andric       // Notify the scheduler of the region, even if we may skip scheduling
6040b57cec5SDimitry Andric       // it. Perhaps it still needs to be bundled.
6050b57cec5SDimitry Andric       Scheduler.enterRegion(&*MBB, I, RegionEnd, NumRegionInstrs);
6060b57cec5SDimitry Andric 
6070b57cec5SDimitry Andric       // Skip empty scheduling regions (0 or 1 schedulable instructions).
6080b57cec5SDimitry Andric       if (I == RegionEnd || I == std::prev(RegionEnd)) {
6090b57cec5SDimitry Andric         // Close the current region. Bundle the terminator if needed.
6100b57cec5SDimitry Andric         // This invalidates 'RegionEnd' and 'I'.
6110b57cec5SDimitry Andric         Scheduler.exitRegion();
6120b57cec5SDimitry Andric         continue;
6130b57cec5SDimitry Andric       }
6140b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "********** MI Scheduling **********\n");
6150b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << MF->getName() << ":" << printMBBReference(*MBB)
6160b57cec5SDimitry Andric                         << " " << MBB->getName() << "\n  From: " << *I
6170b57cec5SDimitry Andric                         << "    To: ";
6180b57cec5SDimitry Andric                  if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
619349cc55cSDimitry Andric                  else dbgs() << "End\n";
6200b57cec5SDimitry Andric                  dbgs() << " RegionInstrs: " << NumRegionInstrs << '\n');
6210b57cec5SDimitry Andric       if (DumpCriticalPathLength) {
6220b57cec5SDimitry Andric         errs() << MF->getName();
6230b57cec5SDimitry Andric         errs() << ":%bb. " << MBB->getNumber();
6240b57cec5SDimitry Andric         errs() << " " << MBB->getName() << " \n";
6250b57cec5SDimitry Andric       }
6260b57cec5SDimitry Andric 
6270b57cec5SDimitry Andric       // Schedule a region: possibly reorder instructions.
6280b57cec5SDimitry Andric       // This invalidates the original region iterators.
6290b57cec5SDimitry Andric       Scheduler.schedule();
6300b57cec5SDimitry Andric 
6310b57cec5SDimitry Andric       // Close the current region.
6320b57cec5SDimitry Andric       Scheduler.exitRegion();
6330b57cec5SDimitry Andric     }
6340b57cec5SDimitry Andric     Scheduler.finishBlock();
6350b57cec5SDimitry Andric     // FIXME: Ideally, no further passes should rely on kill flags. However,
6360b57cec5SDimitry Andric     // thumb2 size reduction is currently an exception, so the PostMIScheduler
6370b57cec5SDimitry Andric     // needs to do this.
6380b57cec5SDimitry Andric     if (FixKillFlags)
6390b57cec5SDimitry Andric       Scheduler.fixupKills(*MBB);
6400b57cec5SDimitry Andric   }
6410b57cec5SDimitry Andric   Scheduler.finalizeSchedule();
6420b57cec5SDimitry Andric }
6430b57cec5SDimitry Andric 
print(raw_ostream & O,const Module * m) const6440b57cec5SDimitry Andric void MachineSchedulerBase::print(raw_ostream &O, const Module* m) const {
6450b57cec5SDimitry Andric   // unimplemented
6460b57cec5SDimitry Andric }
6470b57cec5SDimitry Andric 
6480b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump() const6490b57cec5SDimitry Andric LLVM_DUMP_METHOD void ReadyQueue::dump() const {
6500b57cec5SDimitry Andric   dbgs() << "Queue " << Name << ": ";
6510b57cec5SDimitry Andric   for (const SUnit *SU : Queue)
6520b57cec5SDimitry Andric     dbgs() << SU->NodeNum << " ";
6530b57cec5SDimitry Andric   dbgs() << "\n";
6540b57cec5SDimitry Andric }
6550b57cec5SDimitry Andric #endif
6560b57cec5SDimitry Andric 
6570b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
6580b57cec5SDimitry Andric // ScheduleDAGMI - Basic machine instruction scheduling. This is
6590b57cec5SDimitry Andric // independent of PreRA/PostRA scheduling and involves no extra book-keeping for
6600b57cec5SDimitry Andric // virtual registers.
6610b57cec5SDimitry Andric // ===----------------------------------------------------------------------===/
6620b57cec5SDimitry Andric 
6630b57cec5SDimitry Andric // Provide a vtable anchor.
6640b57cec5SDimitry Andric ScheduleDAGMI::~ScheduleDAGMI() = default;
6650b57cec5SDimitry Andric 
6660b57cec5SDimitry Andric /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
6670b57cec5SDimitry Andric /// NumPredsLeft reaches zero, release the successor node.
6680b57cec5SDimitry Andric ///
6690b57cec5SDimitry Andric /// FIXME: Adjust SuccSU height based on MinLatency.
releaseSucc(SUnit * SU,SDep * SuccEdge)6700b57cec5SDimitry Andric void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
6710b57cec5SDimitry Andric   SUnit *SuccSU = SuccEdge->getSUnit();
6720b57cec5SDimitry Andric 
6730b57cec5SDimitry Andric   if (SuccEdge->isWeak()) {
6740b57cec5SDimitry Andric     --SuccSU->WeakPredsLeft;
6750b57cec5SDimitry Andric     if (SuccEdge->isCluster())
6760b57cec5SDimitry Andric       NextClusterSucc = SuccSU;
6770b57cec5SDimitry Andric     return;
6780b57cec5SDimitry Andric   }
6790b57cec5SDimitry Andric #ifndef NDEBUG
6800b57cec5SDimitry Andric   if (SuccSU->NumPredsLeft == 0) {
6810b57cec5SDimitry Andric     dbgs() << "*** Scheduling failed! ***\n";
6820b57cec5SDimitry Andric     dumpNode(*SuccSU);
6830b57cec5SDimitry Andric     dbgs() << " has been released too many times!\n";
6840b57cec5SDimitry Andric     llvm_unreachable(nullptr);
6850b57cec5SDimitry Andric   }
6860b57cec5SDimitry Andric #endif
6870b57cec5SDimitry Andric   // SU->TopReadyCycle was set to CurrCycle when it was scheduled. However,
6880b57cec5SDimitry Andric   // CurrCycle may have advanced since then.
6890b57cec5SDimitry Andric   if (SuccSU->TopReadyCycle < SU->TopReadyCycle + SuccEdge->getLatency())
6900b57cec5SDimitry Andric     SuccSU->TopReadyCycle = SU->TopReadyCycle + SuccEdge->getLatency();
6910b57cec5SDimitry Andric 
6920b57cec5SDimitry Andric   --SuccSU->NumPredsLeft;
6930b57cec5SDimitry Andric   if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
6940b57cec5SDimitry Andric     SchedImpl->releaseTopNode(SuccSU);
6950b57cec5SDimitry Andric }
6960b57cec5SDimitry Andric 
6970b57cec5SDimitry Andric /// releaseSuccessors - Call releaseSucc on each of SU's successors.
releaseSuccessors(SUnit * SU)6980b57cec5SDimitry Andric void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
6990b57cec5SDimitry Andric   for (SDep &Succ : SU->Succs)
7000b57cec5SDimitry Andric     releaseSucc(SU, &Succ);
7010b57cec5SDimitry Andric }
7020b57cec5SDimitry Andric 
7030b57cec5SDimitry Andric /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
7040b57cec5SDimitry Andric /// NumSuccsLeft reaches zero, release the predecessor node.
7050b57cec5SDimitry Andric ///
7060b57cec5SDimitry Andric /// FIXME: Adjust PredSU height based on MinLatency.
releasePred(SUnit * SU,SDep * PredEdge)7070b57cec5SDimitry Andric void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
7080b57cec5SDimitry Andric   SUnit *PredSU = PredEdge->getSUnit();
7090b57cec5SDimitry Andric 
7100b57cec5SDimitry Andric   if (PredEdge->isWeak()) {
7110b57cec5SDimitry Andric     --PredSU->WeakSuccsLeft;
7120b57cec5SDimitry Andric     if (PredEdge->isCluster())
7130b57cec5SDimitry Andric       NextClusterPred = PredSU;
7140b57cec5SDimitry Andric     return;
7150b57cec5SDimitry Andric   }
7160b57cec5SDimitry Andric #ifndef NDEBUG
7170b57cec5SDimitry Andric   if (PredSU->NumSuccsLeft == 0) {
7180b57cec5SDimitry Andric     dbgs() << "*** Scheduling failed! ***\n";
7190b57cec5SDimitry Andric     dumpNode(*PredSU);
7200b57cec5SDimitry Andric     dbgs() << " has been released too many times!\n";
7210b57cec5SDimitry Andric     llvm_unreachable(nullptr);
7220b57cec5SDimitry Andric   }
7230b57cec5SDimitry Andric #endif
7240b57cec5SDimitry Andric   // SU->BotReadyCycle was set to CurrCycle when it was scheduled. However,
7250b57cec5SDimitry Andric   // CurrCycle may have advanced since then.
7260b57cec5SDimitry Andric   if (PredSU->BotReadyCycle < SU->BotReadyCycle + PredEdge->getLatency())
7270b57cec5SDimitry Andric     PredSU->BotReadyCycle = SU->BotReadyCycle + PredEdge->getLatency();
7280b57cec5SDimitry Andric 
7290b57cec5SDimitry Andric   --PredSU->NumSuccsLeft;
7300b57cec5SDimitry Andric   if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
7310b57cec5SDimitry Andric     SchedImpl->releaseBottomNode(PredSU);
7320b57cec5SDimitry Andric }
7330b57cec5SDimitry Andric 
7340b57cec5SDimitry Andric /// releasePredecessors - Call releasePred on each of SU's predecessors.
releasePredecessors(SUnit * SU)7350b57cec5SDimitry Andric void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
7360b57cec5SDimitry Andric   for (SDep &Pred : SU->Preds)
7370b57cec5SDimitry Andric     releasePred(SU, &Pred);
7380b57cec5SDimitry Andric }
7390b57cec5SDimitry Andric 
startBlock(MachineBasicBlock * bb)7400b57cec5SDimitry Andric void ScheduleDAGMI::startBlock(MachineBasicBlock *bb) {
7410b57cec5SDimitry Andric   ScheduleDAGInstrs::startBlock(bb);
7420b57cec5SDimitry Andric   SchedImpl->enterMBB(bb);
7430b57cec5SDimitry Andric }
7440b57cec5SDimitry Andric 
finishBlock()7450b57cec5SDimitry Andric void ScheduleDAGMI::finishBlock() {
7460b57cec5SDimitry Andric   SchedImpl->leaveMBB();
7470b57cec5SDimitry Andric   ScheduleDAGInstrs::finishBlock();
7480b57cec5SDimitry Andric }
7490b57cec5SDimitry Andric 
750c9157d92SDimitry Andric /// enterRegion - Called back from PostMachineScheduler::runOnMachineFunction
751c9157d92SDimitry Andric /// after crossing a scheduling boundary. [begin, end) includes all instructions
752c9157d92SDimitry Andric /// in the region, including the boundary itself and single-instruction regions
7530b57cec5SDimitry Andric /// that don't get scheduled.
enterRegion(MachineBasicBlock * bb,MachineBasicBlock::iterator begin,MachineBasicBlock::iterator end,unsigned regioninstrs)7540b57cec5SDimitry Andric void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
7550b57cec5SDimitry Andric                                      MachineBasicBlock::iterator begin,
7560b57cec5SDimitry Andric                                      MachineBasicBlock::iterator end,
7570b57cec5SDimitry Andric                                      unsigned regioninstrs)
7580b57cec5SDimitry Andric {
7590b57cec5SDimitry Andric   ScheduleDAGInstrs::enterRegion(bb, begin, end, regioninstrs);
7600b57cec5SDimitry Andric 
7610b57cec5SDimitry Andric   SchedImpl->initPolicy(begin, end, regioninstrs);
7620b57cec5SDimitry Andric }
7630b57cec5SDimitry Andric 
7640b57cec5SDimitry Andric /// This is normally called from the main scheduler loop but may also be invoked
7650b57cec5SDimitry Andric /// by the scheduling strategy to perform additional code motion.
moveInstruction(MachineInstr * MI,MachineBasicBlock::iterator InsertPos)7660b57cec5SDimitry Andric void ScheduleDAGMI::moveInstruction(
7670b57cec5SDimitry Andric   MachineInstr *MI, MachineBasicBlock::iterator InsertPos) {
7680b57cec5SDimitry Andric   // Advance RegionBegin if the first instruction moves down.
7690b57cec5SDimitry Andric   if (&*RegionBegin == MI)
7700b57cec5SDimitry Andric     ++RegionBegin;
7710b57cec5SDimitry Andric 
7720b57cec5SDimitry Andric   // Update the instruction stream.
7730b57cec5SDimitry Andric   BB->splice(InsertPos, BB, MI);
7740b57cec5SDimitry Andric 
7750b57cec5SDimitry Andric   // Update LiveIntervals
7760b57cec5SDimitry Andric   if (LIS)
7770b57cec5SDimitry Andric     LIS->handleMove(*MI, /*UpdateFlags=*/true);
7780b57cec5SDimitry Andric 
7790b57cec5SDimitry Andric   // Recede RegionBegin if an instruction moves above the first.
7800b57cec5SDimitry Andric   if (RegionBegin == InsertPos)
7810b57cec5SDimitry Andric     RegionBegin = MI;
7820b57cec5SDimitry Andric }
7830b57cec5SDimitry Andric 
checkSchedLimit()7840b57cec5SDimitry Andric bool ScheduleDAGMI::checkSchedLimit() {
78561cfbce3SDimitry Andric #if LLVM_ENABLE_ABI_BREAKING_CHECKS && !defined(NDEBUG)
7860b57cec5SDimitry Andric   if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
7870b57cec5SDimitry Andric     CurrentTop = CurrentBottom;
7880b57cec5SDimitry Andric     return false;
7890b57cec5SDimitry Andric   }
7900b57cec5SDimitry Andric   ++NumInstrsScheduled;
7910b57cec5SDimitry Andric #endif
7920b57cec5SDimitry Andric   return true;
7930b57cec5SDimitry Andric }
7940b57cec5SDimitry Andric 
7950b57cec5SDimitry Andric /// Per-region scheduling driver, called back from
796c9157d92SDimitry Andric /// PostMachineScheduler::runOnMachineFunction. This is a simplified driver
797c9157d92SDimitry Andric /// that does not consider liveness or register pressure. It is useful for
798c9157d92SDimitry Andric /// PostRA scheduling and potentially other custom schedulers.
schedule()7990b57cec5SDimitry Andric void ScheduleDAGMI::schedule() {
8000b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "ScheduleDAGMI::schedule starting\n");
8010b57cec5SDimitry Andric   LLVM_DEBUG(SchedImpl->dumpPolicy());
8020b57cec5SDimitry Andric 
8030b57cec5SDimitry Andric   // Build the DAG.
8040b57cec5SDimitry Andric   buildSchedGraph(AA);
8050b57cec5SDimitry Andric 
806fe013be4SDimitry Andric   postProcessDAG();
8070b57cec5SDimitry Andric 
8080b57cec5SDimitry Andric   SmallVector<SUnit*, 8> TopRoots, BotRoots;
8090b57cec5SDimitry Andric   findRootsAndBiasEdges(TopRoots, BotRoots);
8100b57cec5SDimitry Andric 
8110b57cec5SDimitry Andric   LLVM_DEBUG(dump());
8120b57cec5SDimitry Andric   if (PrintDAGs) dump();
8130b57cec5SDimitry Andric   if (ViewMISchedDAGs) viewGraph();
8140b57cec5SDimitry Andric 
8150b57cec5SDimitry Andric   // Initialize the strategy before modifying the DAG.
8160b57cec5SDimitry Andric   // This may initialize a DFSResult to be used for queue priority.
8170b57cec5SDimitry Andric   SchedImpl->initialize(this);
8180b57cec5SDimitry Andric 
8190b57cec5SDimitry Andric   // Initialize ready queues now that the DAG and priority data are finalized.
8200b57cec5SDimitry Andric   initQueues(TopRoots, BotRoots);
8210b57cec5SDimitry Andric 
8220b57cec5SDimitry Andric   bool IsTopNode = false;
8230b57cec5SDimitry Andric   while (true) {
8240b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "** ScheduleDAGMI::schedule picking next node\n");
8250b57cec5SDimitry Andric     SUnit *SU = SchedImpl->pickNode(IsTopNode);
8260b57cec5SDimitry Andric     if (!SU) break;
8270b57cec5SDimitry Andric 
8280b57cec5SDimitry Andric     assert(!SU->isScheduled && "Node already scheduled");
8290b57cec5SDimitry Andric     if (!checkSchedLimit())
8300b57cec5SDimitry Andric       break;
8310b57cec5SDimitry Andric 
8320b57cec5SDimitry Andric     MachineInstr *MI = SU->getInstr();
8330b57cec5SDimitry Andric     if (IsTopNode) {
8340b57cec5SDimitry Andric       assert(SU->isTopReady() && "node still has unscheduled dependencies");
8350b57cec5SDimitry Andric       if (&*CurrentTop == MI)
8360b57cec5SDimitry Andric         CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
8370b57cec5SDimitry Andric       else
8380b57cec5SDimitry Andric         moveInstruction(MI, CurrentTop);
8390b57cec5SDimitry Andric     } else {
8400b57cec5SDimitry Andric       assert(SU->isBottomReady() && "node still has unscheduled dependencies");
8410b57cec5SDimitry Andric       MachineBasicBlock::iterator priorII =
8420b57cec5SDimitry Andric         priorNonDebug(CurrentBottom, CurrentTop);
8430b57cec5SDimitry Andric       if (&*priorII == MI)
8440b57cec5SDimitry Andric         CurrentBottom = priorII;
8450b57cec5SDimitry Andric       else {
8460b57cec5SDimitry Andric         if (&*CurrentTop == MI)
8470b57cec5SDimitry Andric           CurrentTop = nextIfDebug(++CurrentTop, priorII);
8480b57cec5SDimitry Andric         moveInstruction(MI, CurrentBottom);
8490b57cec5SDimitry Andric         CurrentBottom = MI;
8500b57cec5SDimitry Andric       }
8510b57cec5SDimitry Andric     }
8520b57cec5SDimitry Andric     // Notify the scheduling strategy before updating the DAG.
8530b57cec5SDimitry Andric     // This sets the scheduled node's ReadyCycle to CurrCycle. When updateQueues
8540b57cec5SDimitry Andric     // runs, it can then use the accurate ReadyCycle time to determine whether
8550b57cec5SDimitry Andric     // newly released nodes can move to the readyQ.
8560b57cec5SDimitry Andric     SchedImpl->schedNode(SU, IsTopNode);
8570b57cec5SDimitry Andric 
8580b57cec5SDimitry Andric     updateQueues(SU, IsTopNode);
8590b57cec5SDimitry Andric   }
8600b57cec5SDimitry Andric   assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
8610b57cec5SDimitry Andric 
8620b57cec5SDimitry Andric   placeDebugValues();
8630b57cec5SDimitry Andric 
8640b57cec5SDimitry Andric   LLVM_DEBUG({
8650b57cec5SDimitry Andric     dbgs() << "*** Final schedule for "
8660b57cec5SDimitry Andric            << printMBBReference(*begin()->getParent()) << " ***\n";
8670b57cec5SDimitry Andric     dumpSchedule();
8680b57cec5SDimitry Andric     dbgs() << '\n';
8690b57cec5SDimitry Andric   });
8700b57cec5SDimitry Andric }
8710b57cec5SDimitry Andric 
8720b57cec5SDimitry Andric /// Apply each ScheduleDAGMutation step in order.
postProcessDAG()873fe013be4SDimitry Andric void ScheduleDAGMI::postProcessDAG() {
8740b57cec5SDimitry Andric   for (auto &m : Mutations)
8750b57cec5SDimitry Andric     m->apply(this);
8760b57cec5SDimitry Andric }
8770b57cec5SDimitry Andric 
8780b57cec5SDimitry Andric void ScheduleDAGMI::
findRootsAndBiasEdges(SmallVectorImpl<SUnit * > & TopRoots,SmallVectorImpl<SUnit * > & BotRoots)8790b57cec5SDimitry Andric findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
8800b57cec5SDimitry Andric                       SmallVectorImpl<SUnit*> &BotRoots) {
8810b57cec5SDimitry Andric   for (SUnit &SU : SUnits) {
8820b57cec5SDimitry Andric     assert(!SU.isBoundaryNode() && "Boundary node should not be in SUnits");
8830b57cec5SDimitry Andric 
8840b57cec5SDimitry Andric     // Order predecessors so DFSResult follows the critical path.
8850b57cec5SDimitry Andric     SU.biasCriticalPath();
8860b57cec5SDimitry Andric 
8870b57cec5SDimitry Andric     // A SUnit is ready to top schedule if it has no predecessors.
8880b57cec5SDimitry Andric     if (!SU.NumPredsLeft)
8890b57cec5SDimitry Andric       TopRoots.push_back(&SU);
8900b57cec5SDimitry Andric     // A SUnit is ready to bottom schedule if it has no successors.
8910b57cec5SDimitry Andric     if (!SU.NumSuccsLeft)
8920b57cec5SDimitry Andric       BotRoots.push_back(&SU);
8930b57cec5SDimitry Andric   }
8940b57cec5SDimitry Andric   ExitSU.biasCriticalPath();
8950b57cec5SDimitry Andric }
8960b57cec5SDimitry Andric 
8970b57cec5SDimitry Andric /// Identify DAG roots and setup scheduler queues.
initQueues(ArrayRef<SUnit * > TopRoots,ArrayRef<SUnit * > BotRoots)8980b57cec5SDimitry Andric void ScheduleDAGMI::initQueues(ArrayRef<SUnit*> TopRoots,
8990b57cec5SDimitry Andric                                ArrayRef<SUnit*> BotRoots) {
9000b57cec5SDimitry Andric   NextClusterSucc = nullptr;
9010b57cec5SDimitry Andric   NextClusterPred = nullptr;
9020b57cec5SDimitry Andric 
9030b57cec5SDimitry Andric   // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
9040b57cec5SDimitry Andric   //
9050b57cec5SDimitry Andric   // Nodes with unreleased weak edges can still be roots.
9060b57cec5SDimitry Andric   // Release top roots in forward order.
9070b57cec5SDimitry Andric   for (SUnit *SU : TopRoots)
9080b57cec5SDimitry Andric     SchedImpl->releaseTopNode(SU);
9090b57cec5SDimitry Andric 
9100b57cec5SDimitry Andric   // Release bottom roots in reverse order so the higher priority nodes appear
9110b57cec5SDimitry Andric   // first. This is more natural and slightly more efficient.
9120b57cec5SDimitry Andric   for (SmallVectorImpl<SUnit*>::const_reverse_iterator
9130b57cec5SDimitry Andric          I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I) {
9140b57cec5SDimitry Andric     SchedImpl->releaseBottomNode(*I);
9150b57cec5SDimitry Andric   }
9160b57cec5SDimitry Andric 
9170b57cec5SDimitry Andric   releaseSuccessors(&EntrySU);
9180b57cec5SDimitry Andric   releasePredecessors(&ExitSU);
9190b57cec5SDimitry Andric 
9200b57cec5SDimitry Andric   SchedImpl->registerRoots();
9210b57cec5SDimitry Andric 
9220b57cec5SDimitry Andric   // Advance past initial DebugValues.
9230b57cec5SDimitry Andric   CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
9240b57cec5SDimitry Andric   CurrentBottom = RegionEnd;
9250b57cec5SDimitry Andric }
9260b57cec5SDimitry Andric 
9270b57cec5SDimitry Andric /// Update scheduler queues after scheduling an instruction.
updateQueues(SUnit * SU,bool IsTopNode)9280b57cec5SDimitry Andric void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
9290b57cec5SDimitry Andric   // Release dependent instructions for scheduling.
9300b57cec5SDimitry Andric   if (IsTopNode)
9310b57cec5SDimitry Andric     releaseSuccessors(SU);
9320b57cec5SDimitry Andric   else
9330b57cec5SDimitry Andric     releasePredecessors(SU);
9340b57cec5SDimitry Andric 
9350b57cec5SDimitry Andric   SU->isScheduled = true;
9360b57cec5SDimitry Andric }
9370b57cec5SDimitry Andric 
9380b57cec5SDimitry Andric /// Reinsert any remaining debug_values, just like the PostRA scheduler.
placeDebugValues()9390b57cec5SDimitry Andric void ScheduleDAGMI::placeDebugValues() {
9400b57cec5SDimitry Andric   // If first instruction was a DBG_VALUE then put it back.
9410b57cec5SDimitry Andric   if (FirstDbgValue) {
9420b57cec5SDimitry Andric     BB->splice(RegionBegin, BB, FirstDbgValue);
9430b57cec5SDimitry Andric     RegionBegin = FirstDbgValue;
9440b57cec5SDimitry Andric   }
9450b57cec5SDimitry Andric 
9460b57cec5SDimitry Andric   for (std::vector<std::pair<MachineInstr *, MachineInstr *>>::iterator
9470b57cec5SDimitry Andric          DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
9480b57cec5SDimitry Andric     std::pair<MachineInstr *, MachineInstr *> P = *std::prev(DI);
9490b57cec5SDimitry Andric     MachineInstr *DbgValue = P.first;
9500b57cec5SDimitry Andric     MachineBasicBlock::iterator OrigPrevMI = P.second;
9510b57cec5SDimitry Andric     if (&*RegionBegin == DbgValue)
9520b57cec5SDimitry Andric       ++RegionBegin;
95381ad6265SDimitry Andric     BB->splice(std::next(OrigPrevMI), BB, DbgValue);
95481ad6265SDimitry Andric     if (RegionEnd != BB->end() && OrigPrevMI == &*RegionEnd)
9550b57cec5SDimitry Andric       RegionEnd = DbgValue;
9560b57cec5SDimitry Andric   }
9570b57cec5SDimitry Andric }
9580b57cec5SDimitry Andric 
9590b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
960fe013be4SDimitry Andric static const char *scheduleTableLegend = "  i: issue\n  x: resource booked";
961fe013be4SDimitry Andric 
dumpScheduleTraceTopDown() const962fe013be4SDimitry Andric LLVM_DUMP_METHOD void ScheduleDAGMI::dumpScheduleTraceTopDown() const {
963fe013be4SDimitry Andric   // Bail off when there is no schedule model to query.
964fe013be4SDimitry Andric   if (!SchedModel.hasInstrSchedModel())
965fe013be4SDimitry Andric     return;
966fe013be4SDimitry Andric 
967fe013be4SDimitry Andric   //  Nothing to show if there is no or just one instruction.
968fe013be4SDimitry Andric   if (BB->size() < 2)
969fe013be4SDimitry Andric     return;
970fe013be4SDimitry Andric 
971fe013be4SDimitry Andric   dbgs() << " * Schedule table (TopDown):\n";
972fe013be4SDimitry Andric   dbgs() << scheduleTableLegend << "\n";
973fe013be4SDimitry Andric   const unsigned FirstCycle = getSUnit(&*(std::begin(*this)))->TopReadyCycle;
974fe013be4SDimitry Andric   unsigned LastCycle = getSUnit(&*(std::prev(std::end(*this))))->TopReadyCycle;
975fe013be4SDimitry Andric   for (MachineInstr &MI : *this) {
976fe013be4SDimitry Andric     SUnit *SU = getSUnit(&MI);
977fe013be4SDimitry Andric     if (!SU)
978fe013be4SDimitry Andric       continue;
979fe013be4SDimitry Andric     const MCSchedClassDesc *SC = getSchedClass(SU);
980fe013be4SDimitry Andric     for (TargetSchedModel::ProcResIter PI = SchedModel.getWriteProcResBegin(SC),
981fe013be4SDimitry Andric                                        PE = SchedModel.getWriteProcResEnd(SC);
982fe013be4SDimitry Andric          PI != PE; ++PI) {
983c9157d92SDimitry Andric       if (SU->TopReadyCycle + PI->ReleaseAtCycle - 1 > LastCycle)
984c9157d92SDimitry Andric         LastCycle = SU->TopReadyCycle + PI->ReleaseAtCycle - 1;
985fe013be4SDimitry Andric     }
986fe013be4SDimitry Andric   }
987fe013be4SDimitry Andric   // Print the header with the cycles
988fe013be4SDimitry Andric   dbgs() << llvm::left_justify("Cycle", HeaderColWidth);
989fe013be4SDimitry Andric   for (unsigned C = FirstCycle; C <= LastCycle; ++C)
990fe013be4SDimitry Andric     dbgs() << llvm::left_justify("| " + std::to_string(C), ColWidth);
991fe013be4SDimitry Andric   dbgs() << "|\n";
992fe013be4SDimitry Andric 
993fe013be4SDimitry Andric   for (MachineInstr &MI : *this) {
994fe013be4SDimitry Andric     SUnit *SU = getSUnit(&MI);
995fe013be4SDimitry Andric     if (!SU) {
996fe013be4SDimitry Andric       dbgs() << "Missing SUnit\n";
997fe013be4SDimitry Andric       continue;
998fe013be4SDimitry Andric     }
999fe013be4SDimitry Andric     std::string NodeName("SU(");
1000fe013be4SDimitry Andric     NodeName += std::to_string(SU->NodeNum) + ")";
1001fe013be4SDimitry Andric     dbgs() << llvm::left_justify(NodeName, HeaderColWidth);
1002fe013be4SDimitry Andric     unsigned C = FirstCycle;
1003fe013be4SDimitry Andric     for (; C <= LastCycle; ++C) {
1004fe013be4SDimitry Andric       if (C == SU->TopReadyCycle)
1005fe013be4SDimitry Andric         dbgs() << llvm::left_justify("| i", ColWidth);
1006fe013be4SDimitry Andric       else
1007fe013be4SDimitry Andric         dbgs() << llvm::left_justify("|", ColWidth);
1008fe013be4SDimitry Andric     }
1009fe013be4SDimitry Andric     dbgs() << "|\n";
1010fe013be4SDimitry Andric     const MCSchedClassDesc *SC = getSchedClass(SU);
1011fe013be4SDimitry Andric 
1012fe013be4SDimitry Andric     SmallVector<MCWriteProcResEntry, 4> ResourcesIt(
1013fe013be4SDimitry Andric         make_range(SchedModel.getWriteProcResBegin(SC),
1014fe013be4SDimitry Andric                    SchedModel.getWriteProcResEnd(SC)));
1015fe013be4SDimitry Andric 
1016fe013be4SDimitry Andric     if (MISchedSortResourcesInTrace)
1017fe013be4SDimitry Andric       llvm::stable_sort(ResourcesIt,
1018fe013be4SDimitry Andric                         [](const MCWriteProcResEntry &LHS,
1019fe013be4SDimitry Andric                            const MCWriteProcResEntry &RHS) -> bool {
1020c9157d92SDimitry Andric                           return LHS.AcquireAtCycle < RHS.AcquireAtCycle ||
1021c9157d92SDimitry Andric                                  (LHS.AcquireAtCycle == RHS.AcquireAtCycle &&
1022c9157d92SDimitry Andric                                   LHS.ReleaseAtCycle < RHS.ReleaseAtCycle);
1023fe013be4SDimitry Andric                         });
1024fe013be4SDimitry Andric     for (const MCWriteProcResEntry &PI : ResourcesIt) {
1025fe013be4SDimitry Andric       C = FirstCycle;
1026fe013be4SDimitry Andric       const std::string ResName =
1027fe013be4SDimitry Andric           SchedModel.getResourceName(PI.ProcResourceIdx);
1028fe013be4SDimitry Andric       dbgs() << llvm::right_justify(ResName + " ", HeaderColWidth);
1029c9157d92SDimitry Andric       for (; C < SU->TopReadyCycle + PI.AcquireAtCycle; ++C) {
1030fe013be4SDimitry Andric         dbgs() << llvm::left_justify("|", ColWidth);
1031fe013be4SDimitry Andric       }
1032c9157d92SDimitry Andric       for (unsigned I = 0, E = PI.ReleaseAtCycle - PI.AcquireAtCycle; I != E;
1033c9157d92SDimitry Andric            ++I, ++C)
1034fe013be4SDimitry Andric         dbgs() << llvm::left_justify("| x", ColWidth);
1035fe013be4SDimitry Andric       while (C++ <= LastCycle)
1036fe013be4SDimitry Andric         dbgs() << llvm::left_justify("|", ColWidth);
1037fe013be4SDimitry Andric       // Place end char
1038fe013be4SDimitry Andric       dbgs() << "| \n";
1039fe013be4SDimitry Andric     }
1040fe013be4SDimitry Andric   }
1041fe013be4SDimitry Andric }
1042fe013be4SDimitry Andric 
dumpScheduleTraceBottomUp() const1043fe013be4SDimitry Andric LLVM_DUMP_METHOD void ScheduleDAGMI::dumpScheduleTraceBottomUp() const {
1044fe013be4SDimitry Andric   // Bail off when there is no schedule model to query.
1045fe013be4SDimitry Andric   if (!SchedModel.hasInstrSchedModel())
1046fe013be4SDimitry Andric     return;
1047fe013be4SDimitry Andric 
1048fe013be4SDimitry Andric   //  Nothing to show if there is no or just one instruction.
1049fe013be4SDimitry Andric   if (BB->size() < 2)
1050fe013be4SDimitry Andric     return;
1051fe013be4SDimitry Andric 
1052fe013be4SDimitry Andric   dbgs() << " * Schedule table (BottomUp):\n";
1053fe013be4SDimitry Andric   dbgs() << scheduleTableLegend << "\n";
1054fe013be4SDimitry Andric 
1055fe013be4SDimitry Andric   const int FirstCycle = getSUnit(&*(std::begin(*this)))->BotReadyCycle;
1056fe013be4SDimitry Andric   int LastCycle = getSUnit(&*(std::prev(std::end(*this))))->BotReadyCycle;
1057fe013be4SDimitry Andric   for (MachineInstr &MI : *this) {
1058fe013be4SDimitry Andric     SUnit *SU = getSUnit(&MI);
1059fe013be4SDimitry Andric     if (!SU)
1060fe013be4SDimitry Andric       continue;
1061fe013be4SDimitry Andric     const MCSchedClassDesc *SC = getSchedClass(SU);
1062fe013be4SDimitry Andric     for (TargetSchedModel::ProcResIter PI = SchedModel.getWriteProcResBegin(SC),
1063fe013be4SDimitry Andric                                        PE = SchedModel.getWriteProcResEnd(SC);
1064fe013be4SDimitry Andric          PI != PE; ++PI) {
1065c9157d92SDimitry Andric       if ((int)SU->BotReadyCycle - PI->ReleaseAtCycle + 1 < LastCycle)
1066c9157d92SDimitry Andric         LastCycle = (int)SU->BotReadyCycle - PI->ReleaseAtCycle + 1;
1067fe013be4SDimitry Andric     }
1068fe013be4SDimitry Andric   }
1069fe013be4SDimitry Andric   // Print the header with the cycles
1070fe013be4SDimitry Andric   dbgs() << llvm::left_justify("Cycle", HeaderColWidth);
1071fe013be4SDimitry Andric   for (int C = FirstCycle; C >= LastCycle; --C)
1072fe013be4SDimitry Andric     dbgs() << llvm::left_justify("| " + std::to_string(C), ColWidth);
1073fe013be4SDimitry Andric   dbgs() << "|\n";
1074fe013be4SDimitry Andric 
1075fe013be4SDimitry Andric   for (MachineInstr &MI : *this) {
1076fe013be4SDimitry Andric     SUnit *SU = getSUnit(&MI);
1077fe013be4SDimitry Andric     if (!SU) {
1078fe013be4SDimitry Andric       dbgs() << "Missing SUnit\n";
1079fe013be4SDimitry Andric       continue;
1080fe013be4SDimitry Andric     }
1081fe013be4SDimitry Andric     std::string NodeName("SU(");
1082fe013be4SDimitry Andric     NodeName += std::to_string(SU->NodeNum) + ")";
1083fe013be4SDimitry Andric     dbgs() << llvm::left_justify(NodeName, HeaderColWidth);
1084fe013be4SDimitry Andric     int C = FirstCycle;
1085fe013be4SDimitry Andric     for (; C >= LastCycle; --C) {
1086fe013be4SDimitry Andric       if (C == (int)SU->BotReadyCycle)
1087fe013be4SDimitry Andric         dbgs() << llvm::left_justify("| i", ColWidth);
1088fe013be4SDimitry Andric       else
1089fe013be4SDimitry Andric         dbgs() << llvm::left_justify("|", ColWidth);
1090fe013be4SDimitry Andric     }
1091fe013be4SDimitry Andric     dbgs() << "|\n";
1092fe013be4SDimitry Andric     const MCSchedClassDesc *SC = getSchedClass(SU);
1093fe013be4SDimitry Andric     SmallVector<MCWriteProcResEntry, 4> ResourcesIt(
1094fe013be4SDimitry Andric         make_range(SchedModel.getWriteProcResBegin(SC),
1095fe013be4SDimitry Andric                    SchedModel.getWriteProcResEnd(SC)));
1096fe013be4SDimitry Andric 
1097fe013be4SDimitry Andric     if (MISchedSortResourcesInTrace)
1098fe013be4SDimitry Andric       llvm::stable_sort(ResourcesIt,
1099fe013be4SDimitry Andric                         [](const MCWriteProcResEntry &LHS,
1100fe013be4SDimitry Andric                            const MCWriteProcResEntry &RHS) -> bool {
1101c9157d92SDimitry Andric                           return LHS.AcquireAtCycle < RHS.AcquireAtCycle ||
1102c9157d92SDimitry Andric                                  (LHS.AcquireAtCycle == RHS.AcquireAtCycle &&
1103c9157d92SDimitry Andric                                   LHS.ReleaseAtCycle < RHS.ReleaseAtCycle);
1104fe013be4SDimitry Andric                         });
1105fe013be4SDimitry Andric     for (const MCWriteProcResEntry &PI : ResourcesIt) {
1106fe013be4SDimitry Andric       C = FirstCycle;
1107fe013be4SDimitry Andric       const std::string ResName =
1108fe013be4SDimitry Andric           SchedModel.getResourceName(PI.ProcResourceIdx);
1109fe013be4SDimitry Andric       dbgs() << llvm::right_justify(ResName + " ", HeaderColWidth);
1110c9157d92SDimitry Andric       for (; C > ((int)SU->BotReadyCycle - (int)PI.AcquireAtCycle); --C) {
1111fe013be4SDimitry Andric         dbgs() << llvm::left_justify("|", ColWidth);
1112fe013be4SDimitry Andric       }
1113c9157d92SDimitry Andric       for (unsigned I = 0, E = PI.ReleaseAtCycle - PI.AcquireAtCycle; I != E;
1114c9157d92SDimitry Andric            ++I, --C)
1115fe013be4SDimitry Andric         dbgs() << llvm::left_justify("| x", ColWidth);
1116fe013be4SDimitry Andric       while (C-- >= LastCycle)
1117fe013be4SDimitry Andric         dbgs() << llvm::left_justify("|", ColWidth);
1118fe013be4SDimitry Andric       // Place end char
1119fe013be4SDimitry Andric       dbgs() << "| \n";
1120fe013be4SDimitry Andric     }
1121fe013be4SDimitry Andric   }
1122fe013be4SDimitry Andric }
1123fe013be4SDimitry Andric #endif
1124fe013be4SDimitry Andric 
1125fe013be4SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dumpSchedule() const11260b57cec5SDimitry Andric LLVM_DUMP_METHOD void ScheduleDAGMI::dumpSchedule() const {
1127fe013be4SDimitry Andric   if (MISchedDumpScheduleTrace) {
1128fe013be4SDimitry Andric     if (ForceTopDown)
1129fe013be4SDimitry Andric       dumpScheduleTraceTopDown();
1130fe013be4SDimitry Andric     else if (ForceBottomUp)
1131fe013be4SDimitry Andric       dumpScheduleTraceBottomUp();
1132fe013be4SDimitry Andric     else {
1133fe013be4SDimitry Andric       dbgs() << "* Schedule table (Bidirectional): not implemented\n";
1134fe013be4SDimitry Andric     }
1135fe013be4SDimitry Andric   }
1136fe013be4SDimitry Andric 
1137fe6060f1SDimitry Andric   for (MachineInstr &MI : *this) {
1138fe6060f1SDimitry Andric     if (SUnit *SU = getSUnit(&MI))
11390b57cec5SDimitry Andric       dumpNode(*SU);
11400b57cec5SDimitry Andric     else
11410b57cec5SDimitry Andric       dbgs() << "Missing SUnit\n";
11420b57cec5SDimitry Andric   }
11430b57cec5SDimitry Andric }
11440b57cec5SDimitry Andric #endif
11450b57cec5SDimitry Andric 
11460b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
11470b57cec5SDimitry Andric // ScheduleDAGMILive - Base class for MachineInstr scheduling with LiveIntervals
11480b57cec5SDimitry Andric // preservation.
11490b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
11500b57cec5SDimitry Andric 
~ScheduleDAGMILive()11510b57cec5SDimitry Andric ScheduleDAGMILive::~ScheduleDAGMILive() {
11520b57cec5SDimitry Andric   delete DFSResult;
11530b57cec5SDimitry Andric }
11540b57cec5SDimitry Andric 
collectVRegUses(SUnit & SU)11550b57cec5SDimitry Andric void ScheduleDAGMILive::collectVRegUses(SUnit &SU) {
11560b57cec5SDimitry Andric   const MachineInstr &MI = *SU.getInstr();
11570b57cec5SDimitry Andric   for (const MachineOperand &MO : MI.operands()) {
11580b57cec5SDimitry Andric     if (!MO.isReg())
11590b57cec5SDimitry Andric       continue;
11600b57cec5SDimitry Andric     if (!MO.readsReg())
11610b57cec5SDimitry Andric       continue;
11620b57cec5SDimitry Andric     if (TrackLaneMasks && !MO.isUse())
11630b57cec5SDimitry Andric       continue;
11640b57cec5SDimitry Andric 
11658bcb0991SDimitry Andric     Register Reg = MO.getReg();
1166bdd1243dSDimitry Andric     if (!Reg.isVirtual())
11670b57cec5SDimitry Andric       continue;
11680b57cec5SDimitry Andric 
11690b57cec5SDimitry Andric     // Ignore re-defs.
11700b57cec5SDimitry Andric     if (TrackLaneMasks) {
11710b57cec5SDimitry Andric       bool FoundDef = false;
1172fe013be4SDimitry Andric       for (const MachineOperand &MO2 : MI.all_defs()) {
1173fe013be4SDimitry Andric         if (MO2.getReg() == Reg && !MO2.isDead()) {
11740b57cec5SDimitry Andric           FoundDef = true;
11750b57cec5SDimitry Andric           break;
11760b57cec5SDimitry Andric         }
11770b57cec5SDimitry Andric       }
11780b57cec5SDimitry Andric       if (FoundDef)
11790b57cec5SDimitry Andric         continue;
11800b57cec5SDimitry Andric     }
11810b57cec5SDimitry Andric 
11820b57cec5SDimitry Andric     // Record this local VReg use.
11830b57cec5SDimitry Andric     VReg2SUnitMultiMap::iterator UI = VRegUses.find(Reg);
11840b57cec5SDimitry Andric     for (; UI != VRegUses.end(); ++UI) {
11850b57cec5SDimitry Andric       if (UI->SU == &SU)
11860b57cec5SDimitry Andric         break;
11870b57cec5SDimitry Andric     }
11880b57cec5SDimitry Andric     if (UI == VRegUses.end())
11890b57cec5SDimitry Andric       VRegUses.insert(VReg2SUnit(Reg, LaneBitmask::getNone(), &SU));
11900b57cec5SDimitry Andric   }
11910b57cec5SDimitry Andric }
11920b57cec5SDimitry Andric 
11930b57cec5SDimitry Andric /// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
11940b57cec5SDimitry Andric /// crossing a scheduling boundary. [begin, end) includes all instructions in
11950b57cec5SDimitry Andric /// the region, including the boundary itself and single-instruction regions
11960b57cec5SDimitry Andric /// that don't get scheduled.
enterRegion(MachineBasicBlock * bb,MachineBasicBlock::iterator begin,MachineBasicBlock::iterator end,unsigned regioninstrs)11970b57cec5SDimitry Andric void ScheduleDAGMILive::enterRegion(MachineBasicBlock *bb,
11980b57cec5SDimitry Andric                                 MachineBasicBlock::iterator begin,
11990b57cec5SDimitry Andric                                 MachineBasicBlock::iterator end,
12000b57cec5SDimitry Andric                                 unsigned regioninstrs)
12010b57cec5SDimitry Andric {
12020b57cec5SDimitry Andric   // ScheduleDAGMI initializes SchedImpl's per-region policy.
12030b57cec5SDimitry Andric   ScheduleDAGMI::enterRegion(bb, begin, end, regioninstrs);
12040b57cec5SDimitry Andric 
12050b57cec5SDimitry Andric   // For convenience remember the end of the liveness region.
12060b57cec5SDimitry Andric   LiveRegionEnd = (RegionEnd == bb->end()) ? RegionEnd : std::next(RegionEnd);
12070b57cec5SDimitry Andric 
12080b57cec5SDimitry Andric   SUPressureDiffs.clear();
12090b57cec5SDimitry Andric 
12100b57cec5SDimitry Andric   ShouldTrackPressure = SchedImpl->shouldTrackPressure();
12110b57cec5SDimitry Andric   ShouldTrackLaneMasks = SchedImpl->shouldTrackLaneMasks();
12120b57cec5SDimitry Andric 
12130b57cec5SDimitry Andric   assert((!ShouldTrackLaneMasks || ShouldTrackPressure) &&
12140b57cec5SDimitry Andric          "ShouldTrackLaneMasks requires ShouldTrackPressure");
12150b57cec5SDimitry Andric }
12160b57cec5SDimitry Andric 
12178bcb0991SDimitry Andric // Setup the register pressure trackers for the top scheduled and bottom
12180b57cec5SDimitry Andric // scheduled regions.
initRegPressure()12190b57cec5SDimitry Andric void ScheduleDAGMILive::initRegPressure() {
12200b57cec5SDimitry Andric   VRegUses.clear();
12210b57cec5SDimitry Andric   VRegUses.setUniverse(MRI.getNumVirtRegs());
12220b57cec5SDimitry Andric   for (SUnit &SU : SUnits)
12230b57cec5SDimitry Andric     collectVRegUses(SU);
12240b57cec5SDimitry Andric 
12250b57cec5SDimitry Andric   TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin,
12260b57cec5SDimitry Andric                     ShouldTrackLaneMasks, false);
12270b57cec5SDimitry Andric   BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
12280b57cec5SDimitry Andric                     ShouldTrackLaneMasks, false);
12290b57cec5SDimitry Andric 
12300b57cec5SDimitry Andric   // Close the RPTracker to finalize live ins.
12310b57cec5SDimitry Andric   RPTracker.closeRegion();
12320b57cec5SDimitry Andric 
12330b57cec5SDimitry Andric   LLVM_DEBUG(RPTracker.dump());
12340b57cec5SDimitry Andric 
12350b57cec5SDimitry Andric   // Initialize the live ins and live outs.
12360b57cec5SDimitry Andric   TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
12370b57cec5SDimitry Andric   BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
12380b57cec5SDimitry Andric 
12390b57cec5SDimitry Andric   // Close one end of the tracker so we can call
12400b57cec5SDimitry Andric   // getMaxUpward/DownwardPressureDelta before advancing across any
12410b57cec5SDimitry Andric   // instructions. This converts currently live regs into live ins/outs.
12420b57cec5SDimitry Andric   TopRPTracker.closeTop();
12430b57cec5SDimitry Andric   BotRPTracker.closeBottom();
12440b57cec5SDimitry Andric 
12450b57cec5SDimitry Andric   BotRPTracker.initLiveThru(RPTracker);
12460b57cec5SDimitry Andric   if (!BotRPTracker.getLiveThru().empty()) {
12470b57cec5SDimitry Andric     TopRPTracker.initLiveThru(BotRPTracker.getLiveThru());
12480b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Live Thru: ";
12490b57cec5SDimitry Andric                dumpRegSetPressure(BotRPTracker.getLiveThru(), TRI));
12500b57cec5SDimitry Andric   };
12510b57cec5SDimitry Andric 
12520b57cec5SDimitry Andric   // For each live out vreg reduce the pressure change associated with other
12530b57cec5SDimitry Andric   // uses of the same vreg below the live-out reaching def.
12540b57cec5SDimitry Andric   updatePressureDiffs(RPTracker.getPressure().LiveOutRegs);
12550b57cec5SDimitry Andric 
12560b57cec5SDimitry Andric   // Account for liveness generated by the region boundary.
12570b57cec5SDimitry Andric   if (LiveRegionEnd != RegionEnd) {
12580b57cec5SDimitry Andric     SmallVector<RegisterMaskPair, 8> LiveUses;
12590b57cec5SDimitry Andric     BotRPTracker.recede(&LiveUses);
12600b57cec5SDimitry Andric     updatePressureDiffs(LiveUses);
12610b57cec5SDimitry Andric   }
12620b57cec5SDimitry Andric 
12630b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Top Pressure:\n";
12640b57cec5SDimitry Andric              dumpRegSetPressure(TopRPTracker.getRegSetPressureAtPos(), TRI);
12650b57cec5SDimitry Andric              dbgs() << "Bottom Pressure:\n";
12660b57cec5SDimitry Andric              dumpRegSetPressure(BotRPTracker.getRegSetPressureAtPos(), TRI););
12670b57cec5SDimitry Andric 
12680b57cec5SDimitry Andric   assert((BotRPTracker.getPos() == RegionEnd ||
12690b57cec5SDimitry Andric           (RegionEnd->isDebugInstr() &&
12700b57cec5SDimitry Andric            BotRPTracker.getPos() == priorNonDebug(RegionEnd, RegionBegin))) &&
12710b57cec5SDimitry Andric          "Can't find the region bottom");
12720b57cec5SDimitry Andric 
12730b57cec5SDimitry Andric   // Cache the list of excess pressure sets in this region. This will also track
12740b57cec5SDimitry Andric   // the max pressure in the scheduled code for these sets.
12750b57cec5SDimitry Andric   RegionCriticalPSets.clear();
12760b57cec5SDimitry Andric   const std::vector<unsigned> &RegionPressure =
12770b57cec5SDimitry Andric     RPTracker.getPressure().MaxSetPressure;
12780b57cec5SDimitry Andric   for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
12790b57cec5SDimitry Andric     unsigned Limit = RegClassInfo->getRegPressureSetLimit(i);
12800b57cec5SDimitry Andric     if (RegionPressure[i] > Limit) {
12810b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << TRI->getRegPressureSetName(i) << " Limit " << Limit
12820b57cec5SDimitry Andric                         << " Actual " << RegionPressure[i] << "\n");
12830b57cec5SDimitry Andric       RegionCriticalPSets.push_back(PressureChange(i));
12840b57cec5SDimitry Andric     }
12850b57cec5SDimitry Andric   }
12860b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Excess PSets: ";
12870b57cec5SDimitry Andric              for (const PressureChange &RCPS
12880b57cec5SDimitry Andric                   : RegionCriticalPSets) dbgs()
12890b57cec5SDimitry Andric              << TRI->getRegPressureSetName(RCPS.getPSet()) << " ";
12900b57cec5SDimitry Andric              dbgs() << "\n");
12910b57cec5SDimitry Andric }
12920b57cec5SDimitry Andric 
12930b57cec5SDimitry Andric void ScheduleDAGMILive::
updateScheduledPressure(const SUnit * SU,const std::vector<unsigned> & NewMaxPressure)12940b57cec5SDimitry Andric updateScheduledPressure(const SUnit *SU,
12950b57cec5SDimitry Andric                         const std::vector<unsigned> &NewMaxPressure) {
12960b57cec5SDimitry Andric   const PressureDiff &PDiff = getPressureDiff(SU);
12970b57cec5SDimitry Andric   unsigned CritIdx = 0, CritEnd = RegionCriticalPSets.size();
12980b57cec5SDimitry Andric   for (const PressureChange &PC : PDiff) {
12990b57cec5SDimitry Andric     if (!PC.isValid())
13000b57cec5SDimitry Andric       break;
13010b57cec5SDimitry Andric     unsigned ID = PC.getPSet();
13020b57cec5SDimitry Andric     while (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() < ID)
13030b57cec5SDimitry Andric       ++CritIdx;
13040b57cec5SDimitry Andric     if (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() == ID) {
13050b57cec5SDimitry Andric       if ((int)NewMaxPressure[ID] > RegionCriticalPSets[CritIdx].getUnitInc()
13060b57cec5SDimitry Andric           && NewMaxPressure[ID] <= (unsigned)std::numeric_limits<int16_t>::max())
13070b57cec5SDimitry Andric         RegionCriticalPSets[CritIdx].setUnitInc(NewMaxPressure[ID]);
13080b57cec5SDimitry Andric     }
13090b57cec5SDimitry Andric     unsigned Limit = RegClassInfo->getRegPressureSetLimit(ID);
13100b57cec5SDimitry Andric     if (NewMaxPressure[ID] >= Limit - 2) {
13110b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "  " << TRI->getRegPressureSetName(ID) << ": "
13120b57cec5SDimitry Andric                         << NewMaxPressure[ID]
13130b57cec5SDimitry Andric                         << ((NewMaxPressure[ID] > Limit) ? " > " : " <= ")
13140b57cec5SDimitry Andric                         << Limit << "(+ " << BotRPTracker.getLiveThru()[ID]
13150b57cec5SDimitry Andric                         << " livethru)\n");
13160b57cec5SDimitry Andric     }
13170b57cec5SDimitry Andric   }
13180b57cec5SDimitry Andric }
13190b57cec5SDimitry Andric 
13200b57cec5SDimitry Andric /// Update the PressureDiff array for liveness after scheduling this
13210b57cec5SDimitry Andric /// instruction.
updatePressureDiffs(ArrayRef<RegisterMaskPair> LiveUses)13220b57cec5SDimitry Andric void ScheduleDAGMILive::updatePressureDiffs(
13230b57cec5SDimitry Andric     ArrayRef<RegisterMaskPair> LiveUses) {
13240b57cec5SDimitry Andric   for (const RegisterMaskPair &P : LiveUses) {
1325e8d8bef9SDimitry Andric     Register Reg = P.RegUnit;
13260b57cec5SDimitry Andric     /// FIXME: Currently assuming single-use physregs.
1327bdd1243dSDimitry Andric     if (!Reg.isVirtual())
13280b57cec5SDimitry Andric       continue;
13290b57cec5SDimitry Andric 
13300b57cec5SDimitry Andric     if (ShouldTrackLaneMasks) {
13310b57cec5SDimitry Andric       // If the register has just become live then other uses won't change
13320b57cec5SDimitry Andric       // this fact anymore => decrement pressure.
13330b57cec5SDimitry Andric       // If the register has just become dead then other uses make it come
13340b57cec5SDimitry Andric       // back to life => increment pressure.
13350b57cec5SDimitry Andric       bool Decrement = P.LaneMask.any();
13360b57cec5SDimitry Andric 
13370b57cec5SDimitry Andric       for (const VReg2SUnit &V2SU
13380b57cec5SDimitry Andric            : make_range(VRegUses.find(Reg), VRegUses.end())) {
13390b57cec5SDimitry Andric         SUnit &SU = *V2SU.SU;
13400b57cec5SDimitry Andric         if (SU.isScheduled || &SU == &ExitSU)
13410b57cec5SDimitry Andric           continue;
13420b57cec5SDimitry Andric 
13430b57cec5SDimitry Andric         PressureDiff &PDiff = getPressureDiff(&SU);
13440b57cec5SDimitry Andric         PDiff.addPressureChange(Reg, Decrement, &MRI);
13450b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "  UpdateRegP: SU(" << SU.NodeNum << ") "
13460b57cec5SDimitry Andric                           << printReg(Reg, TRI) << ':'
13470b57cec5SDimitry Andric                           << PrintLaneMask(P.LaneMask) << ' ' << *SU.getInstr();
13480b57cec5SDimitry Andric                    dbgs() << "              to "; PDiff.dump(*TRI););
13490b57cec5SDimitry Andric       }
13500b57cec5SDimitry Andric     } else {
13510b57cec5SDimitry Andric       assert(P.LaneMask.any());
13520b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "  LiveReg: " << printVRegOrUnit(Reg, TRI) << "\n");
13530b57cec5SDimitry Andric       // This may be called before CurrentBottom has been initialized. However,
13540b57cec5SDimitry Andric       // BotRPTracker must have a valid position. We want the value live into the
13550b57cec5SDimitry Andric       // instruction or live out of the block, so ask for the previous
13560b57cec5SDimitry Andric       // instruction's live-out.
13570b57cec5SDimitry Andric       const LiveInterval &LI = LIS->getInterval(Reg);
13580b57cec5SDimitry Andric       VNInfo *VNI;
13590b57cec5SDimitry Andric       MachineBasicBlock::const_iterator I =
13600b57cec5SDimitry Andric         nextIfDebug(BotRPTracker.getPos(), BB->end());
13610b57cec5SDimitry Andric       if (I == BB->end())
13620b57cec5SDimitry Andric         VNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
13630b57cec5SDimitry Andric       else {
13640b57cec5SDimitry Andric         LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(*I));
13650b57cec5SDimitry Andric         VNI = LRQ.valueIn();
13660b57cec5SDimitry Andric       }
13670b57cec5SDimitry Andric       // RegisterPressureTracker guarantees that readsReg is true for LiveUses.
13680b57cec5SDimitry Andric       assert(VNI && "No live value at use.");
13690b57cec5SDimitry Andric       for (const VReg2SUnit &V2SU
13700b57cec5SDimitry Andric            : make_range(VRegUses.find(Reg), VRegUses.end())) {
13710b57cec5SDimitry Andric         SUnit *SU = V2SU.SU;
13720b57cec5SDimitry Andric         // If this use comes before the reaching def, it cannot be a last use,
13730b57cec5SDimitry Andric         // so decrease its pressure change.
13740b57cec5SDimitry Andric         if (!SU->isScheduled && SU != &ExitSU) {
13750b57cec5SDimitry Andric           LiveQueryResult LRQ =
13760b57cec5SDimitry Andric               LI.Query(LIS->getInstructionIndex(*SU->getInstr()));
13770b57cec5SDimitry Andric           if (LRQ.valueIn() == VNI) {
13780b57cec5SDimitry Andric             PressureDiff &PDiff = getPressureDiff(SU);
13790b57cec5SDimitry Andric             PDiff.addPressureChange(Reg, true, &MRI);
13800b57cec5SDimitry Andric             LLVM_DEBUG(dbgs() << "  UpdateRegP: SU(" << SU->NodeNum << ") "
13810b57cec5SDimitry Andric                               << *SU->getInstr();
13820b57cec5SDimitry Andric                        dbgs() << "              to "; PDiff.dump(*TRI););
13830b57cec5SDimitry Andric           }
13840b57cec5SDimitry Andric         }
13850b57cec5SDimitry Andric       }
13860b57cec5SDimitry Andric     }
13870b57cec5SDimitry Andric   }
13880b57cec5SDimitry Andric }
13890b57cec5SDimitry Andric 
dump() const13900b57cec5SDimitry Andric void ScheduleDAGMILive::dump() const {
13910b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
13920b57cec5SDimitry Andric   if (EntrySU.getInstr() != nullptr)
13930b57cec5SDimitry Andric     dumpNodeAll(EntrySU);
13940b57cec5SDimitry Andric   for (const SUnit &SU : SUnits) {
13950b57cec5SDimitry Andric     dumpNodeAll(SU);
13960b57cec5SDimitry Andric     if (ShouldTrackPressure) {
13970b57cec5SDimitry Andric       dbgs() << "  Pressure Diff      : ";
13980b57cec5SDimitry Andric       getPressureDiff(&SU).dump(*TRI);
13990b57cec5SDimitry Andric     }
14000b57cec5SDimitry Andric     dbgs() << "  Single Issue       : ";
14010b57cec5SDimitry Andric     if (SchedModel.mustBeginGroup(SU.getInstr()) &&
14020b57cec5SDimitry Andric         SchedModel.mustEndGroup(SU.getInstr()))
14030b57cec5SDimitry Andric       dbgs() << "true;";
14040b57cec5SDimitry Andric     else
14050b57cec5SDimitry Andric       dbgs() << "false;";
14060b57cec5SDimitry Andric     dbgs() << '\n';
14070b57cec5SDimitry Andric   }
14080b57cec5SDimitry Andric   if (ExitSU.getInstr() != nullptr)
14090b57cec5SDimitry Andric     dumpNodeAll(ExitSU);
14100b57cec5SDimitry Andric #endif
14110b57cec5SDimitry Andric }
14120b57cec5SDimitry Andric 
14130b57cec5SDimitry Andric /// schedule - Called back from MachineScheduler::runOnMachineFunction
14140b57cec5SDimitry Andric /// after setting up the current scheduling region. [RegionBegin, RegionEnd)
14150b57cec5SDimitry Andric /// only includes instructions that have DAG nodes, not scheduling boundaries.
14160b57cec5SDimitry Andric ///
14170b57cec5SDimitry Andric /// This is a skeletal driver, with all the functionality pushed into helpers,
14180b57cec5SDimitry Andric /// so that it can be easily extended by experimental schedulers. Generally,
14190b57cec5SDimitry Andric /// implementing MachineSchedStrategy should be sufficient to implement a new
14200b57cec5SDimitry Andric /// scheduling algorithm. However, if a scheduler further subclasses
14210b57cec5SDimitry Andric /// ScheduleDAGMILive then it will want to override this virtual method in order
14220b57cec5SDimitry Andric /// to update any specialized state.
schedule()14230b57cec5SDimitry Andric void ScheduleDAGMILive::schedule() {
14240b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "ScheduleDAGMILive::schedule starting\n");
14250b57cec5SDimitry Andric   LLVM_DEBUG(SchedImpl->dumpPolicy());
14260b57cec5SDimitry Andric   buildDAGWithRegPressure();
14270b57cec5SDimitry Andric 
1428fe013be4SDimitry Andric   postProcessDAG();
14290b57cec5SDimitry Andric 
14300b57cec5SDimitry Andric   SmallVector<SUnit*, 8> TopRoots, BotRoots;
14310b57cec5SDimitry Andric   findRootsAndBiasEdges(TopRoots, BotRoots);
14320b57cec5SDimitry Andric 
14330b57cec5SDimitry Andric   // Initialize the strategy before modifying the DAG.
14340b57cec5SDimitry Andric   // This may initialize a DFSResult to be used for queue priority.
14350b57cec5SDimitry Andric   SchedImpl->initialize(this);
14360b57cec5SDimitry Andric 
14370b57cec5SDimitry Andric   LLVM_DEBUG(dump());
14380b57cec5SDimitry Andric   if (PrintDAGs) dump();
14390b57cec5SDimitry Andric   if (ViewMISchedDAGs) viewGraph();
14400b57cec5SDimitry Andric 
14410b57cec5SDimitry Andric   // Initialize ready queues now that the DAG and priority data are finalized.
14420b57cec5SDimitry Andric   initQueues(TopRoots, BotRoots);
14430b57cec5SDimitry Andric 
14440b57cec5SDimitry Andric   bool IsTopNode = false;
14450b57cec5SDimitry Andric   while (true) {
14460b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "** ScheduleDAGMILive::schedule picking next node\n");
14470b57cec5SDimitry Andric     SUnit *SU = SchedImpl->pickNode(IsTopNode);
14480b57cec5SDimitry Andric     if (!SU) break;
14490b57cec5SDimitry Andric 
14500b57cec5SDimitry Andric     assert(!SU->isScheduled && "Node already scheduled");
14510b57cec5SDimitry Andric     if (!checkSchedLimit())
14520b57cec5SDimitry Andric       break;
14530b57cec5SDimitry Andric 
14540b57cec5SDimitry Andric     scheduleMI(SU, IsTopNode);
14550b57cec5SDimitry Andric 
14560b57cec5SDimitry Andric     if (DFSResult) {
14570b57cec5SDimitry Andric       unsigned SubtreeID = DFSResult->getSubtreeID(SU);
14580b57cec5SDimitry Andric       if (!ScheduledTrees.test(SubtreeID)) {
14590b57cec5SDimitry Andric         ScheduledTrees.set(SubtreeID);
14600b57cec5SDimitry Andric         DFSResult->scheduleTree(SubtreeID);
14610b57cec5SDimitry Andric         SchedImpl->scheduleTree(SubtreeID);
14620b57cec5SDimitry Andric       }
14630b57cec5SDimitry Andric     }
14640b57cec5SDimitry Andric 
14650b57cec5SDimitry Andric     // Notify the scheduling strategy after updating the DAG.
14660b57cec5SDimitry Andric     SchedImpl->schedNode(SU, IsTopNode);
14670b57cec5SDimitry Andric 
14680b57cec5SDimitry Andric     updateQueues(SU, IsTopNode);
14690b57cec5SDimitry Andric   }
14700b57cec5SDimitry Andric   assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
14710b57cec5SDimitry Andric 
14720b57cec5SDimitry Andric   placeDebugValues();
14730b57cec5SDimitry Andric 
14740b57cec5SDimitry Andric   LLVM_DEBUG({
14750b57cec5SDimitry Andric     dbgs() << "*** Final schedule for "
14760b57cec5SDimitry Andric            << printMBBReference(*begin()->getParent()) << " ***\n";
14770b57cec5SDimitry Andric     dumpSchedule();
14780b57cec5SDimitry Andric     dbgs() << '\n';
14790b57cec5SDimitry Andric   });
14800b57cec5SDimitry Andric }
14810b57cec5SDimitry Andric 
14820b57cec5SDimitry Andric /// Build the DAG and setup three register pressure trackers.
buildDAGWithRegPressure()14830b57cec5SDimitry Andric void ScheduleDAGMILive::buildDAGWithRegPressure() {
14840b57cec5SDimitry Andric   if (!ShouldTrackPressure) {
14850b57cec5SDimitry Andric     RPTracker.reset();
14860b57cec5SDimitry Andric     RegionCriticalPSets.clear();
14870b57cec5SDimitry Andric     buildSchedGraph(AA);
14880b57cec5SDimitry Andric     return;
14890b57cec5SDimitry Andric   }
14900b57cec5SDimitry Andric 
14910b57cec5SDimitry Andric   // Initialize the register pressure tracker used by buildSchedGraph.
14920b57cec5SDimitry Andric   RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
14930b57cec5SDimitry Andric                  ShouldTrackLaneMasks, /*TrackUntiedDefs=*/true);
14940b57cec5SDimitry Andric 
14950b57cec5SDimitry Andric   // Account for liveness generate by the region boundary.
14960b57cec5SDimitry Andric   if (LiveRegionEnd != RegionEnd)
14970b57cec5SDimitry Andric     RPTracker.recede();
14980b57cec5SDimitry Andric 
14990b57cec5SDimitry Andric   // Build the DAG, and compute current register pressure.
15000b57cec5SDimitry Andric   buildSchedGraph(AA, &RPTracker, &SUPressureDiffs, LIS, ShouldTrackLaneMasks);
15010b57cec5SDimitry Andric 
15020b57cec5SDimitry Andric   // Initialize top/bottom trackers after computing region pressure.
15030b57cec5SDimitry Andric   initRegPressure();
15040b57cec5SDimitry Andric }
15050b57cec5SDimitry Andric 
computeDFSResult()15060b57cec5SDimitry Andric void ScheduleDAGMILive::computeDFSResult() {
15070b57cec5SDimitry Andric   if (!DFSResult)
15080b57cec5SDimitry Andric     DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize);
15090b57cec5SDimitry Andric   DFSResult->clear();
15100b57cec5SDimitry Andric   ScheduledTrees.clear();
15110b57cec5SDimitry Andric   DFSResult->resize(SUnits.size());
15120b57cec5SDimitry Andric   DFSResult->compute(SUnits);
15130b57cec5SDimitry Andric   ScheduledTrees.resize(DFSResult->getNumSubtrees());
15140b57cec5SDimitry Andric }
15150b57cec5SDimitry Andric 
15160b57cec5SDimitry Andric /// Compute the max cyclic critical path through the DAG. The scheduling DAG
15170b57cec5SDimitry Andric /// only provides the critical path for single block loops. To handle loops that
15180b57cec5SDimitry Andric /// span blocks, we could use the vreg path latencies provided by
15190b57cec5SDimitry Andric /// MachineTraceMetrics instead. However, MachineTraceMetrics is not currently
15200b57cec5SDimitry Andric /// available for use in the scheduler.
15210b57cec5SDimitry Andric ///
15220b57cec5SDimitry Andric /// The cyclic path estimation identifies a def-use pair that crosses the back
15230b57cec5SDimitry Andric /// edge and considers the depth and height of the nodes. For example, consider
15240b57cec5SDimitry Andric /// the following instruction sequence where each instruction has unit latency
1525e8d8bef9SDimitry Andric /// and defines an eponymous virtual register:
15260b57cec5SDimitry Andric ///
15270b57cec5SDimitry Andric /// a->b(a,c)->c(b)->d(c)->exit
15280b57cec5SDimitry Andric ///
15290b57cec5SDimitry Andric /// The cyclic critical path is a two cycles: b->c->b
15300b57cec5SDimitry Andric /// The acyclic critical path is four cycles: a->b->c->d->exit
15310b57cec5SDimitry Andric /// LiveOutHeight = height(c) = len(c->d->exit) = 2
15320b57cec5SDimitry Andric /// LiveOutDepth = depth(c) + 1 = len(a->b->c) + 1 = 3
15330b57cec5SDimitry Andric /// LiveInHeight = height(b) + 1 = len(b->c->d->exit) + 1 = 4
15340b57cec5SDimitry Andric /// LiveInDepth = depth(b) = len(a->b) = 1
15350b57cec5SDimitry Andric ///
15360b57cec5SDimitry Andric /// LiveOutDepth - LiveInDepth = 3 - 1 = 2
15370b57cec5SDimitry Andric /// LiveInHeight - LiveOutHeight = 4 - 2 = 2
15380b57cec5SDimitry Andric /// CyclicCriticalPath = min(2, 2) = 2
15390b57cec5SDimitry Andric ///
15400b57cec5SDimitry Andric /// This could be relevant to PostRA scheduling, but is currently implemented
15410b57cec5SDimitry Andric /// assuming LiveIntervals.
computeCyclicCriticalPath()15420b57cec5SDimitry Andric unsigned ScheduleDAGMILive::computeCyclicCriticalPath() {
15430b57cec5SDimitry Andric   // This only applies to single block loop.
15440b57cec5SDimitry Andric   if (!BB->isSuccessor(BB))
15450b57cec5SDimitry Andric     return 0;
15460b57cec5SDimitry Andric 
15470b57cec5SDimitry Andric   unsigned MaxCyclicLatency = 0;
15480b57cec5SDimitry Andric   // Visit each live out vreg def to find def/use pairs that cross iterations.
15490b57cec5SDimitry Andric   for (const RegisterMaskPair &P : RPTracker.getPressure().LiveOutRegs) {
1550e8d8bef9SDimitry Andric     Register Reg = P.RegUnit;
1551bdd1243dSDimitry Andric     if (!Reg.isVirtual())
15520b57cec5SDimitry Andric       continue;
15530b57cec5SDimitry Andric     const LiveInterval &LI = LIS->getInterval(Reg);
15540b57cec5SDimitry Andric     const VNInfo *DefVNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
15550b57cec5SDimitry Andric     if (!DefVNI)
15560b57cec5SDimitry Andric       continue;
15570b57cec5SDimitry Andric 
15580b57cec5SDimitry Andric     MachineInstr *DefMI = LIS->getInstructionFromIndex(DefVNI->def);
15590b57cec5SDimitry Andric     const SUnit *DefSU = getSUnit(DefMI);
15600b57cec5SDimitry Andric     if (!DefSU)
15610b57cec5SDimitry Andric       continue;
15620b57cec5SDimitry Andric 
15630b57cec5SDimitry Andric     unsigned LiveOutHeight = DefSU->getHeight();
15640b57cec5SDimitry Andric     unsigned LiveOutDepth = DefSU->getDepth() + DefSU->Latency;
15650b57cec5SDimitry Andric     // Visit all local users of the vreg def.
15660b57cec5SDimitry Andric     for (const VReg2SUnit &V2SU
15670b57cec5SDimitry Andric          : make_range(VRegUses.find(Reg), VRegUses.end())) {
15680b57cec5SDimitry Andric       SUnit *SU = V2SU.SU;
15690b57cec5SDimitry Andric       if (SU == &ExitSU)
15700b57cec5SDimitry Andric         continue;
15710b57cec5SDimitry Andric 
15720b57cec5SDimitry Andric       // Only consider uses of the phi.
15730b57cec5SDimitry Andric       LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(*SU->getInstr()));
15740b57cec5SDimitry Andric       if (!LRQ.valueIn()->isPHIDef())
15750b57cec5SDimitry Andric         continue;
15760b57cec5SDimitry Andric 
15770b57cec5SDimitry Andric       // Assume that a path spanning two iterations is a cycle, which could
15780b57cec5SDimitry Andric       // overestimate in strange cases. This allows cyclic latency to be
15790b57cec5SDimitry Andric       // estimated as the minimum slack of the vreg's depth or height.
15800b57cec5SDimitry Andric       unsigned CyclicLatency = 0;
15810b57cec5SDimitry Andric       if (LiveOutDepth > SU->getDepth())
15820b57cec5SDimitry Andric         CyclicLatency = LiveOutDepth - SU->getDepth();
15830b57cec5SDimitry Andric 
15840b57cec5SDimitry Andric       unsigned LiveInHeight = SU->getHeight() + DefSU->Latency;
15850b57cec5SDimitry Andric       if (LiveInHeight > LiveOutHeight) {
15860b57cec5SDimitry Andric         if (LiveInHeight - LiveOutHeight < CyclicLatency)
15870b57cec5SDimitry Andric           CyclicLatency = LiveInHeight - LiveOutHeight;
15880b57cec5SDimitry Andric       } else
15890b57cec5SDimitry Andric         CyclicLatency = 0;
15900b57cec5SDimitry Andric 
15910b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "Cyclic Path: SU(" << DefSU->NodeNum << ") -> SU("
15920b57cec5SDimitry Andric                         << SU->NodeNum << ") = " << CyclicLatency << "c\n");
15930b57cec5SDimitry Andric       if (CyclicLatency > MaxCyclicLatency)
15940b57cec5SDimitry Andric         MaxCyclicLatency = CyclicLatency;
15950b57cec5SDimitry Andric     }
15960b57cec5SDimitry Andric   }
15970b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Cyclic Critical Path: " << MaxCyclicLatency << "c\n");
15980b57cec5SDimitry Andric   return MaxCyclicLatency;
15990b57cec5SDimitry Andric }
16000b57cec5SDimitry Andric 
16010b57cec5SDimitry Andric /// Release ExitSU predecessors and setup scheduler queues. Re-position
16020b57cec5SDimitry Andric /// the Top RP tracker in case the region beginning has changed.
initQueues(ArrayRef<SUnit * > TopRoots,ArrayRef<SUnit * > BotRoots)16030b57cec5SDimitry Andric void ScheduleDAGMILive::initQueues(ArrayRef<SUnit*> TopRoots,
16040b57cec5SDimitry Andric                                    ArrayRef<SUnit*> BotRoots) {
16050b57cec5SDimitry Andric   ScheduleDAGMI::initQueues(TopRoots, BotRoots);
16060b57cec5SDimitry Andric   if (ShouldTrackPressure) {
16070b57cec5SDimitry Andric     assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
16080b57cec5SDimitry Andric     TopRPTracker.setPos(CurrentTop);
16090b57cec5SDimitry Andric   }
16100b57cec5SDimitry Andric }
16110b57cec5SDimitry Andric 
16120b57cec5SDimitry Andric /// Move an instruction and update register pressure.
scheduleMI(SUnit * SU,bool IsTopNode)16130b57cec5SDimitry Andric void ScheduleDAGMILive::scheduleMI(SUnit *SU, bool IsTopNode) {
16140b57cec5SDimitry Andric   // Move the instruction to its new location in the instruction stream.
16150b57cec5SDimitry Andric   MachineInstr *MI = SU->getInstr();
16160b57cec5SDimitry Andric 
16170b57cec5SDimitry Andric   if (IsTopNode) {
16180b57cec5SDimitry Andric     assert(SU->isTopReady() && "node still has unscheduled dependencies");
16190b57cec5SDimitry Andric     if (&*CurrentTop == MI)
16200b57cec5SDimitry Andric       CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
16210b57cec5SDimitry Andric     else {
16220b57cec5SDimitry Andric       moveInstruction(MI, CurrentTop);
16230b57cec5SDimitry Andric       TopRPTracker.setPos(MI);
16240b57cec5SDimitry Andric     }
16250b57cec5SDimitry Andric 
16260b57cec5SDimitry Andric     if (ShouldTrackPressure) {
16270b57cec5SDimitry Andric       // Update top scheduled pressure.
16280b57cec5SDimitry Andric       RegisterOperands RegOpers;
16290b57cec5SDimitry Andric       RegOpers.collect(*MI, *TRI, MRI, ShouldTrackLaneMasks, false);
16300b57cec5SDimitry Andric       if (ShouldTrackLaneMasks) {
16310b57cec5SDimitry Andric         // Adjust liveness and add missing dead+read-undef flags.
16320b57cec5SDimitry Andric         SlotIndex SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot();
16330b57cec5SDimitry Andric         RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx, MI);
16340b57cec5SDimitry Andric       } else {
16350b57cec5SDimitry Andric         // Adjust for missing dead-def flags.
16360b57cec5SDimitry Andric         RegOpers.detectDeadDefs(*MI, *LIS);
16370b57cec5SDimitry Andric       }
16380b57cec5SDimitry Andric 
16390b57cec5SDimitry Andric       TopRPTracker.advance(RegOpers);
16400b57cec5SDimitry Andric       assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
16410b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "Top Pressure:\n"; dumpRegSetPressure(
16420b57cec5SDimitry Andric                      TopRPTracker.getRegSetPressureAtPos(), TRI););
16430b57cec5SDimitry Andric 
16440b57cec5SDimitry Andric       updateScheduledPressure(SU, TopRPTracker.getPressure().MaxSetPressure);
16450b57cec5SDimitry Andric     }
16460b57cec5SDimitry Andric   } else {
16470b57cec5SDimitry Andric     assert(SU->isBottomReady() && "node still has unscheduled dependencies");
16480b57cec5SDimitry Andric     MachineBasicBlock::iterator priorII =
16490b57cec5SDimitry Andric       priorNonDebug(CurrentBottom, CurrentTop);
16500b57cec5SDimitry Andric     if (&*priorII == MI)
16510b57cec5SDimitry Andric       CurrentBottom = priorII;
16520b57cec5SDimitry Andric     else {
16530b57cec5SDimitry Andric       if (&*CurrentTop == MI) {
16540b57cec5SDimitry Andric         CurrentTop = nextIfDebug(++CurrentTop, priorII);
16550b57cec5SDimitry Andric         TopRPTracker.setPos(CurrentTop);
16560b57cec5SDimitry Andric       }
16570b57cec5SDimitry Andric       moveInstruction(MI, CurrentBottom);
16580b57cec5SDimitry Andric       CurrentBottom = MI;
16590b57cec5SDimitry Andric       BotRPTracker.setPos(CurrentBottom);
16600b57cec5SDimitry Andric     }
16610b57cec5SDimitry Andric     if (ShouldTrackPressure) {
16620b57cec5SDimitry Andric       RegisterOperands RegOpers;
16630b57cec5SDimitry Andric       RegOpers.collect(*MI, *TRI, MRI, ShouldTrackLaneMasks, false);
16640b57cec5SDimitry Andric       if (ShouldTrackLaneMasks) {
16650b57cec5SDimitry Andric         // Adjust liveness and add missing dead+read-undef flags.
16660b57cec5SDimitry Andric         SlotIndex SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot();
16670b57cec5SDimitry Andric         RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx, MI);
16680b57cec5SDimitry Andric       } else {
16690b57cec5SDimitry Andric         // Adjust for missing dead-def flags.
16700b57cec5SDimitry Andric         RegOpers.detectDeadDefs(*MI, *LIS);
16710b57cec5SDimitry Andric       }
16720b57cec5SDimitry Andric 
16730b57cec5SDimitry Andric       if (BotRPTracker.getPos() != CurrentBottom)
16740b57cec5SDimitry Andric         BotRPTracker.recedeSkipDebugValues();
16750b57cec5SDimitry Andric       SmallVector<RegisterMaskPair, 8> LiveUses;
16760b57cec5SDimitry Andric       BotRPTracker.recede(RegOpers, &LiveUses);
16770b57cec5SDimitry Andric       assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
16780b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "Bottom Pressure:\n"; dumpRegSetPressure(
16790b57cec5SDimitry Andric                      BotRPTracker.getRegSetPressureAtPos(), TRI););
16800b57cec5SDimitry Andric 
16810b57cec5SDimitry Andric       updateScheduledPressure(SU, BotRPTracker.getPressure().MaxSetPressure);
16820b57cec5SDimitry Andric       updatePressureDiffs(LiveUses);
16830b57cec5SDimitry Andric     }
16840b57cec5SDimitry Andric   }
16850b57cec5SDimitry Andric }
16860b57cec5SDimitry Andric 
16870b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
16880b57cec5SDimitry Andric // BaseMemOpClusterMutation - DAG post-processing to cluster loads or stores.
16890b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
16900b57cec5SDimitry Andric 
16910b57cec5SDimitry Andric namespace {
16920b57cec5SDimitry Andric 
16930b57cec5SDimitry Andric /// Post-process the DAG to create cluster edges between neighboring
16940b57cec5SDimitry Andric /// loads or between neighboring stores.
16950b57cec5SDimitry Andric class BaseMemOpClusterMutation : public ScheduleDAGMutation {
16960b57cec5SDimitry Andric   struct MemOpInfo {
16970b57cec5SDimitry Andric     SUnit *SU;
16985ffd83dbSDimitry Andric     SmallVector<const MachineOperand *, 4> BaseOps;
16990b57cec5SDimitry Andric     int64_t Offset;
17005ffd83dbSDimitry Andric     unsigned Width;
1701c9157d92SDimitry Andric     bool OffsetIsScalable;
17020b57cec5SDimitry Andric 
MemOpInfo__anon83be91fe0511::BaseMemOpClusterMutation::MemOpInfo17035ffd83dbSDimitry Andric     MemOpInfo(SUnit *SU, ArrayRef<const MachineOperand *> BaseOps,
1704c9157d92SDimitry Andric               int64_t Offset, bool OffsetIsScalable, unsigned Width)
17055ffd83dbSDimitry Andric         : SU(SU), BaseOps(BaseOps.begin(), BaseOps.end()), Offset(Offset),
1706c9157d92SDimitry Andric           Width(Width), OffsetIsScalable(OffsetIsScalable) {}
17070b57cec5SDimitry Andric 
Compare__anon83be91fe0511::BaseMemOpClusterMutation::MemOpInfo17085ffd83dbSDimitry Andric     static bool Compare(const MachineOperand *const &A,
17095ffd83dbSDimitry Andric                         const MachineOperand *const &B) {
17105ffd83dbSDimitry Andric       if (A->getType() != B->getType())
17115ffd83dbSDimitry Andric         return A->getType() < B->getType();
17125ffd83dbSDimitry Andric       if (A->isReg())
17135ffd83dbSDimitry Andric         return A->getReg() < B->getReg();
17145ffd83dbSDimitry Andric       if (A->isFI()) {
17155ffd83dbSDimitry Andric         const MachineFunction &MF = *A->getParent()->getParent()->getParent();
17160b57cec5SDimitry Andric         const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
17170b57cec5SDimitry Andric         bool StackGrowsDown = TFI.getStackGrowthDirection() ==
17180b57cec5SDimitry Andric                               TargetFrameLowering::StackGrowsDown;
17195ffd83dbSDimitry Andric         return StackGrowsDown ? A->getIndex() > B->getIndex()
17205ffd83dbSDimitry Andric                               : A->getIndex() < B->getIndex();
17210b57cec5SDimitry Andric       }
17220b57cec5SDimitry Andric 
17230b57cec5SDimitry Andric       llvm_unreachable("MemOpClusterMutation only supports register or frame "
17240b57cec5SDimitry Andric                        "index bases.");
17250b57cec5SDimitry Andric     }
17265ffd83dbSDimitry Andric 
operator <__anon83be91fe0511::BaseMemOpClusterMutation::MemOpInfo17275ffd83dbSDimitry Andric     bool operator<(const MemOpInfo &RHS) const {
17285ffd83dbSDimitry Andric       // FIXME: Don't compare everything twice. Maybe use C++20 three way
17295ffd83dbSDimitry Andric       // comparison instead when it's available.
17305ffd83dbSDimitry Andric       if (std::lexicographical_compare(BaseOps.begin(), BaseOps.end(),
17315ffd83dbSDimitry Andric                                        RHS.BaseOps.begin(), RHS.BaseOps.end(),
17325ffd83dbSDimitry Andric                                        Compare))
17335ffd83dbSDimitry Andric         return true;
17345ffd83dbSDimitry Andric       if (std::lexicographical_compare(RHS.BaseOps.begin(), RHS.BaseOps.end(),
17355ffd83dbSDimitry Andric                                        BaseOps.begin(), BaseOps.end(), Compare))
17365ffd83dbSDimitry Andric         return false;
17375ffd83dbSDimitry Andric       if (Offset != RHS.Offset)
17385ffd83dbSDimitry Andric         return Offset < RHS.Offset;
17395ffd83dbSDimitry Andric       return SU->NodeNum < RHS.SU->NodeNum;
17405ffd83dbSDimitry Andric     }
17410b57cec5SDimitry Andric   };
17420b57cec5SDimitry Andric 
17430b57cec5SDimitry Andric   const TargetInstrInfo *TII;
17440b57cec5SDimitry Andric   const TargetRegisterInfo *TRI;
17450b57cec5SDimitry Andric   bool IsLoad;
1746*a58f00eaSDimitry Andric   bool ReorderWhileClustering;
17470b57cec5SDimitry Andric 
17480b57cec5SDimitry Andric public:
BaseMemOpClusterMutation(const TargetInstrInfo * tii,const TargetRegisterInfo * tri,bool IsLoad,bool ReorderWhileClustering)17490b57cec5SDimitry Andric   BaseMemOpClusterMutation(const TargetInstrInfo *tii,
1750*a58f00eaSDimitry Andric                            const TargetRegisterInfo *tri, bool IsLoad,
1751*a58f00eaSDimitry Andric                            bool ReorderWhileClustering)
1752*a58f00eaSDimitry Andric       : TII(tii), TRI(tri), IsLoad(IsLoad),
1753*a58f00eaSDimitry Andric         ReorderWhileClustering(ReorderWhileClustering) {}
17540b57cec5SDimitry Andric 
17550b57cec5SDimitry Andric   void apply(ScheduleDAGInstrs *DAGInstrs) override;
17560b57cec5SDimitry Andric 
17570b57cec5SDimitry Andric protected:
1758e8d8bef9SDimitry Andric   void clusterNeighboringMemOps(ArrayRef<MemOpInfo> MemOps, bool FastCluster,
1759e8d8bef9SDimitry Andric                                 ScheduleDAGInstrs *DAG);
1760e8d8bef9SDimitry Andric   void collectMemOpRecords(std::vector<SUnit> &SUnits,
1761e8d8bef9SDimitry Andric                            SmallVectorImpl<MemOpInfo> &MemOpRecords);
1762e8d8bef9SDimitry Andric   bool groupMemOps(ArrayRef<MemOpInfo> MemOps, ScheduleDAGInstrs *DAG,
1763e8d8bef9SDimitry Andric                    DenseMap<unsigned, SmallVector<MemOpInfo, 32>> &Groups);
17640b57cec5SDimitry Andric };
17650b57cec5SDimitry Andric 
17660b57cec5SDimitry Andric class StoreClusterMutation : public BaseMemOpClusterMutation {
17670b57cec5SDimitry Andric public:
StoreClusterMutation(const TargetInstrInfo * tii,const TargetRegisterInfo * tri,bool ReorderWhileClustering)17680b57cec5SDimitry Andric   StoreClusterMutation(const TargetInstrInfo *tii,
1769*a58f00eaSDimitry Andric                        const TargetRegisterInfo *tri,
1770*a58f00eaSDimitry Andric                        bool ReorderWhileClustering)
1771*a58f00eaSDimitry Andric       : BaseMemOpClusterMutation(tii, tri, false, ReorderWhileClustering) {}
17720b57cec5SDimitry Andric };
17730b57cec5SDimitry Andric 
17740b57cec5SDimitry Andric class LoadClusterMutation : public BaseMemOpClusterMutation {
17750b57cec5SDimitry Andric public:
LoadClusterMutation(const TargetInstrInfo * tii,const TargetRegisterInfo * tri,bool ReorderWhileClustering)1776*a58f00eaSDimitry Andric   LoadClusterMutation(const TargetInstrInfo *tii, const TargetRegisterInfo *tri,
1777*a58f00eaSDimitry Andric                       bool ReorderWhileClustering)
1778*a58f00eaSDimitry Andric       : BaseMemOpClusterMutation(tii, tri, true, ReorderWhileClustering) {}
17790b57cec5SDimitry Andric };
17800b57cec5SDimitry Andric 
17810b57cec5SDimitry Andric } // end anonymous namespace
17820b57cec5SDimitry Andric 
17830b57cec5SDimitry Andric namespace llvm {
17840b57cec5SDimitry Andric 
17850b57cec5SDimitry Andric std::unique_ptr<ScheduleDAGMutation>
createLoadClusterDAGMutation(const TargetInstrInfo * TII,const TargetRegisterInfo * TRI,bool ReorderWhileClustering)17860b57cec5SDimitry Andric createLoadClusterDAGMutation(const TargetInstrInfo *TII,
1787*a58f00eaSDimitry Andric                              const TargetRegisterInfo *TRI,
1788*a58f00eaSDimitry Andric                              bool ReorderWhileClustering) {
1789*a58f00eaSDimitry Andric   return EnableMemOpCluster ? std::make_unique<LoadClusterMutation>(
1790*a58f00eaSDimitry Andric                                   TII, TRI, ReorderWhileClustering)
17910b57cec5SDimitry Andric                             : nullptr;
17920b57cec5SDimitry Andric }
17930b57cec5SDimitry Andric 
17940b57cec5SDimitry Andric std::unique_ptr<ScheduleDAGMutation>
createStoreClusterDAGMutation(const TargetInstrInfo * TII,const TargetRegisterInfo * TRI,bool ReorderWhileClustering)17950b57cec5SDimitry Andric createStoreClusterDAGMutation(const TargetInstrInfo *TII,
1796*a58f00eaSDimitry Andric                               const TargetRegisterInfo *TRI,
1797*a58f00eaSDimitry Andric                               bool ReorderWhileClustering) {
1798*a58f00eaSDimitry Andric   return EnableMemOpCluster ? std::make_unique<StoreClusterMutation>(
1799*a58f00eaSDimitry Andric                                   TII, TRI, ReorderWhileClustering)
18000b57cec5SDimitry Andric                             : nullptr;
18010b57cec5SDimitry Andric }
18020b57cec5SDimitry Andric 
18030b57cec5SDimitry Andric } // end namespace llvm
18040b57cec5SDimitry Andric 
1805e8d8bef9SDimitry Andric // Sorting all the loads/stores first, then for each load/store, checking the
1806e8d8bef9SDimitry Andric // following load/store one by one, until reach the first non-dependent one and
1807e8d8bef9SDimitry Andric // call target hook to see if they can cluster.
1808e8d8bef9SDimitry Andric // If FastCluster is enabled, we assume that, all the loads/stores have been
1809e8d8bef9SDimitry Andric // preprocessed and now, they didn't have dependencies on each other.
clusterNeighboringMemOps(ArrayRef<MemOpInfo> MemOpRecords,bool FastCluster,ScheduleDAGInstrs * DAG)18100b57cec5SDimitry Andric void BaseMemOpClusterMutation::clusterNeighboringMemOps(
1811e8d8bef9SDimitry Andric     ArrayRef<MemOpInfo> MemOpRecords, bool FastCluster,
1812e8d8bef9SDimitry Andric     ScheduleDAGInstrs *DAG) {
1813e8d8bef9SDimitry Andric   // Keep track of the current cluster length and bytes for each SUnit.
1814e8d8bef9SDimitry Andric   DenseMap<unsigned, std::pair<unsigned, unsigned>> SUnit2ClusterInfo;
18155ffd83dbSDimitry Andric 
18165ffd83dbSDimitry Andric   // At this point, `MemOpRecords` array must hold atleast two mem ops. Try to
18175ffd83dbSDimitry Andric   // cluster mem ops collected within `MemOpRecords` array.
18180b57cec5SDimitry Andric   for (unsigned Idx = 0, End = MemOpRecords.size(); Idx < (End - 1); ++Idx) {
18195ffd83dbSDimitry Andric     // Decision to cluster mem ops is taken based on target dependent logic
18205ffd83dbSDimitry Andric     auto MemOpa = MemOpRecords[Idx];
1821e8d8bef9SDimitry Andric 
1822e8d8bef9SDimitry Andric     // Seek for the next load/store to do the cluster.
1823e8d8bef9SDimitry Andric     unsigned NextIdx = Idx + 1;
1824e8d8bef9SDimitry Andric     for (; NextIdx < End; ++NextIdx)
1825e8d8bef9SDimitry Andric       // Skip if MemOpb has been clustered already or has dependency with
1826e8d8bef9SDimitry Andric       // MemOpa.
1827e8d8bef9SDimitry Andric       if (!SUnit2ClusterInfo.count(MemOpRecords[NextIdx].SU->NodeNum) &&
1828e8d8bef9SDimitry Andric           (FastCluster ||
1829e8d8bef9SDimitry Andric            (!DAG->IsReachable(MemOpRecords[NextIdx].SU, MemOpa.SU) &&
1830e8d8bef9SDimitry Andric             !DAG->IsReachable(MemOpa.SU, MemOpRecords[NextIdx].SU))))
1831e8d8bef9SDimitry Andric         break;
1832e8d8bef9SDimitry Andric     if (NextIdx == End)
18335ffd83dbSDimitry Andric       continue;
1834e8d8bef9SDimitry Andric 
1835e8d8bef9SDimitry Andric     auto MemOpb = MemOpRecords[NextIdx];
1836e8d8bef9SDimitry Andric     unsigned ClusterLength = 2;
1837e8d8bef9SDimitry Andric     unsigned CurrentClusterBytes = MemOpa.Width + MemOpb.Width;
1838e8d8bef9SDimitry Andric     if (SUnit2ClusterInfo.count(MemOpa.SU->NodeNum)) {
1839e8d8bef9SDimitry Andric       ClusterLength = SUnit2ClusterInfo[MemOpa.SU->NodeNum].first + 1;
1840e8d8bef9SDimitry Andric       CurrentClusterBytes =
1841e8d8bef9SDimitry Andric           SUnit2ClusterInfo[MemOpa.SU->NodeNum].second + MemOpb.Width;
18425ffd83dbSDimitry Andric     }
18435ffd83dbSDimitry Andric 
1844c9157d92SDimitry Andric     if (!TII->shouldClusterMemOps(MemOpa.BaseOps, MemOpa.Offset,
1845c9157d92SDimitry Andric                                   MemOpa.OffsetIsScalable, MemOpb.BaseOps,
1846c9157d92SDimitry Andric                                   MemOpb.Offset, MemOpb.OffsetIsScalable,
1847c9157d92SDimitry Andric                                   ClusterLength, CurrentClusterBytes))
1848e8d8bef9SDimitry Andric       continue;
1849e8d8bef9SDimitry Andric 
18505ffd83dbSDimitry Andric     SUnit *SUa = MemOpa.SU;
18515ffd83dbSDimitry Andric     SUnit *SUb = MemOpb.SU;
1852*a58f00eaSDimitry Andric     if (!ReorderWhileClustering && SUa->NodeNum > SUb->NodeNum)
1853480093f4SDimitry Andric       std::swap(SUa, SUb);
18545ffd83dbSDimitry Andric 
18555ffd83dbSDimitry Andric     // FIXME: Is this check really required?
1856e8d8bef9SDimitry Andric     if (!DAG->addEdge(SUb, SDep(SUa, SDep::Cluster)))
18575ffd83dbSDimitry Andric       continue;
18585ffd83dbSDimitry Andric 
18590b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Cluster ld/st SU(" << SUa->NodeNum << ") - SU("
18600b57cec5SDimitry Andric                       << SUb->NodeNum << ")\n");
1861e8d8bef9SDimitry Andric     ++NumClustered;
18625ffd83dbSDimitry Andric 
1863e8d8bef9SDimitry Andric     if (IsLoad) {
18640b57cec5SDimitry Andric       // Copy successor edges from SUa to SUb. Interleaving computation
18650b57cec5SDimitry Andric       // dependent on SUa can prevent load combining due to register reuse.
18665ffd83dbSDimitry Andric       // Predecessor edges do not need to be copied from SUb to SUa since
18675ffd83dbSDimitry Andric       // nearby loads should have effectively the same inputs.
18680b57cec5SDimitry Andric       for (const SDep &Succ : SUa->Succs) {
18690b57cec5SDimitry Andric         if (Succ.getSUnit() == SUb)
18700b57cec5SDimitry Andric           continue;
18710b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "  Copy Succ SU(" << Succ.getSUnit()->NodeNum
18720b57cec5SDimitry Andric                           << ")\n");
18730b57cec5SDimitry Andric         DAG->addEdge(Succ.getSUnit(), SDep(SUb, SDep::Artificial));
18740b57cec5SDimitry Andric       }
1875e8d8bef9SDimitry Andric     } else {
1876e8d8bef9SDimitry Andric       // Copy predecessor edges from SUb to SUa to avoid the SUnits that
1877e8d8bef9SDimitry Andric       // SUb dependent on scheduled in-between SUb and SUa. Successor edges
1878e8d8bef9SDimitry Andric       // do not need to be copied from SUa to SUb since no one will depend
1879e8d8bef9SDimitry Andric       // on stores.
1880e8d8bef9SDimitry Andric       // Notice that, we don't need to care about the memory dependency as
1881e8d8bef9SDimitry Andric       // we won't try to cluster them if they have any memory dependency.
1882e8d8bef9SDimitry Andric       for (const SDep &Pred : SUb->Preds) {
1883e8d8bef9SDimitry Andric         if (Pred.getSUnit() == SUa)
1884e8d8bef9SDimitry Andric           continue;
1885e8d8bef9SDimitry Andric         LLVM_DEBUG(dbgs() << "  Copy Pred SU(" << Pred.getSUnit()->NodeNum
1886e8d8bef9SDimitry Andric                           << ")\n");
1887e8d8bef9SDimitry Andric         DAG->addEdge(SUa, SDep(Pred.getSUnit(), SDep::Artificial));
1888e8d8bef9SDimitry Andric       }
1889e8d8bef9SDimitry Andric     }
1890e8d8bef9SDimitry Andric 
1891e8d8bef9SDimitry Andric     SUnit2ClusterInfo[MemOpb.SU->NodeNum] = {ClusterLength,
1892e8d8bef9SDimitry Andric                                              CurrentClusterBytes};
18935ffd83dbSDimitry Andric 
18945ffd83dbSDimitry Andric     LLVM_DEBUG(dbgs() << "  Curr cluster length: " << ClusterLength
18955ffd83dbSDimitry Andric                       << ", Curr cluster bytes: " << CurrentClusterBytes
18965ffd83dbSDimitry Andric                       << "\n");
18970b57cec5SDimitry Andric   }
18980b57cec5SDimitry Andric }
18990b57cec5SDimitry Andric 
collectMemOpRecords(std::vector<SUnit> & SUnits,SmallVectorImpl<MemOpInfo> & MemOpRecords)1900e8d8bef9SDimitry Andric void BaseMemOpClusterMutation::collectMemOpRecords(
1901e8d8bef9SDimitry Andric     std::vector<SUnit> &SUnits, SmallVectorImpl<MemOpInfo> &MemOpRecords) {
1902e8d8bef9SDimitry Andric   for (auto &SU : SUnits) {
19030b57cec5SDimitry Andric     if ((IsLoad && !SU.getInstr()->mayLoad()) ||
19040b57cec5SDimitry Andric         (!IsLoad && !SU.getInstr()->mayStore()))
19050b57cec5SDimitry Andric       continue;
19060b57cec5SDimitry Andric 
1907e8d8bef9SDimitry Andric     const MachineInstr &MI = *SU.getInstr();
1908e8d8bef9SDimitry Andric     SmallVector<const MachineOperand *, 4> BaseOps;
1909e8d8bef9SDimitry Andric     int64_t Offset;
1910e8d8bef9SDimitry Andric     bool OffsetIsScalable;
1911e8d8bef9SDimitry Andric     unsigned Width;
1912e8d8bef9SDimitry Andric     if (TII->getMemOperandsWithOffsetWidth(MI, BaseOps, Offset,
1913e8d8bef9SDimitry Andric                                            OffsetIsScalable, Width, TRI)) {
1914c9157d92SDimitry Andric       MemOpRecords.push_back(
1915c9157d92SDimitry Andric           MemOpInfo(&SU, BaseOps, Offset, OffsetIsScalable, Width));
1916e8d8bef9SDimitry Andric 
1917e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Num BaseOps: " << BaseOps.size() << ", Offset: "
1918e8d8bef9SDimitry Andric                         << Offset << ", OffsetIsScalable: " << OffsetIsScalable
1919e8d8bef9SDimitry Andric                         << ", Width: " << Width << "\n");
1920e8d8bef9SDimitry Andric     }
1921e8d8bef9SDimitry Andric #ifndef NDEBUG
1922fcaf7f86SDimitry Andric     for (const auto *Op : BaseOps)
1923e8d8bef9SDimitry Andric       assert(Op);
1924e8d8bef9SDimitry Andric #endif
1925e8d8bef9SDimitry Andric   }
1926e8d8bef9SDimitry Andric }
1927e8d8bef9SDimitry Andric 
groupMemOps(ArrayRef<MemOpInfo> MemOps,ScheduleDAGInstrs * DAG,DenseMap<unsigned,SmallVector<MemOpInfo,32>> & Groups)1928e8d8bef9SDimitry Andric bool BaseMemOpClusterMutation::groupMemOps(
1929e8d8bef9SDimitry Andric     ArrayRef<MemOpInfo> MemOps, ScheduleDAGInstrs *DAG,
1930e8d8bef9SDimitry Andric     DenseMap<unsigned, SmallVector<MemOpInfo, 32>> &Groups) {
1931e8d8bef9SDimitry Andric   bool FastCluster =
1932e8d8bef9SDimitry Andric       ForceFastCluster ||
1933e8d8bef9SDimitry Andric       MemOps.size() * DAG->SUnits.size() / 1000 > FastClusterThreshold;
1934e8d8bef9SDimitry Andric 
1935e8d8bef9SDimitry Andric   for (const auto &MemOp : MemOps) {
19360b57cec5SDimitry Andric     unsigned ChainPredID = DAG->SUnits.size();
1937e8d8bef9SDimitry Andric     if (FastCluster) {
1938e8d8bef9SDimitry Andric       for (const SDep &Pred : MemOp.SU->Preds) {
1939e8d8bef9SDimitry Andric         // We only want to cluster the mem ops that have the same ctrl(non-data)
1940e8d8bef9SDimitry Andric         // pred so that they didn't have ctrl dependency for each other. But for
1941e8d8bef9SDimitry Andric         // store instrs, we can still cluster them if the pred is load instr.
1942e8d8bef9SDimitry Andric         if ((Pred.isCtrl() &&
1943e8d8bef9SDimitry Andric              (IsLoad ||
1944e8d8bef9SDimitry Andric               (Pred.getSUnit() && Pred.getSUnit()->getInstr()->mayStore()))) &&
1945e8d8bef9SDimitry Andric             !Pred.isArtificial()) {
19460b57cec5SDimitry Andric           ChainPredID = Pred.getSUnit()->NodeNum;
19470b57cec5SDimitry Andric           break;
19480b57cec5SDimitry Andric         }
19490b57cec5SDimitry Andric       }
1950e8d8bef9SDimitry Andric     } else
1951e8d8bef9SDimitry Andric       ChainPredID = 0;
1952e8d8bef9SDimitry Andric 
1953e8d8bef9SDimitry Andric     Groups[ChainPredID].push_back(MemOp);
1954e8d8bef9SDimitry Andric   }
1955e8d8bef9SDimitry Andric   return FastCluster;
19560b57cec5SDimitry Andric }
19570b57cec5SDimitry Andric 
1958e8d8bef9SDimitry Andric /// Callback from DAG postProcessing to create cluster edges for loads/stores.
apply(ScheduleDAGInstrs * DAG)1959e8d8bef9SDimitry Andric void BaseMemOpClusterMutation::apply(ScheduleDAGInstrs *DAG) {
1960e8d8bef9SDimitry Andric   // Collect all the clusterable loads/stores
1961e8d8bef9SDimitry Andric   SmallVector<MemOpInfo, 32> MemOpRecords;
1962e8d8bef9SDimitry Andric   collectMemOpRecords(DAG->SUnits, MemOpRecords);
1963e8d8bef9SDimitry Andric 
1964e8d8bef9SDimitry Andric   if (MemOpRecords.size() < 2)
1965e8d8bef9SDimitry Andric     return;
1966e8d8bef9SDimitry Andric 
1967e8d8bef9SDimitry Andric   // Put the loads/stores without dependency into the same group with some
1968e8d8bef9SDimitry Andric   // heuristic if the DAG is too complex to avoid compiling time blow up.
1969e8d8bef9SDimitry Andric   // Notice that, some fusion pair could be lost with this.
1970e8d8bef9SDimitry Andric   DenseMap<unsigned, SmallVector<MemOpInfo, 32>> Groups;
1971e8d8bef9SDimitry Andric   bool FastCluster = groupMemOps(MemOpRecords, DAG, Groups);
1972e8d8bef9SDimitry Andric 
1973e8d8bef9SDimitry Andric   for (auto &Group : Groups) {
1974e8d8bef9SDimitry Andric     // Sorting the loads/stores, so that, we can stop the cluster as early as
1975e8d8bef9SDimitry Andric     // possible.
1976e8d8bef9SDimitry Andric     llvm::sort(Group.second);
1977e8d8bef9SDimitry Andric 
1978e8d8bef9SDimitry Andric     // Trying to cluster all the neighboring loads/stores.
1979e8d8bef9SDimitry Andric     clusterNeighboringMemOps(Group.second, FastCluster, DAG);
1980e8d8bef9SDimitry Andric   }
19810b57cec5SDimitry Andric }
19820b57cec5SDimitry Andric 
19830b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
19840b57cec5SDimitry Andric // CopyConstrain - DAG post-processing to encourage copy elimination.
19850b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
19860b57cec5SDimitry Andric 
19870b57cec5SDimitry Andric namespace {
19880b57cec5SDimitry Andric 
19890b57cec5SDimitry Andric /// Post-process the DAG to create weak edges from all uses of a copy to
19900b57cec5SDimitry Andric /// the one use that defines the copy's source vreg, most likely an induction
19910b57cec5SDimitry Andric /// variable increment.
19920b57cec5SDimitry Andric class CopyConstrain : public ScheduleDAGMutation {
19930b57cec5SDimitry Andric   // Transient state.
19940b57cec5SDimitry Andric   SlotIndex RegionBeginIdx;
19950b57cec5SDimitry Andric 
19960b57cec5SDimitry Andric   // RegionEndIdx is the slot index of the last non-debug instruction in the
19970b57cec5SDimitry Andric   // scheduling region. So we may have RegionBeginIdx == RegionEndIdx.
19980b57cec5SDimitry Andric   SlotIndex RegionEndIdx;
19990b57cec5SDimitry Andric 
20000b57cec5SDimitry Andric public:
CopyConstrain(const TargetInstrInfo *,const TargetRegisterInfo *)20010b57cec5SDimitry Andric   CopyConstrain(const TargetInstrInfo *, const TargetRegisterInfo *) {}
20020b57cec5SDimitry Andric 
20030b57cec5SDimitry Andric   void apply(ScheduleDAGInstrs *DAGInstrs) override;
20040b57cec5SDimitry Andric 
20050b57cec5SDimitry Andric protected:
20060b57cec5SDimitry Andric   void constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG);
20070b57cec5SDimitry Andric };
20080b57cec5SDimitry Andric 
20090b57cec5SDimitry Andric } // end anonymous namespace
20100b57cec5SDimitry Andric 
20110b57cec5SDimitry Andric namespace llvm {
20120b57cec5SDimitry Andric 
20130b57cec5SDimitry Andric std::unique_ptr<ScheduleDAGMutation>
createCopyConstrainDAGMutation(const TargetInstrInfo * TII,const TargetRegisterInfo * TRI)20140b57cec5SDimitry Andric createCopyConstrainDAGMutation(const TargetInstrInfo *TII,
20150b57cec5SDimitry Andric                                const TargetRegisterInfo *TRI) {
20168bcb0991SDimitry Andric   return std::make_unique<CopyConstrain>(TII, TRI);
20170b57cec5SDimitry Andric }
20180b57cec5SDimitry Andric 
20190b57cec5SDimitry Andric } // end namespace llvm
20200b57cec5SDimitry Andric 
20210b57cec5SDimitry Andric /// constrainLocalCopy handles two possibilities:
20220b57cec5SDimitry Andric /// 1) Local src:
20230b57cec5SDimitry Andric /// I0:     = dst
20240b57cec5SDimitry Andric /// I1: src = ...
20250b57cec5SDimitry Andric /// I2:     = dst
20260b57cec5SDimitry Andric /// I3: dst = src (copy)
20270b57cec5SDimitry Andric /// (create pred->succ edges I0->I1, I2->I1)
20280b57cec5SDimitry Andric ///
20290b57cec5SDimitry Andric /// 2) Local copy:
20300b57cec5SDimitry Andric /// I0: dst = src (copy)
20310b57cec5SDimitry Andric /// I1:     = dst
20320b57cec5SDimitry Andric /// I2: src = ...
20330b57cec5SDimitry Andric /// I3:     = dst
20340b57cec5SDimitry Andric /// (create pred->succ edges I1->I2, I3->I2)
20350b57cec5SDimitry Andric ///
20360b57cec5SDimitry Andric /// Although the MachineScheduler is currently constrained to single blocks,
20370b57cec5SDimitry Andric /// this algorithm should handle extended blocks. An EBB is a set of
20380b57cec5SDimitry Andric /// contiguously numbered blocks such that the previous block in the EBB is
20390b57cec5SDimitry Andric /// always the single predecessor.
constrainLocalCopy(SUnit * CopySU,ScheduleDAGMILive * DAG)20400b57cec5SDimitry Andric void CopyConstrain::constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG) {
20410b57cec5SDimitry Andric   LiveIntervals *LIS = DAG->getLIS();
20420b57cec5SDimitry Andric   MachineInstr *Copy = CopySU->getInstr();
20430b57cec5SDimitry Andric 
20440b57cec5SDimitry Andric   // Check for pure vreg copies.
20450b57cec5SDimitry Andric   const MachineOperand &SrcOp = Copy->getOperand(1);
20468bcb0991SDimitry Andric   Register SrcReg = SrcOp.getReg();
2047bdd1243dSDimitry Andric   if (!SrcReg.isVirtual() || !SrcOp.readsReg())
20480b57cec5SDimitry Andric     return;
20490b57cec5SDimitry Andric 
20500b57cec5SDimitry Andric   const MachineOperand &DstOp = Copy->getOperand(0);
20518bcb0991SDimitry Andric   Register DstReg = DstOp.getReg();
2052bdd1243dSDimitry Andric   if (!DstReg.isVirtual() || DstOp.isDead())
20530b57cec5SDimitry Andric     return;
20540b57cec5SDimitry Andric 
20550b57cec5SDimitry Andric   // Check if either the dest or source is local. If it's live across a back
20560b57cec5SDimitry Andric   // edge, it's not local. Note that if both vregs are live across the back
20570b57cec5SDimitry Andric   // edge, we cannot successfully contrain the copy without cyclic scheduling.
20580b57cec5SDimitry Andric   // If both the copy's source and dest are local live intervals, then we
20590b57cec5SDimitry Andric   // should treat the dest as the global for the purpose of adding
20600b57cec5SDimitry Andric   // constraints. This adds edges from source's other uses to the copy.
20610b57cec5SDimitry Andric   unsigned LocalReg = SrcReg;
20620b57cec5SDimitry Andric   unsigned GlobalReg = DstReg;
20630b57cec5SDimitry Andric   LiveInterval *LocalLI = &LIS->getInterval(LocalReg);
20640b57cec5SDimitry Andric   if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx)) {
20650b57cec5SDimitry Andric     LocalReg = DstReg;
20660b57cec5SDimitry Andric     GlobalReg = SrcReg;
20670b57cec5SDimitry Andric     LocalLI = &LIS->getInterval(LocalReg);
20680b57cec5SDimitry Andric     if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx))
20690b57cec5SDimitry Andric       return;
20700b57cec5SDimitry Andric   }
20710b57cec5SDimitry Andric   LiveInterval *GlobalLI = &LIS->getInterval(GlobalReg);
20720b57cec5SDimitry Andric 
20730b57cec5SDimitry Andric   // Find the global segment after the start of the local LI.
20740b57cec5SDimitry Andric   LiveInterval::iterator GlobalSegment = GlobalLI->find(LocalLI->beginIndex());
20750b57cec5SDimitry Andric   // If GlobalLI does not overlap LocalLI->start, then a copy directly feeds a
20760b57cec5SDimitry Andric   // local live range. We could create edges from other global uses to the local
20770b57cec5SDimitry Andric   // start, but the coalescer should have already eliminated these cases, so
20780b57cec5SDimitry Andric   // don't bother dealing with it.
20790b57cec5SDimitry Andric   if (GlobalSegment == GlobalLI->end())
20800b57cec5SDimitry Andric     return;
20810b57cec5SDimitry Andric 
20820b57cec5SDimitry Andric   // If GlobalSegment is killed at the LocalLI->start, the call to find()
20830b57cec5SDimitry Andric   // returned the next global segment. But if GlobalSegment overlaps with
20840b57cec5SDimitry Andric   // LocalLI->start, then advance to the next segment. If a hole in GlobalLI
20850b57cec5SDimitry Andric   // exists in LocalLI's vicinity, GlobalSegment will be the end of the hole.
20860b57cec5SDimitry Andric   if (GlobalSegment->contains(LocalLI->beginIndex()))
20870b57cec5SDimitry Andric     ++GlobalSegment;
20880b57cec5SDimitry Andric 
20890b57cec5SDimitry Andric   if (GlobalSegment == GlobalLI->end())
20900b57cec5SDimitry Andric     return;
20910b57cec5SDimitry Andric 
20920b57cec5SDimitry Andric   // Check if GlobalLI contains a hole in the vicinity of LocalLI.
20930b57cec5SDimitry Andric   if (GlobalSegment != GlobalLI->begin()) {
20940b57cec5SDimitry Andric     // Two address defs have no hole.
20950b57cec5SDimitry Andric     if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->end,
20960b57cec5SDimitry Andric                                GlobalSegment->start)) {
20970b57cec5SDimitry Andric       return;
20980b57cec5SDimitry Andric     }
20990b57cec5SDimitry Andric     // If the prior global segment may be defined by the same two-address
21000b57cec5SDimitry Andric     // instruction that also defines LocalLI, then can't make a hole here.
21010b57cec5SDimitry Andric     if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->start,
21020b57cec5SDimitry Andric                                LocalLI->beginIndex())) {
21030b57cec5SDimitry Andric       return;
21040b57cec5SDimitry Andric     }
21050b57cec5SDimitry Andric     // If GlobalLI has a prior segment, it must be live into the EBB. Otherwise
21060b57cec5SDimitry Andric     // it would be a disconnected component in the live range.
21070b57cec5SDimitry Andric     assert(std::prev(GlobalSegment)->start < LocalLI->beginIndex() &&
21080b57cec5SDimitry Andric            "Disconnected LRG within the scheduling region.");
21090b57cec5SDimitry Andric   }
21100b57cec5SDimitry Andric   MachineInstr *GlobalDef = LIS->getInstructionFromIndex(GlobalSegment->start);
21110b57cec5SDimitry Andric   if (!GlobalDef)
21120b57cec5SDimitry Andric     return;
21130b57cec5SDimitry Andric 
21140b57cec5SDimitry Andric   SUnit *GlobalSU = DAG->getSUnit(GlobalDef);
21150b57cec5SDimitry Andric   if (!GlobalSU)
21160b57cec5SDimitry Andric     return;
21170b57cec5SDimitry Andric 
21180b57cec5SDimitry Andric   // GlobalDef is the bottom of the GlobalLI hole. Open the hole by
21190b57cec5SDimitry Andric   // constraining the uses of the last local def to precede GlobalDef.
21200b57cec5SDimitry Andric   SmallVector<SUnit*,8> LocalUses;
21210b57cec5SDimitry Andric   const VNInfo *LastLocalVN = LocalLI->getVNInfoBefore(LocalLI->endIndex());
21220b57cec5SDimitry Andric   MachineInstr *LastLocalDef = LIS->getInstructionFromIndex(LastLocalVN->def);
21230b57cec5SDimitry Andric   SUnit *LastLocalSU = DAG->getSUnit(LastLocalDef);
21240b57cec5SDimitry Andric   for (const SDep &Succ : LastLocalSU->Succs) {
21250b57cec5SDimitry Andric     if (Succ.getKind() != SDep::Data || Succ.getReg() != LocalReg)
21260b57cec5SDimitry Andric       continue;
21270b57cec5SDimitry Andric     if (Succ.getSUnit() == GlobalSU)
21280b57cec5SDimitry Andric       continue;
21290b57cec5SDimitry Andric     if (!DAG->canAddEdge(GlobalSU, Succ.getSUnit()))
21300b57cec5SDimitry Andric       return;
21310b57cec5SDimitry Andric     LocalUses.push_back(Succ.getSUnit());
21320b57cec5SDimitry Andric   }
21330b57cec5SDimitry Andric   // Open the top of the GlobalLI hole by constraining any earlier global uses
21340b57cec5SDimitry Andric   // to precede the start of LocalLI.
21350b57cec5SDimitry Andric   SmallVector<SUnit*,8> GlobalUses;
21360b57cec5SDimitry Andric   MachineInstr *FirstLocalDef =
21370b57cec5SDimitry Andric     LIS->getInstructionFromIndex(LocalLI->beginIndex());
21380b57cec5SDimitry Andric   SUnit *FirstLocalSU = DAG->getSUnit(FirstLocalDef);
21390b57cec5SDimitry Andric   for (const SDep &Pred : GlobalSU->Preds) {
21400b57cec5SDimitry Andric     if (Pred.getKind() != SDep::Anti || Pred.getReg() != GlobalReg)
21410b57cec5SDimitry Andric       continue;
21420b57cec5SDimitry Andric     if (Pred.getSUnit() == FirstLocalSU)
21430b57cec5SDimitry Andric       continue;
21440b57cec5SDimitry Andric     if (!DAG->canAddEdge(FirstLocalSU, Pred.getSUnit()))
21450b57cec5SDimitry Andric       return;
21460b57cec5SDimitry Andric     GlobalUses.push_back(Pred.getSUnit());
21470b57cec5SDimitry Andric   }
21480b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Constraining copy SU(" << CopySU->NodeNum << ")\n");
21490b57cec5SDimitry Andric   // Add the weak edges.
2150fe6060f1SDimitry Andric   for (SUnit *LU : LocalUses) {
2151fe6060f1SDimitry Andric     LLVM_DEBUG(dbgs() << "  Local use SU(" << LU->NodeNum << ") -> SU("
21520b57cec5SDimitry Andric                       << GlobalSU->NodeNum << ")\n");
2153fe6060f1SDimitry Andric     DAG->addEdge(GlobalSU, SDep(LU, SDep::Weak));
21540b57cec5SDimitry Andric   }
2155fe6060f1SDimitry Andric   for (SUnit *GU : GlobalUses) {
2156fe6060f1SDimitry Andric     LLVM_DEBUG(dbgs() << "  Global use SU(" << GU->NodeNum << ") -> SU("
21570b57cec5SDimitry Andric                       << FirstLocalSU->NodeNum << ")\n");
2158fe6060f1SDimitry Andric     DAG->addEdge(FirstLocalSU, SDep(GU, SDep::Weak));
21590b57cec5SDimitry Andric   }
21600b57cec5SDimitry Andric }
21610b57cec5SDimitry Andric 
21620b57cec5SDimitry Andric /// Callback from DAG postProcessing to create weak edges to encourage
21630b57cec5SDimitry Andric /// copy elimination.
apply(ScheduleDAGInstrs * DAGInstrs)21640b57cec5SDimitry Andric void CopyConstrain::apply(ScheduleDAGInstrs *DAGInstrs) {
21650b57cec5SDimitry Andric   ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs);
21660b57cec5SDimitry Andric   assert(DAG->hasVRegLiveness() && "Expect VRegs with LiveIntervals");
21670b57cec5SDimitry Andric 
21680b57cec5SDimitry Andric   MachineBasicBlock::iterator FirstPos = nextIfDebug(DAG->begin(), DAG->end());
21690b57cec5SDimitry Andric   if (FirstPos == DAG->end())
21700b57cec5SDimitry Andric     return;
21710b57cec5SDimitry Andric   RegionBeginIdx = DAG->getLIS()->getInstructionIndex(*FirstPos);
21720b57cec5SDimitry Andric   RegionEndIdx = DAG->getLIS()->getInstructionIndex(
21730b57cec5SDimitry Andric       *priorNonDebug(DAG->end(), DAG->begin()));
21740b57cec5SDimitry Andric 
21750b57cec5SDimitry Andric   for (SUnit &SU : DAG->SUnits) {
21760b57cec5SDimitry Andric     if (!SU.getInstr()->isCopy())
21770b57cec5SDimitry Andric       continue;
21780b57cec5SDimitry Andric 
21790b57cec5SDimitry Andric     constrainLocalCopy(&SU, static_cast<ScheduleDAGMILive*>(DAG));
21800b57cec5SDimitry Andric   }
21810b57cec5SDimitry Andric }
21820b57cec5SDimitry Andric 
21830b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
21840b57cec5SDimitry Andric // MachineSchedStrategy helpers used by GenericScheduler, GenericPostScheduler
21850b57cec5SDimitry Andric // and possibly other custom schedulers.
21860b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
21870b57cec5SDimitry Andric 
21880b57cec5SDimitry Andric static const unsigned InvalidCycle = ~0U;
21890b57cec5SDimitry Andric 
~SchedBoundary()21900b57cec5SDimitry Andric SchedBoundary::~SchedBoundary() { delete HazardRec; }
21910b57cec5SDimitry Andric 
21920b57cec5SDimitry Andric /// Given a Count of resource usage and a Latency value, return true if a
21930b57cec5SDimitry Andric /// SchedBoundary becomes resource limited.
21940b57cec5SDimitry Andric /// If we are checking after scheduling a node, we should return true when
21950b57cec5SDimitry Andric /// we just reach the resource limit.
checkResourceLimit(unsigned LFactor,unsigned Count,unsigned Latency,bool AfterSchedNode)21960b57cec5SDimitry Andric static bool checkResourceLimit(unsigned LFactor, unsigned Count,
21970b57cec5SDimitry Andric                                unsigned Latency, bool AfterSchedNode) {
21980b57cec5SDimitry Andric   int ResCntFactor = (int)(Count - (Latency * LFactor));
21990b57cec5SDimitry Andric   if (AfterSchedNode)
22000b57cec5SDimitry Andric     return ResCntFactor >= (int)LFactor;
22010b57cec5SDimitry Andric   else
22020b57cec5SDimitry Andric     return ResCntFactor > (int)LFactor;
22030b57cec5SDimitry Andric }
22040b57cec5SDimitry Andric 
reset()22050b57cec5SDimitry Andric void SchedBoundary::reset() {
22060b57cec5SDimitry Andric   // A new HazardRec is created for each DAG and owned by SchedBoundary.
22070b57cec5SDimitry Andric   // Destroying and reconstructing it is very expensive though. So keep
22080b57cec5SDimitry Andric   // invalid, placeholder HazardRecs.
22090b57cec5SDimitry Andric   if (HazardRec && HazardRec->isEnabled()) {
22100b57cec5SDimitry Andric     delete HazardRec;
22110b57cec5SDimitry Andric     HazardRec = nullptr;
22120b57cec5SDimitry Andric   }
22130b57cec5SDimitry Andric   Available.clear();
22140b57cec5SDimitry Andric   Pending.clear();
22150b57cec5SDimitry Andric   CheckPending = false;
22160b57cec5SDimitry Andric   CurrCycle = 0;
22170b57cec5SDimitry Andric   CurrMOps = 0;
22180b57cec5SDimitry Andric   MinReadyCycle = std::numeric_limits<unsigned>::max();
22190b57cec5SDimitry Andric   ExpectedLatency = 0;
22200b57cec5SDimitry Andric   DependentLatency = 0;
22210b57cec5SDimitry Andric   RetiredMOps = 0;
22220b57cec5SDimitry Andric   MaxExecutedResCount = 0;
22230b57cec5SDimitry Andric   ZoneCritResIdx = 0;
22240b57cec5SDimitry Andric   IsResourceLimited = false;
22250b57cec5SDimitry Andric   ReservedCycles.clear();
2226fe013be4SDimitry Andric   ReservedResourceSegments.clear();
22270b57cec5SDimitry Andric   ReservedCyclesIndex.clear();
2228fe6060f1SDimitry Andric   ResourceGroupSubUnitMasks.clear();
222981ad6265SDimitry Andric #if LLVM_ENABLE_ABI_BREAKING_CHECKS
22300b57cec5SDimitry Andric   // Track the maximum number of stall cycles that could arise either from the
22310b57cec5SDimitry Andric   // latency of a DAG edge or the number of cycles that a processor resource is
22320b57cec5SDimitry Andric   // reserved (SchedBoundary::ReservedCycles).
22330b57cec5SDimitry Andric   MaxObservedStall = 0;
22340b57cec5SDimitry Andric #endif
22350b57cec5SDimitry Andric   // Reserve a zero-count for invalid CritResIdx.
22360b57cec5SDimitry Andric   ExecutedResCounts.resize(1);
22370b57cec5SDimitry Andric   assert(!ExecutedResCounts[0] && "nonzero count for bad resource");
22380b57cec5SDimitry Andric }
22390b57cec5SDimitry Andric 
22400b57cec5SDimitry Andric void SchedRemainder::
init(ScheduleDAGMI * DAG,const TargetSchedModel * SchedModel)22410b57cec5SDimitry Andric init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
22420b57cec5SDimitry Andric   reset();
22430b57cec5SDimitry Andric   if (!SchedModel->hasInstrSchedModel())
22440b57cec5SDimitry Andric     return;
22450b57cec5SDimitry Andric   RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
22460b57cec5SDimitry Andric   for (SUnit &SU : DAG->SUnits) {
22470b57cec5SDimitry Andric     const MCSchedClassDesc *SC = DAG->getSchedClass(&SU);
22480b57cec5SDimitry Andric     RemIssueCount += SchedModel->getNumMicroOps(SU.getInstr(), SC)
22490b57cec5SDimitry Andric       * SchedModel->getMicroOpFactor();
22500b57cec5SDimitry Andric     for (TargetSchedModel::ProcResIter
22510b57cec5SDimitry Andric            PI = SchedModel->getWriteProcResBegin(SC),
22520b57cec5SDimitry Andric            PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
22530b57cec5SDimitry Andric       unsigned PIdx = PI->ProcResourceIdx;
22540b57cec5SDimitry Andric       unsigned Factor = SchedModel->getResourceFactor(PIdx);
2255c9157d92SDimitry Andric       assert(PI->ReleaseAtCycle >= PI->AcquireAtCycle);
2256c9157d92SDimitry Andric       RemainingCounts[PIdx] +=
2257c9157d92SDimitry Andric           (Factor * (PI->ReleaseAtCycle - PI->AcquireAtCycle));
22580b57cec5SDimitry Andric     }
22590b57cec5SDimitry Andric   }
22600b57cec5SDimitry Andric }
22610b57cec5SDimitry Andric 
22620b57cec5SDimitry Andric void SchedBoundary::
init(ScheduleDAGMI * dag,const TargetSchedModel * smodel,SchedRemainder * rem)22630b57cec5SDimitry Andric init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
22640b57cec5SDimitry Andric   reset();
22650b57cec5SDimitry Andric   DAG = dag;
22660b57cec5SDimitry Andric   SchedModel = smodel;
22670b57cec5SDimitry Andric   Rem = rem;
22680b57cec5SDimitry Andric   if (SchedModel->hasInstrSchedModel()) {
22690b57cec5SDimitry Andric     unsigned ResourceCount = SchedModel->getNumProcResourceKinds();
22700b57cec5SDimitry Andric     ReservedCyclesIndex.resize(ResourceCount);
22710b57cec5SDimitry Andric     ExecutedResCounts.resize(ResourceCount);
2272fe6060f1SDimitry Andric     ResourceGroupSubUnitMasks.resize(ResourceCount, APInt(ResourceCount, 0));
22730b57cec5SDimitry Andric     unsigned NumUnits = 0;
22740b57cec5SDimitry Andric 
22750b57cec5SDimitry Andric     for (unsigned i = 0; i < ResourceCount; ++i) {
22760b57cec5SDimitry Andric       ReservedCyclesIndex[i] = NumUnits;
22770b57cec5SDimitry Andric       NumUnits += SchedModel->getProcResource(i)->NumUnits;
2278fe6060f1SDimitry Andric       if (isUnbufferedGroup(i)) {
2279fe6060f1SDimitry Andric         auto SubUnits = SchedModel->getProcResource(i)->SubUnitsIdxBegin;
2280fe6060f1SDimitry Andric         for (unsigned U = 0, UE = SchedModel->getProcResource(i)->NumUnits;
2281fe6060f1SDimitry Andric              U != UE; ++U)
2282fe6060f1SDimitry Andric           ResourceGroupSubUnitMasks[i].setBit(SubUnits[U]);
2283fe6060f1SDimitry Andric       }
22840b57cec5SDimitry Andric     }
22850b57cec5SDimitry Andric 
22860b57cec5SDimitry Andric     ReservedCycles.resize(NumUnits, InvalidCycle);
22870b57cec5SDimitry Andric   }
22880b57cec5SDimitry Andric }
22890b57cec5SDimitry Andric 
22900b57cec5SDimitry Andric /// Compute the stall cycles based on this SUnit's ready time. Heuristics treat
22910b57cec5SDimitry Andric /// these "soft stalls" differently than the hard stall cycles based on CPU
22920b57cec5SDimitry Andric /// resources and computed by checkHazard(). A fully in-order model
22930b57cec5SDimitry Andric /// (MicroOpBufferSize==0) will not make use of this since instructions are not
22940b57cec5SDimitry Andric /// available for scheduling until they are ready. However, a weaker in-order
22950b57cec5SDimitry Andric /// model may use this for heuristics. For example, if a processor has in-order
22960b57cec5SDimitry Andric /// behavior when reading certain resources, this may come into play.
getLatencyStallCycles(SUnit * SU)22970b57cec5SDimitry Andric unsigned SchedBoundary::getLatencyStallCycles(SUnit *SU) {
22980b57cec5SDimitry Andric   if (!SU->isUnbuffered)
22990b57cec5SDimitry Andric     return 0;
23000b57cec5SDimitry Andric 
23010b57cec5SDimitry Andric   unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
23020b57cec5SDimitry Andric   if (ReadyCycle > CurrCycle)
23030b57cec5SDimitry Andric     return ReadyCycle - CurrCycle;
23040b57cec5SDimitry Andric   return 0;
23050b57cec5SDimitry Andric }
23060b57cec5SDimitry Andric 
23070b57cec5SDimitry Andric /// Compute the next cycle at which the given processor resource unit
23080b57cec5SDimitry Andric /// can be scheduled.
getNextResourceCycleByInstance(unsigned InstanceIdx,unsigned ReleaseAtCycle,unsigned AcquireAtCycle)23090b57cec5SDimitry Andric unsigned SchedBoundary::getNextResourceCycleByInstance(unsigned InstanceIdx,
2310c9157d92SDimitry Andric                                                        unsigned ReleaseAtCycle,
2311c9157d92SDimitry Andric                                                        unsigned AcquireAtCycle) {
2312fe013be4SDimitry Andric   if (SchedModel && SchedModel->enableIntervals()) {
2313fe013be4SDimitry Andric     if (isTop())
2314fe013be4SDimitry Andric       return ReservedResourceSegments[InstanceIdx].getFirstAvailableAtFromTop(
2315c9157d92SDimitry Andric           CurrCycle, AcquireAtCycle, ReleaseAtCycle);
2316fe013be4SDimitry Andric 
2317fe013be4SDimitry Andric     return ReservedResourceSegments[InstanceIdx].getFirstAvailableAtFromBottom(
2318c9157d92SDimitry Andric         CurrCycle, AcquireAtCycle, ReleaseAtCycle);
2319fe013be4SDimitry Andric   }
2320fe013be4SDimitry Andric 
23210b57cec5SDimitry Andric   unsigned NextUnreserved = ReservedCycles[InstanceIdx];
23220b57cec5SDimitry Andric   // If this resource has never been used, always return cycle zero.
23230b57cec5SDimitry Andric   if (NextUnreserved == InvalidCycle)
2324fe013be4SDimitry Andric     return CurrCycle;
23250b57cec5SDimitry Andric   // For bottom-up scheduling add the cycles needed for the current operation.
23260b57cec5SDimitry Andric   if (!isTop())
2327c9157d92SDimitry Andric     NextUnreserved = std::max(CurrCycle, NextUnreserved + ReleaseAtCycle);
23280b57cec5SDimitry Andric   return NextUnreserved;
23290b57cec5SDimitry Andric }
23300b57cec5SDimitry Andric 
23310b57cec5SDimitry Andric /// Compute the next cycle at which the given processor resource can be
23320b57cec5SDimitry Andric /// scheduled.  Returns the next cycle and the index of the processor resource
23330b57cec5SDimitry Andric /// instance in the reserved cycles vector.
23340b57cec5SDimitry Andric std::pair<unsigned, unsigned>
getNextResourceCycle(const MCSchedClassDesc * SC,unsigned PIdx,unsigned ReleaseAtCycle,unsigned AcquireAtCycle)2335fe6060f1SDimitry Andric SchedBoundary::getNextResourceCycle(const MCSchedClassDesc *SC, unsigned PIdx,
2336c9157d92SDimitry Andric                                     unsigned ReleaseAtCycle,
2337c9157d92SDimitry Andric                                     unsigned AcquireAtCycle) {
2338fe013be4SDimitry Andric   if (MischedDetailResourceBooking) {
2339fe013be4SDimitry Andric     LLVM_DEBUG(dbgs() << "  Resource booking (@" << CurrCycle << "c): \n");
2340fe013be4SDimitry Andric     LLVM_DEBUG(dumpReservedCycles());
2341fe013be4SDimitry Andric     LLVM_DEBUG(dbgs() << "  getNextResourceCycle (@" << CurrCycle << "c): \n");
2342fe013be4SDimitry Andric   }
23430b57cec5SDimitry Andric   unsigned MinNextUnreserved = InvalidCycle;
23440b57cec5SDimitry Andric   unsigned InstanceIdx = 0;
23450b57cec5SDimitry Andric   unsigned StartIndex = ReservedCyclesIndex[PIdx];
23460b57cec5SDimitry Andric   unsigned NumberOfInstances = SchedModel->getProcResource(PIdx)->NumUnits;
23470b57cec5SDimitry Andric   assert(NumberOfInstances > 0 &&
23480b57cec5SDimitry Andric          "Cannot have zero instances of a ProcResource");
23490b57cec5SDimitry Andric 
2350fe6060f1SDimitry Andric   if (isUnbufferedGroup(PIdx)) {
2351c9157d92SDimitry Andric     // If any subunits are used by the instruction, report that the
2352c9157d92SDimitry Andric     // subunits of the resource group are available at the first cycle
2353c9157d92SDimitry Andric     // in which the unit is available, effectively removing the group
2354c9157d92SDimitry Andric     // record from hazarding and basing the hazarding decisions on the
2355c9157d92SDimitry Andric     // subunit records. Otherwise, choose the first available instance
2356c9157d92SDimitry Andric     // from among the subunits.  Specifications which assign cycles to
2357c9157d92SDimitry Andric     // both the subunits and the group or which use an unbuffered
2358c9157d92SDimitry Andric     // group with buffered subunits will appear to schedule
2359c9157d92SDimitry Andric     // strangely. In the first case, the additional cycles for the
2360c9157d92SDimitry Andric     // group will be ignored.  In the second, the group will be
2361c9157d92SDimitry Andric     // ignored entirely.
2362fe6060f1SDimitry Andric     for (const MCWriteProcResEntry &PE :
2363fe6060f1SDimitry Andric          make_range(SchedModel->getWriteProcResBegin(SC),
2364fe6060f1SDimitry Andric                     SchedModel->getWriteProcResEnd(SC)))
2365fe6060f1SDimitry Andric       if (ResourceGroupSubUnitMasks[PIdx][PE.ProcResourceIdx])
2366c9157d92SDimitry Andric         return std::make_pair(getNextResourceCycleByInstance(
2367c9157d92SDimitry Andric                                   StartIndex, ReleaseAtCycle, AcquireAtCycle),
2368c9157d92SDimitry Andric                               StartIndex);
2369fe6060f1SDimitry Andric 
2370fe6060f1SDimitry Andric     auto SubUnits = SchedModel->getProcResource(PIdx)->SubUnitsIdxBegin;
2371fe6060f1SDimitry Andric     for (unsigned I = 0, End = NumberOfInstances; I < End; ++I) {
2372fe6060f1SDimitry Andric       unsigned NextUnreserved, NextInstanceIdx;
2373fe6060f1SDimitry Andric       std::tie(NextUnreserved, NextInstanceIdx) =
2374c9157d92SDimitry Andric           getNextResourceCycle(SC, SubUnits[I], ReleaseAtCycle, AcquireAtCycle);
2375fe6060f1SDimitry Andric       if (MinNextUnreserved > NextUnreserved) {
2376fe6060f1SDimitry Andric         InstanceIdx = NextInstanceIdx;
2377fe6060f1SDimitry Andric         MinNextUnreserved = NextUnreserved;
2378fe6060f1SDimitry Andric       }
2379fe6060f1SDimitry Andric     }
2380fe6060f1SDimitry Andric     return std::make_pair(MinNextUnreserved, InstanceIdx);
2381fe6060f1SDimitry Andric   }
2382fe6060f1SDimitry Andric 
23830b57cec5SDimitry Andric   for (unsigned I = StartIndex, End = StartIndex + NumberOfInstances; I < End;
23840b57cec5SDimitry Andric        ++I) {
2385fe013be4SDimitry Andric     unsigned NextUnreserved =
2386c9157d92SDimitry Andric         getNextResourceCycleByInstance(I, ReleaseAtCycle, AcquireAtCycle);
2387fe013be4SDimitry Andric     if (MischedDetailResourceBooking)
2388fe013be4SDimitry Andric       LLVM_DEBUG(dbgs() << "    Instance " << I - StartIndex << " available @"
2389fe013be4SDimitry Andric                         << NextUnreserved << "c\n");
23900b57cec5SDimitry Andric     if (MinNextUnreserved > NextUnreserved) {
23910b57cec5SDimitry Andric       InstanceIdx = I;
23920b57cec5SDimitry Andric       MinNextUnreserved = NextUnreserved;
23930b57cec5SDimitry Andric     }
23940b57cec5SDimitry Andric   }
2395fe013be4SDimitry Andric   if (MischedDetailResourceBooking)
2396fe013be4SDimitry Andric     LLVM_DEBUG(dbgs() << "    selecting " << SchedModel->getResourceName(PIdx)
2397fe013be4SDimitry Andric                       << "[" << InstanceIdx - StartIndex << "]"
2398fe013be4SDimitry Andric                       << " available @" << MinNextUnreserved << "c"
2399fe013be4SDimitry Andric                       << "\n");
24000b57cec5SDimitry Andric   return std::make_pair(MinNextUnreserved, InstanceIdx);
24010b57cec5SDimitry Andric }
24020b57cec5SDimitry Andric 
24030b57cec5SDimitry Andric /// Does this SU have a hazard within the current instruction group.
24040b57cec5SDimitry Andric ///
24050b57cec5SDimitry Andric /// The scheduler supports two modes of hazard recognition. The first is the
24060b57cec5SDimitry Andric /// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
24070b57cec5SDimitry Andric /// supports highly complicated in-order reservation tables
24080b57cec5SDimitry Andric /// (ScoreboardHazardRecognizer) and arbitrary target-specific logic.
24090b57cec5SDimitry Andric ///
24100b57cec5SDimitry Andric /// The second is a streamlined mechanism that checks for hazards based on
24110b57cec5SDimitry Andric /// simple counters that the scheduler itself maintains. It explicitly checks
24120b57cec5SDimitry Andric /// for instruction dispatch limitations, including the number of micro-ops that
24130b57cec5SDimitry Andric /// can dispatch per cycle.
24140b57cec5SDimitry Andric ///
24150b57cec5SDimitry Andric /// TODO: Also check whether the SU must start a new group.
checkHazard(SUnit * SU)24160b57cec5SDimitry Andric bool SchedBoundary::checkHazard(SUnit *SU) {
24170b57cec5SDimitry Andric   if (HazardRec->isEnabled()
24180b57cec5SDimitry Andric       && HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard) {
24190b57cec5SDimitry Andric     return true;
24200b57cec5SDimitry Andric   }
24210b57cec5SDimitry Andric 
24220b57cec5SDimitry Andric   unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
24230b57cec5SDimitry Andric   if ((CurrMOps > 0) && (CurrMOps + uops > SchedModel->getIssueWidth())) {
24240b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "  SU(" << SU->NodeNum << ") uops="
24250b57cec5SDimitry Andric                       << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
24260b57cec5SDimitry Andric     return true;
24270b57cec5SDimitry Andric   }
24280b57cec5SDimitry Andric 
24290b57cec5SDimitry Andric   if (CurrMOps > 0 &&
24300b57cec5SDimitry Andric       ((isTop() && SchedModel->mustBeginGroup(SU->getInstr())) ||
24310b57cec5SDimitry Andric        (!isTop() && SchedModel->mustEndGroup(SU->getInstr())))) {
24320b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "  hazard: SU(" << SU->NodeNum << ") must "
24330b57cec5SDimitry Andric                       << (isTop() ? "begin" : "end") << " group\n");
24340b57cec5SDimitry Andric     return true;
24350b57cec5SDimitry Andric   }
24360b57cec5SDimitry Andric 
24370b57cec5SDimitry Andric   if (SchedModel->hasInstrSchedModel() && SU->hasReservedResource) {
24380b57cec5SDimitry Andric     const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
24390b57cec5SDimitry Andric     for (const MCWriteProcResEntry &PE :
24400b57cec5SDimitry Andric           make_range(SchedModel->getWriteProcResBegin(SC),
24410b57cec5SDimitry Andric                      SchedModel->getWriteProcResEnd(SC))) {
24420b57cec5SDimitry Andric       unsigned ResIdx = PE.ProcResourceIdx;
2443c9157d92SDimitry Andric       unsigned ReleaseAtCycle = PE.ReleaseAtCycle;
2444c9157d92SDimitry Andric       unsigned AcquireAtCycle = PE.AcquireAtCycle;
24450b57cec5SDimitry Andric       unsigned NRCycle, InstanceIdx;
2446fe013be4SDimitry Andric       std::tie(NRCycle, InstanceIdx) =
2447c9157d92SDimitry Andric           getNextResourceCycle(SC, ResIdx, ReleaseAtCycle, AcquireAtCycle);
24480b57cec5SDimitry Andric       if (NRCycle > CurrCycle) {
244981ad6265SDimitry Andric #if LLVM_ENABLE_ABI_BREAKING_CHECKS
2450c9157d92SDimitry Andric         MaxObservedStall = std::max(ReleaseAtCycle, MaxObservedStall);
24510b57cec5SDimitry Andric #endif
24520b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "  SU(" << SU->NodeNum << ") "
24530b57cec5SDimitry Andric                           << SchedModel->getResourceName(ResIdx)
24540b57cec5SDimitry Andric                           << '[' << InstanceIdx - ReservedCyclesIndex[ResIdx]  << ']'
24550b57cec5SDimitry Andric                           << "=" << NRCycle << "c\n");
24560b57cec5SDimitry Andric         return true;
24570b57cec5SDimitry Andric       }
24580b57cec5SDimitry Andric     }
24590b57cec5SDimitry Andric   }
24600b57cec5SDimitry Andric   return false;
24610b57cec5SDimitry Andric }
24620b57cec5SDimitry Andric 
24630b57cec5SDimitry Andric // Find the unscheduled node in ReadySUs with the highest latency.
24640b57cec5SDimitry Andric unsigned SchedBoundary::
findMaxLatency(ArrayRef<SUnit * > ReadySUs)24650b57cec5SDimitry Andric findMaxLatency(ArrayRef<SUnit*> ReadySUs) {
24660b57cec5SDimitry Andric   SUnit *LateSU = nullptr;
24670b57cec5SDimitry Andric   unsigned RemLatency = 0;
24680b57cec5SDimitry Andric   for (SUnit *SU : ReadySUs) {
24690b57cec5SDimitry Andric     unsigned L = getUnscheduledLatency(SU);
24700b57cec5SDimitry Andric     if (L > RemLatency) {
24710b57cec5SDimitry Andric       RemLatency = L;
24720b57cec5SDimitry Andric       LateSU = SU;
24730b57cec5SDimitry Andric     }
24740b57cec5SDimitry Andric   }
24750b57cec5SDimitry Andric   if (LateSU) {
24760b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << Available.getName() << " RemLatency SU("
24770b57cec5SDimitry Andric                       << LateSU->NodeNum << ") " << RemLatency << "c\n");
24780b57cec5SDimitry Andric   }
24790b57cec5SDimitry Andric   return RemLatency;
24800b57cec5SDimitry Andric }
24810b57cec5SDimitry Andric 
24820b57cec5SDimitry Andric // Count resources in this zone and the remaining unscheduled
24830b57cec5SDimitry Andric // instruction. Return the max count, scaled. Set OtherCritIdx to the critical
24840b57cec5SDimitry Andric // resource index, or zero if the zone is issue limited.
24850b57cec5SDimitry Andric unsigned SchedBoundary::
getOtherResourceCount(unsigned & OtherCritIdx)24860b57cec5SDimitry Andric getOtherResourceCount(unsigned &OtherCritIdx) {
24870b57cec5SDimitry Andric   OtherCritIdx = 0;
24880b57cec5SDimitry Andric   if (!SchedModel->hasInstrSchedModel())
24890b57cec5SDimitry Andric     return 0;
24900b57cec5SDimitry Andric 
24910b57cec5SDimitry Andric   unsigned OtherCritCount = Rem->RemIssueCount
24920b57cec5SDimitry Andric     + (RetiredMOps * SchedModel->getMicroOpFactor());
24930b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "  " << Available.getName() << " + Remain MOps: "
24940b57cec5SDimitry Andric                     << OtherCritCount / SchedModel->getMicroOpFactor() << '\n');
24950b57cec5SDimitry Andric   for (unsigned PIdx = 1, PEnd = SchedModel->getNumProcResourceKinds();
24960b57cec5SDimitry Andric        PIdx != PEnd; ++PIdx) {
24970b57cec5SDimitry Andric     unsigned OtherCount = getResourceCount(PIdx) + Rem->RemainingCounts[PIdx];
24980b57cec5SDimitry Andric     if (OtherCount > OtherCritCount) {
24990b57cec5SDimitry Andric       OtherCritCount = OtherCount;
25000b57cec5SDimitry Andric       OtherCritIdx = PIdx;
25010b57cec5SDimitry Andric     }
25020b57cec5SDimitry Andric   }
25030b57cec5SDimitry Andric   if (OtherCritIdx) {
25040b57cec5SDimitry Andric     LLVM_DEBUG(
25050b57cec5SDimitry Andric         dbgs() << "  " << Available.getName() << " + Remain CritRes: "
25060b57cec5SDimitry Andric                << OtherCritCount / SchedModel->getResourceFactor(OtherCritIdx)
25070b57cec5SDimitry Andric                << " " << SchedModel->getResourceName(OtherCritIdx) << "\n");
25080b57cec5SDimitry Andric   }
25090b57cec5SDimitry Andric   return OtherCritCount;
25100b57cec5SDimitry Andric }
25110b57cec5SDimitry Andric 
releaseNode(SUnit * SU,unsigned ReadyCycle,bool InPQueue,unsigned Idx)2512480093f4SDimitry Andric void SchedBoundary::releaseNode(SUnit *SU, unsigned ReadyCycle, bool InPQueue,
2513480093f4SDimitry Andric                                 unsigned Idx) {
25140b57cec5SDimitry Andric   assert(SU->getInstr() && "Scheduled SUnit must have instr");
25150b57cec5SDimitry Andric 
251681ad6265SDimitry Andric #if LLVM_ENABLE_ABI_BREAKING_CHECKS
25170b57cec5SDimitry Andric   // ReadyCycle was been bumped up to the CurrCycle when this node was
25180b57cec5SDimitry Andric   // scheduled, but CurrCycle may have been eagerly advanced immediately after
25190b57cec5SDimitry Andric   // scheduling, so may now be greater than ReadyCycle.
25200b57cec5SDimitry Andric   if (ReadyCycle > CurrCycle)
25210b57cec5SDimitry Andric     MaxObservedStall = std::max(ReadyCycle - CurrCycle, MaxObservedStall);
25220b57cec5SDimitry Andric #endif
25230b57cec5SDimitry Andric 
25240b57cec5SDimitry Andric   if (ReadyCycle < MinReadyCycle)
25250b57cec5SDimitry Andric     MinReadyCycle = ReadyCycle;
25260b57cec5SDimitry Andric 
25270b57cec5SDimitry Andric   // Check for interlocks first. For the purpose of other heuristics, an
25280b57cec5SDimitry Andric   // instruction that cannot issue appears as if it's not in the ReadyQueue.
25290b57cec5SDimitry Andric   bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
2530480093f4SDimitry Andric   bool HazardDetected = (!IsBuffered && ReadyCycle > CurrCycle) ||
2531480093f4SDimitry Andric                         checkHazard(SU) || (Available.size() >= ReadyListLimit);
2532480093f4SDimitry Andric 
2533480093f4SDimitry Andric   if (!HazardDetected) {
25340b57cec5SDimitry Andric     Available.push(SU);
2535480093f4SDimitry Andric 
2536480093f4SDimitry Andric     if (InPQueue)
2537480093f4SDimitry Andric       Pending.remove(Pending.begin() + Idx);
2538480093f4SDimitry Andric     return;
2539480093f4SDimitry Andric   }
2540480093f4SDimitry Andric 
2541480093f4SDimitry Andric   if (!InPQueue)
2542480093f4SDimitry Andric     Pending.push(SU);
25430b57cec5SDimitry Andric }
25440b57cec5SDimitry Andric 
25450b57cec5SDimitry Andric /// Move the boundary of scheduled code by one cycle.
bumpCycle(unsigned NextCycle)25460b57cec5SDimitry Andric void SchedBoundary::bumpCycle(unsigned NextCycle) {
25470b57cec5SDimitry Andric   if (SchedModel->getMicroOpBufferSize() == 0) {
25480b57cec5SDimitry Andric     assert(MinReadyCycle < std::numeric_limits<unsigned>::max() &&
25490b57cec5SDimitry Andric            "MinReadyCycle uninitialized");
25500b57cec5SDimitry Andric     if (MinReadyCycle > NextCycle)
25510b57cec5SDimitry Andric       NextCycle = MinReadyCycle;
25520b57cec5SDimitry Andric   }
25530b57cec5SDimitry Andric   // Update the current micro-ops, which will issue in the next cycle.
25540b57cec5SDimitry Andric   unsigned DecMOps = SchedModel->getIssueWidth() * (NextCycle - CurrCycle);
25550b57cec5SDimitry Andric   CurrMOps = (CurrMOps <= DecMOps) ? 0 : CurrMOps - DecMOps;
25560b57cec5SDimitry Andric 
25570b57cec5SDimitry Andric   // Decrement DependentLatency based on the next cycle.
25580b57cec5SDimitry Andric   if ((NextCycle - CurrCycle) > DependentLatency)
25590b57cec5SDimitry Andric     DependentLatency = 0;
25600b57cec5SDimitry Andric   else
25610b57cec5SDimitry Andric     DependentLatency -= (NextCycle - CurrCycle);
25620b57cec5SDimitry Andric 
25630b57cec5SDimitry Andric   if (!HazardRec->isEnabled()) {
25640b57cec5SDimitry Andric     // Bypass HazardRec virtual calls.
25650b57cec5SDimitry Andric     CurrCycle = NextCycle;
25660b57cec5SDimitry Andric   } else {
25670b57cec5SDimitry Andric     // Bypass getHazardType calls in case of long latency.
25680b57cec5SDimitry Andric     for (; CurrCycle != NextCycle; ++CurrCycle) {
25690b57cec5SDimitry Andric       if (isTop())
25700b57cec5SDimitry Andric         HazardRec->AdvanceCycle();
25710b57cec5SDimitry Andric       else
25720b57cec5SDimitry Andric         HazardRec->RecedeCycle();
25730b57cec5SDimitry Andric     }
25740b57cec5SDimitry Andric   }
25750b57cec5SDimitry Andric   CheckPending = true;
25760b57cec5SDimitry Andric   IsResourceLimited =
25770b57cec5SDimitry Andric       checkResourceLimit(SchedModel->getLatencyFactor(), getCriticalCount(),
25780b57cec5SDimitry Andric                          getScheduledLatency(), true);
25790b57cec5SDimitry Andric 
25800b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Cycle: " << CurrCycle << ' ' << Available.getName()
25810b57cec5SDimitry Andric                     << '\n');
25820b57cec5SDimitry Andric }
25830b57cec5SDimitry Andric 
incExecutedResources(unsigned PIdx,unsigned Count)25840b57cec5SDimitry Andric void SchedBoundary::incExecutedResources(unsigned PIdx, unsigned Count) {
25850b57cec5SDimitry Andric   ExecutedResCounts[PIdx] += Count;
25860b57cec5SDimitry Andric   if (ExecutedResCounts[PIdx] > MaxExecutedResCount)
25870b57cec5SDimitry Andric     MaxExecutedResCount = ExecutedResCounts[PIdx];
25880b57cec5SDimitry Andric }
25890b57cec5SDimitry Andric 
25900b57cec5SDimitry Andric /// Add the given processor resource to this scheduled zone.
25910b57cec5SDimitry Andric ///
2592c9157d92SDimitry Andric /// \param ReleaseAtCycle indicates the number of consecutive (non-pipelined)
2593c9157d92SDimitry Andric /// cycles during which this resource is released.
2594c9157d92SDimitry Andric ///
2595c9157d92SDimitry Andric /// \param AcquireAtCycle indicates the number of consecutive (non-pipelined)
2596c9157d92SDimitry Andric /// cycles at which the resource is aquired after issue (assuming no stalls).
25970b57cec5SDimitry Andric ///
25980b57cec5SDimitry Andric /// \return the next cycle at which the instruction may execute without
25990b57cec5SDimitry Andric /// oversubscribing resources.
countResource(const MCSchedClassDesc * SC,unsigned PIdx,unsigned ReleaseAtCycle,unsigned NextCycle,unsigned AcquireAtCycle)2600fe6060f1SDimitry Andric unsigned SchedBoundary::countResource(const MCSchedClassDesc *SC, unsigned PIdx,
2601c9157d92SDimitry Andric                                       unsigned ReleaseAtCycle,
2602c9157d92SDimitry Andric                                       unsigned NextCycle,
2603c9157d92SDimitry Andric                                       unsigned AcquireAtCycle) {
26040b57cec5SDimitry Andric   unsigned Factor = SchedModel->getResourceFactor(PIdx);
2605c9157d92SDimitry Andric   unsigned Count = Factor * (ReleaseAtCycle- AcquireAtCycle);
26060b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "  " << SchedModel->getResourceName(PIdx) << " +"
2607c9157d92SDimitry Andric                     << ReleaseAtCycle << "x" << Factor << "u\n");
26080b57cec5SDimitry Andric 
26090b57cec5SDimitry Andric   // Update Executed resources counts.
26100b57cec5SDimitry Andric   incExecutedResources(PIdx, Count);
26110b57cec5SDimitry Andric   assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
26120b57cec5SDimitry Andric   Rem->RemainingCounts[PIdx] -= Count;
26130b57cec5SDimitry Andric 
26140b57cec5SDimitry Andric   // Check if this resource exceeds the current critical resource. If so, it
26150b57cec5SDimitry Andric   // becomes the critical resource.
26160b57cec5SDimitry Andric   if (ZoneCritResIdx != PIdx && (getResourceCount(PIdx) > getCriticalCount())) {
26170b57cec5SDimitry Andric     ZoneCritResIdx = PIdx;
26180b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "  *** Critical resource "
26190b57cec5SDimitry Andric                       << SchedModel->getResourceName(PIdx) << ": "
26200b57cec5SDimitry Andric                       << getResourceCount(PIdx) / SchedModel->getLatencyFactor()
26210b57cec5SDimitry Andric                       << "c\n");
26220b57cec5SDimitry Andric   }
26230b57cec5SDimitry Andric   // For reserved resources, record the highest cycle using the resource.
26240b57cec5SDimitry Andric   unsigned NextAvailable, InstanceIdx;
2625fe013be4SDimitry Andric   std::tie(NextAvailable, InstanceIdx) =
2626c9157d92SDimitry Andric       getNextResourceCycle(SC, PIdx, ReleaseAtCycle, AcquireAtCycle);
26270b57cec5SDimitry Andric   if (NextAvailable > CurrCycle) {
26280b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "  Resource conflict: "
26290b57cec5SDimitry Andric                       << SchedModel->getResourceName(PIdx)
26300b57cec5SDimitry Andric                       << '[' << InstanceIdx - ReservedCyclesIndex[PIdx]  << ']'
26310b57cec5SDimitry Andric                       << " reserved until @" << NextAvailable << "\n");
26320b57cec5SDimitry Andric   }
26330b57cec5SDimitry Andric   return NextAvailable;
26340b57cec5SDimitry Andric }
26350b57cec5SDimitry Andric 
26360b57cec5SDimitry Andric /// Move the boundary of scheduled code by one SUnit.
bumpNode(SUnit * SU)26370b57cec5SDimitry Andric void SchedBoundary::bumpNode(SUnit *SU) {
26380b57cec5SDimitry Andric   // Update the reservation table.
26390b57cec5SDimitry Andric   if (HazardRec->isEnabled()) {
26400b57cec5SDimitry Andric     if (!isTop() && SU->isCall) {
26410b57cec5SDimitry Andric       // Calls are scheduled with their preceding instructions. For bottom-up
26420b57cec5SDimitry Andric       // scheduling, clear the pipeline state before emitting.
26430b57cec5SDimitry Andric       HazardRec->Reset();
26440b57cec5SDimitry Andric     }
26450b57cec5SDimitry Andric     HazardRec->EmitInstruction(SU);
26460b57cec5SDimitry Andric     // Scheduling an instruction may have made pending instructions available.
26470b57cec5SDimitry Andric     CheckPending = true;
26480b57cec5SDimitry Andric   }
26490b57cec5SDimitry Andric   // checkHazard should prevent scheduling multiple instructions per cycle that
26500b57cec5SDimitry Andric   // exceed the issue width.
26510b57cec5SDimitry Andric   const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
26520b57cec5SDimitry Andric   unsigned IncMOps = SchedModel->getNumMicroOps(SU->getInstr());
26530b57cec5SDimitry Andric   assert(
26540b57cec5SDimitry Andric       (CurrMOps == 0 || (CurrMOps + IncMOps) <= SchedModel->getIssueWidth()) &&
26550b57cec5SDimitry Andric       "Cannot schedule this instruction's MicroOps in the current cycle.");
26560b57cec5SDimitry Andric 
26570b57cec5SDimitry Andric   unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
26580b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "  Ready @" << ReadyCycle << "c\n");
26590b57cec5SDimitry Andric 
26600b57cec5SDimitry Andric   unsigned NextCycle = CurrCycle;
26610b57cec5SDimitry Andric   switch (SchedModel->getMicroOpBufferSize()) {
26620b57cec5SDimitry Andric   case 0:
26630b57cec5SDimitry Andric     assert(ReadyCycle <= CurrCycle && "Broken PendingQueue");
26640b57cec5SDimitry Andric     break;
26650b57cec5SDimitry Andric   case 1:
26660b57cec5SDimitry Andric     if (ReadyCycle > NextCycle) {
26670b57cec5SDimitry Andric       NextCycle = ReadyCycle;
26680b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "  *** Stall until: " << ReadyCycle << "\n");
26690b57cec5SDimitry Andric     }
26700b57cec5SDimitry Andric     break;
26710b57cec5SDimitry Andric   default:
26720b57cec5SDimitry Andric     // We don't currently model the OOO reorder buffer, so consider all
26730b57cec5SDimitry Andric     // scheduled MOps to be "retired". We do loosely model in-order resource
26740b57cec5SDimitry Andric     // latency. If this instruction uses an in-order resource, account for any
26750b57cec5SDimitry Andric     // likely stall cycles.
26760b57cec5SDimitry Andric     if (SU->isUnbuffered && ReadyCycle > NextCycle)
26770b57cec5SDimitry Andric       NextCycle = ReadyCycle;
26780b57cec5SDimitry Andric     break;
26790b57cec5SDimitry Andric   }
26800b57cec5SDimitry Andric   RetiredMOps += IncMOps;
26810b57cec5SDimitry Andric 
26820b57cec5SDimitry Andric   // Update resource counts and critical resource.
26830b57cec5SDimitry Andric   if (SchedModel->hasInstrSchedModel()) {
26840b57cec5SDimitry Andric     unsigned DecRemIssue = IncMOps * SchedModel->getMicroOpFactor();
26850b57cec5SDimitry Andric     assert(Rem->RemIssueCount >= DecRemIssue && "MOps double counted");
26860b57cec5SDimitry Andric     Rem->RemIssueCount -= DecRemIssue;
26870b57cec5SDimitry Andric     if (ZoneCritResIdx) {
26880b57cec5SDimitry Andric       // Scale scheduled micro-ops for comparing with the critical resource.
26890b57cec5SDimitry Andric       unsigned ScaledMOps =
26900b57cec5SDimitry Andric         RetiredMOps * SchedModel->getMicroOpFactor();
26910b57cec5SDimitry Andric 
26920b57cec5SDimitry Andric       // If scaled micro-ops are now more than the previous critical resource by
26930b57cec5SDimitry Andric       // a full cycle, then micro-ops issue becomes critical.
26940b57cec5SDimitry Andric       if ((int)(ScaledMOps - getResourceCount(ZoneCritResIdx))
26950b57cec5SDimitry Andric           >= (int)SchedModel->getLatencyFactor()) {
26960b57cec5SDimitry Andric         ZoneCritResIdx = 0;
26970b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "  *** Critical resource NumMicroOps: "
26980b57cec5SDimitry Andric                           << ScaledMOps / SchedModel->getLatencyFactor()
26990b57cec5SDimitry Andric                           << "c\n");
27000b57cec5SDimitry Andric       }
27010b57cec5SDimitry Andric     }
27020b57cec5SDimitry Andric     for (TargetSchedModel::ProcResIter
27030b57cec5SDimitry Andric            PI = SchedModel->getWriteProcResBegin(SC),
27040b57cec5SDimitry Andric            PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2705c9157d92SDimitry Andric       unsigned RCycle =
2706c9157d92SDimitry Andric           countResource(SC, PI->ProcResourceIdx, PI->ReleaseAtCycle, NextCycle,
2707c9157d92SDimitry Andric                         PI->AcquireAtCycle);
27080b57cec5SDimitry Andric       if (RCycle > NextCycle)
27090b57cec5SDimitry Andric         NextCycle = RCycle;
27100b57cec5SDimitry Andric     }
27110b57cec5SDimitry Andric     if (SU->hasReservedResource) {
27120b57cec5SDimitry Andric       // For reserved resources, record the highest cycle using the resource.
27130b57cec5SDimitry Andric       // For top-down scheduling, this is the cycle in which we schedule this
27140b57cec5SDimitry Andric       // instruction plus the number of cycles the operations reserves the
27150b57cec5SDimitry Andric       // resource. For bottom-up is it simply the instruction's cycle.
27160b57cec5SDimitry Andric       for (TargetSchedModel::ProcResIter
27170b57cec5SDimitry Andric              PI = SchedModel->getWriteProcResBegin(SC),
27180b57cec5SDimitry Andric              PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
27190b57cec5SDimitry Andric         unsigned PIdx = PI->ProcResourceIdx;
27200b57cec5SDimitry Andric         if (SchedModel->getProcResource(PIdx)->BufferSize == 0) {
2721fe013be4SDimitry Andric 
2722fe013be4SDimitry Andric           if (SchedModel && SchedModel->enableIntervals()) {
27230b57cec5SDimitry Andric             unsigned ReservedUntil, InstanceIdx;
2724c9157d92SDimitry Andric             std::tie(ReservedUntil, InstanceIdx) = getNextResourceCycle(
2725c9157d92SDimitry Andric                 SC, PIdx, PI->ReleaseAtCycle, PI->AcquireAtCycle);
2726fe013be4SDimitry Andric             if (isTop()) {
2727fe013be4SDimitry Andric               ReservedResourceSegments[InstanceIdx].add(
2728fe013be4SDimitry Andric                   ResourceSegments::getResourceIntervalTop(
2729c9157d92SDimitry Andric                       NextCycle, PI->AcquireAtCycle, PI->ReleaseAtCycle),
2730fe013be4SDimitry Andric                   MIResourceCutOff);
2731fe013be4SDimitry Andric             } else {
2732fe013be4SDimitry Andric               ReservedResourceSegments[InstanceIdx].add(
2733fe013be4SDimitry Andric                   ResourceSegments::getResourceIntervalBottom(
2734c9157d92SDimitry Andric                       NextCycle, PI->AcquireAtCycle, PI->ReleaseAtCycle),
2735fe013be4SDimitry Andric                   MIResourceCutOff);
2736fe013be4SDimitry Andric             }
2737fe013be4SDimitry Andric           } else {
2738fe013be4SDimitry Andric 
2739fe013be4SDimitry Andric             unsigned ReservedUntil, InstanceIdx;
2740c9157d92SDimitry Andric             std::tie(ReservedUntil, InstanceIdx) = getNextResourceCycle(
2741c9157d92SDimitry Andric                 SC, PIdx, PI->ReleaseAtCycle, PI->AcquireAtCycle);
27420b57cec5SDimitry Andric             if (isTop()) {
27430b57cec5SDimitry Andric               ReservedCycles[InstanceIdx] =
2744c9157d92SDimitry Andric                   std::max(ReservedUntil, NextCycle + PI->ReleaseAtCycle);
27450b57cec5SDimitry Andric             } else
27460b57cec5SDimitry Andric               ReservedCycles[InstanceIdx] = NextCycle;
27470b57cec5SDimitry Andric           }
27480b57cec5SDimitry Andric         }
27490b57cec5SDimitry Andric       }
27500b57cec5SDimitry Andric     }
2751fe013be4SDimitry Andric   }
27520b57cec5SDimitry Andric   // Update ExpectedLatency and DependentLatency.
27530b57cec5SDimitry Andric   unsigned &TopLatency = isTop() ? ExpectedLatency : DependentLatency;
27540b57cec5SDimitry Andric   unsigned &BotLatency = isTop() ? DependentLatency : ExpectedLatency;
27550b57cec5SDimitry Andric   if (SU->getDepth() > TopLatency) {
27560b57cec5SDimitry Andric     TopLatency = SU->getDepth();
27570b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "  " << Available.getName() << " TopLatency SU("
27580b57cec5SDimitry Andric                       << SU->NodeNum << ") " << TopLatency << "c\n");
27590b57cec5SDimitry Andric   }
27600b57cec5SDimitry Andric   if (SU->getHeight() > BotLatency) {
27610b57cec5SDimitry Andric     BotLatency = SU->getHeight();
27620b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "  " << Available.getName() << " BotLatency SU("
27630b57cec5SDimitry Andric                       << SU->NodeNum << ") " << BotLatency << "c\n");
27640b57cec5SDimitry Andric   }
27650b57cec5SDimitry Andric   // If we stall for any reason, bump the cycle.
27660b57cec5SDimitry Andric   if (NextCycle > CurrCycle)
27670b57cec5SDimitry Andric     bumpCycle(NextCycle);
27680b57cec5SDimitry Andric   else
27690b57cec5SDimitry Andric     // After updating ZoneCritResIdx and ExpectedLatency, check if we're
27700b57cec5SDimitry Andric     // resource limited. If a stall occurred, bumpCycle does this.
27710b57cec5SDimitry Andric     IsResourceLimited =
27720b57cec5SDimitry Andric         checkResourceLimit(SchedModel->getLatencyFactor(), getCriticalCount(),
27730b57cec5SDimitry Andric                            getScheduledLatency(), true);
27740b57cec5SDimitry Andric 
27750b57cec5SDimitry Andric   // Update CurrMOps after calling bumpCycle to handle stalls, since bumpCycle
27760b57cec5SDimitry Andric   // resets CurrMOps. Loop to handle instructions with more MOps than issue in
27770b57cec5SDimitry Andric   // one cycle.  Since we commonly reach the max MOps here, opportunistically
27780b57cec5SDimitry Andric   // bump the cycle to avoid uselessly checking everything in the readyQ.
27790b57cec5SDimitry Andric   CurrMOps += IncMOps;
27800b57cec5SDimitry Andric 
27810b57cec5SDimitry Andric   // Bump the cycle count for issue group constraints.
27820b57cec5SDimitry Andric   // This must be done after NextCycle has been adjust for all other stalls.
27830b57cec5SDimitry Andric   // Calling bumpCycle(X) will reduce CurrMOps by one issue group and set
27840b57cec5SDimitry Andric   // currCycle to X.
27850b57cec5SDimitry Andric   if ((isTop() &&  SchedModel->mustEndGroup(SU->getInstr())) ||
27860b57cec5SDimitry Andric       (!isTop() && SchedModel->mustBeginGroup(SU->getInstr()))) {
27870b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "  Bump cycle to " << (isTop() ? "end" : "begin")
27880b57cec5SDimitry Andric                       << " group\n");
27890b57cec5SDimitry Andric     bumpCycle(++NextCycle);
27900b57cec5SDimitry Andric   }
27910b57cec5SDimitry Andric 
27920b57cec5SDimitry Andric   while (CurrMOps >= SchedModel->getIssueWidth()) {
27930b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "  *** Max MOps " << CurrMOps << " at cycle "
27940b57cec5SDimitry Andric                       << CurrCycle << '\n');
27950b57cec5SDimitry Andric     bumpCycle(++NextCycle);
27960b57cec5SDimitry Andric   }
27970b57cec5SDimitry Andric   LLVM_DEBUG(dumpScheduledState());
27980b57cec5SDimitry Andric }
27990b57cec5SDimitry Andric 
28000b57cec5SDimitry Andric /// Release pending ready nodes in to the available queue. This makes them
28010b57cec5SDimitry Andric /// visible to heuristics.
releasePending()28020b57cec5SDimitry Andric void SchedBoundary::releasePending() {
28030b57cec5SDimitry Andric   // If the available queue is empty, it is safe to reset MinReadyCycle.
28040b57cec5SDimitry Andric   if (Available.empty())
28050b57cec5SDimitry Andric     MinReadyCycle = std::numeric_limits<unsigned>::max();
28060b57cec5SDimitry Andric 
28070b57cec5SDimitry Andric   // Check to see if any of the pending instructions are ready to issue.  If
28080b57cec5SDimitry Andric   // so, add them to the available queue.
2809480093f4SDimitry Andric   for (unsigned I = 0, E = Pending.size(); I < E; ++I) {
2810480093f4SDimitry Andric     SUnit *SU = *(Pending.begin() + I);
28110b57cec5SDimitry Andric     unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
28120b57cec5SDimitry Andric 
28130b57cec5SDimitry Andric     if (ReadyCycle < MinReadyCycle)
28140b57cec5SDimitry Andric       MinReadyCycle = ReadyCycle;
28150b57cec5SDimitry Andric 
28160b57cec5SDimitry Andric     if (Available.size() >= ReadyListLimit)
28170b57cec5SDimitry Andric       break;
28180b57cec5SDimitry Andric 
2819480093f4SDimitry Andric     releaseNode(SU, ReadyCycle, true, I);
2820480093f4SDimitry Andric     if (E != Pending.size()) {
2821480093f4SDimitry Andric       --I;
2822480093f4SDimitry Andric       --E;
2823480093f4SDimitry Andric     }
28240b57cec5SDimitry Andric   }
28250b57cec5SDimitry Andric   CheckPending = false;
28260b57cec5SDimitry Andric }
28270b57cec5SDimitry Andric 
28280b57cec5SDimitry Andric /// Remove SU from the ready set for this boundary.
removeReady(SUnit * SU)28290b57cec5SDimitry Andric void SchedBoundary::removeReady(SUnit *SU) {
28300b57cec5SDimitry Andric   if (Available.isInQueue(SU))
28310b57cec5SDimitry Andric     Available.remove(Available.find(SU));
28320b57cec5SDimitry Andric   else {
28330b57cec5SDimitry Andric     assert(Pending.isInQueue(SU) && "bad ready count");
28340b57cec5SDimitry Andric     Pending.remove(Pending.find(SU));
28350b57cec5SDimitry Andric   }
28360b57cec5SDimitry Andric }
28370b57cec5SDimitry Andric 
28380b57cec5SDimitry Andric /// If this queue only has one ready candidate, return it. As a side effect,
28390b57cec5SDimitry Andric /// defer any nodes that now hit a hazard, and advance the cycle until at least
28400b57cec5SDimitry Andric /// one node is ready. If multiple instructions are ready, return NULL.
pickOnlyChoice()28410b57cec5SDimitry Andric SUnit *SchedBoundary::pickOnlyChoice() {
28420b57cec5SDimitry Andric   if (CheckPending)
28430b57cec5SDimitry Andric     releasePending();
28440b57cec5SDimitry Andric 
28450b57cec5SDimitry Andric   // Defer any ready instrs that now have a hazard.
28460b57cec5SDimitry Andric   for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
28470b57cec5SDimitry Andric     if (checkHazard(*I)) {
28480b57cec5SDimitry Andric       Pending.push(*I);
28490b57cec5SDimitry Andric       I = Available.remove(I);
28500b57cec5SDimitry Andric       continue;
28510b57cec5SDimitry Andric     }
28520b57cec5SDimitry Andric     ++I;
28530b57cec5SDimitry Andric   }
28540b57cec5SDimitry Andric   for (unsigned i = 0; Available.empty(); ++i) {
28550b57cec5SDimitry Andric //  FIXME: Re-enable assert once PR20057 is resolved.
28560b57cec5SDimitry Andric //    assert(i <= (HazardRec->getMaxLookAhead() + MaxObservedStall) &&
28570b57cec5SDimitry Andric //           "permanent hazard");
28580b57cec5SDimitry Andric     (void)i;
28590b57cec5SDimitry Andric     bumpCycle(CurrCycle + 1);
28600b57cec5SDimitry Andric     releasePending();
28610b57cec5SDimitry Andric   }
28620b57cec5SDimitry Andric 
28630b57cec5SDimitry Andric   LLVM_DEBUG(Pending.dump());
28640b57cec5SDimitry Andric   LLVM_DEBUG(Available.dump());
28650b57cec5SDimitry Andric 
28660b57cec5SDimitry Andric   if (Available.size() == 1)
28670b57cec5SDimitry Andric     return *Available.begin();
28680b57cec5SDimitry Andric   return nullptr;
28690b57cec5SDimitry Andric }
28700b57cec5SDimitry Andric 
28710b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2872bdd1243dSDimitry Andric 
2873bdd1243dSDimitry Andric /// Dump the content of the \ref ReservedCycles vector for the
2874bdd1243dSDimitry Andric /// resources that are used in the basic block.
2875bdd1243dSDimitry Andric ///
dumpReservedCycles() const2876bdd1243dSDimitry Andric LLVM_DUMP_METHOD void SchedBoundary::dumpReservedCycles() const {
2877bdd1243dSDimitry Andric   if (!SchedModel->hasInstrSchedModel())
2878bdd1243dSDimitry Andric     return;
2879bdd1243dSDimitry Andric 
2880bdd1243dSDimitry Andric   unsigned ResourceCount = SchedModel->getNumProcResourceKinds();
2881bdd1243dSDimitry Andric   unsigned StartIdx = 0;
2882bdd1243dSDimitry Andric 
2883bdd1243dSDimitry Andric   for (unsigned ResIdx = 0; ResIdx < ResourceCount; ++ResIdx) {
2884bdd1243dSDimitry Andric     const unsigned NumUnits = SchedModel->getProcResource(ResIdx)->NumUnits;
2885bdd1243dSDimitry Andric     std::string ResName = SchedModel->getResourceName(ResIdx);
2886bdd1243dSDimitry Andric     for (unsigned UnitIdx = 0; UnitIdx < NumUnits; ++UnitIdx) {
2887fe013be4SDimitry Andric       dbgs() << ResName << "(" << UnitIdx << ") = ";
2888fe013be4SDimitry Andric       if (SchedModel && SchedModel->enableIntervals()) {
2889fe013be4SDimitry Andric         if (ReservedResourceSegments.count(StartIdx + UnitIdx))
2890fe013be4SDimitry Andric           dbgs() << ReservedResourceSegments.at(StartIdx + UnitIdx);
2891fe013be4SDimitry Andric         else
2892fe013be4SDimitry Andric           dbgs() << "{ }\n";
2893fe013be4SDimitry Andric       } else
2894fe013be4SDimitry Andric         dbgs() << ReservedCycles[StartIdx + UnitIdx] << "\n";
2895bdd1243dSDimitry Andric     }
2896bdd1243dSDimitry Andric     StartIdx += NumUnits;
2897bdd1243dSDimitry Andric   }
2898bdd1243dSDimitry Andric }
2899bdd1243dSDimitry Andric 
29000b57cec5SDimitry Andric // This is useful information to dump after bumpNode.
29010b57cec5SDimitry Andric // Note that the Queue contents are more useful before pickNodeFromQueue.
dumpScheduledState() const29020b57cec5SDimitry Andric LLVM_DUMP_METHOD void SchedBoundary::dumpScheduledState() const {
29030b57cec5SDimitry Andric   unsigned ResFactor;
29040b57cec5SDimitry Andric   unsigned ResCount;
29050b57cec5SDimitry Andric   if (ZoneCritResIdx) {
29060b57cec5SDimitry Andric     ResFactor = SchedModel->getResourceFactor(ZoneCritResIdx);
29070b57cec5SDimitry Andric     ResCount = getResourceCount(ZoneCritResIdx);
29080b57cec5SDimitry Andric   } else {
29090b57cec5SDimitry Andric     ResFactor = SchedModel->getMicroOpFactor();
29100b57cec5SDimitry Andric     ResCount = RetiredMOps * ResFactor;
29110b57cec5SDimitry Andric   }
29120b57cec5SDimitry Andric   unsigned LFactor = SchedModel->getLatencyFactor();
29130b57cec5SDimitry Andric   dbgs() << Available.getName() << " @" << CurrCycle << "c\n"
29140b57cec5SDimitry Andric          << "  Retired: " << RetiredMOps;
29150b57cec5SDimitry Andric   dbgs() << "\n  Executed: " << getExecutedCount() / LFactor << "c";
29160b57cec5SDimitry Andric   dbgs() << "\n  Critical: " << ResCount / LFactor << "c, "
29170b57cec5SDimitry Andric          << ResCount / ResFactor << " "
29180b57cec5SDimitry Andric          << SchedModel->getResourceName(ZoneCritResIdx)
29190b57cec5SDimitry Andric          << "\n  ExpectedLatency: " << ExpectedLatency << "c\n"
29200b57cec5SDimitry Andric          << (IsResourceLimited ? "  - Resource" : "  - Latency")
29210b57cec5SDimitry Andric          << " limited.\n";
2922bdd1243dSDimitry Andric   if (MISchedDumpReservedCycles)
2923bdd1243dSDimitry Andric     dumpReservedCycles();
29240b57cec5SDimitry Andric }
29250b57cec5SDimitry Andric #endif
29260b57cec5SDimitry Andric 
29270b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
29280b57cec5SDimitry Andric // GenericScheduler - Generic implementation of MachineSchedStrategy.
29290b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
29300b57cec5SDimitry Andric 
29310b57cec5SDimitry Andric void GenericSchedulerBase::SchedCandidate::
initResourceDelta(const ScheduleDAGMI * DAG,const TargetSchedModel * SchedModel)29320b57cec5SDimitry Andric initResourceDelta(const ScheduleDAGMI *DAG,
29330b57cec5SDimitry Andric                   const TargetSchedModel *SchedModel) {
29340b57cec5SDimitry Andric   if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
29350b57cec5SDimitry Andric     return;
29360b57cec5SDimitry Andric 
29370b57cec5SDimitry Andric   const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
29380b57cec5SDimitry Andric   for (TargetSchedModel::ProcResIter
29390b57cec5SDimitry Andric          PI = SchedModel->getWriteProcResBegin(SC),
29400b57cec5SDimitry Andric          PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
29410b57cec5SDimitry Andric     if (PI->ProcResourceIdx == Policy.ReduceResIdx)
2942c9157d92SDimitry Andric       ResDelta.CritResources += PI->ReleaseAtCycle;
29430b57cec5SDimitry Andric     if (PI->ProcResourceIdx == Policy.DemandResIdx)
2944c9157d92SDimitry Andric       ResDelta.DemandedResources += PI->ReleaseAtCycle;
29450b57cec5SDimitry Andric   }
29460b57cec5SDimitry Andric }
29470b57cec5SDimitry Andric 
29480b57cec5SDimitry Andric /// Compute remaining latency. We need this both to determine whether the
29490b57cec5SDimitry Andric /// overall schedule has become latency-limited and whether the instructions
29500b57cec5SDimitry Andric /// outside this zone are resource or latency limited.
29510b57cec5SDimitry Andric ///
29520b57cec5SDimitry Andric /// The "dependent" latency is updated incrementally during scheduling as the
29530b57cec5SDimitry Andric /// max height/depth of scheduled nodes minus the cycles since it was
29540b57cec5SDimitry Andric /// scheduled:
29550b57cec5SDimitry Andric ///   DLat = max (N.depth - (CurrCycle - N.ReadyCycle) for N in Zone
29560b57cec5SDimitry Andric ///
29570b57cec5SDimitry Andric /// The "independent" latency is the max ready queue depth:
29580b57cec5SDimitry Andric ///   ILat = max N.depth for N in Available|Pending
29590b57cec5SDimitry Andric ///
29600b57cec5SDimitry Andric /// RemainingLatency is the greater of independent and dependent latency.
29610b57cec5SDimitry Andric ///
29620b57cec5SDimitry Andric /// These computations are expensive, especially in DAGs with many edges, so
29630b57cec5SDimitry Andric /// only do them if necessary.
computeRemLatency(SchedBoundary & CurrZone)29640b57cec5SDimitry Andric static unsigned computeRemLatency(SchedBoundary &CurrZone) {
29650b57cec5SDimitry Andric   unsigned RemLatency = CurrZone.getDependentLatency();
29660b57cec5SDimitry Andric   RemLatency = std::max(RemLatency,
29670b57cec5SDimitry Andric                         CurrZone.findMaxLatency(CurrZone.Available.elements()));
29680b57cec5SDimitry Andric   RemLatency = std::max(RemLatency,
29690b57cec5SDimitry Andric                         CurrZone.findMaxLatency(CurrZone.Pending.elements()));
29700b57cec5SDimitry Andric   return RemLatency;
29710b57cec5SDimitry Andric }
29720b57cec5SDimitry Andric 
29730b57cec5SDimitry Andric /// Returns true if the current cycle plus remaning latency is greater than
29740b57cec5SDimitry Andric /// the critical path in the scheduling region.
shouldReduceLatency(const CandPolicy & Policy,SchedBoundary & CurrZone,bool ComputeRemLatency,unsigned & RemLatency) const29750b57cec5SDimitry Andric bool GenericSchedulerBase::shouldReduceLatency(const CandPolicy &Policy,
29760b57cec5SDimitry Andric                                                SchedBoundary &CurrZone,
29770b57cec5SDimitry Andric                                                bool ComputeRemLatency,
29780b57cec5SDimitry Andric                                                unsigned &RemLatency) const {
29790b57cec5SDimitry Andric   // The current cycle is already greater than the critical path, so we are
29800b57cec5SDimitry Andric   // already latency limited and don't need to compute the remaining latency.
29810b57cec5SDimitry Andric   if (CurrZone.getCurrCycle() > Rem.CriticalPath)
29820b57cec5SDimitry Andric     return true;
29830b57cec5SDimitry Andric 
29840b57cec5SDimitry Andric   // If we haven't scheduled anything yet, then we aren't latency limited.
29850b57cec5SDimitry Andric   if (CurrZone.getCurrCycle() == 0)
29860b57cec5SDimitry Andric     return false;
29870b57cec5SDimitry Andric 
29880b57cec5SDimitry Andric   if (ComputeRemLatency)
29890b57cec5SDimitry Andric     RemLatency = computeRemLatency(CurrZone);
29900b57cec5SDimitry Andric 
29910b57cec5SDimitry Andric   return RemLatency + CurrZone.getCurrCycle() > Rem.CriticalPath;
29920b57cec5SDimitry Andric }
29930b57cec5SDimitry Andric 
29940b57cec5SDimitry Andric /// Set the CandPolicy given a scheduling zone given the current resources and
29950b57cec5SDimitry Andric /// latencies inside and outside the zone.
setPolicy(CandPolicy & Policy,bool IsPostRA,SchedBoundary & CurrZone,SchedBoundary * OtherZone)29960b57cec5SDimitry Andric void GenericSchedulerBase::setPolicy(CandPolicy &Policy, bool IsPostRA,
29970b57cec5SDimitry Andric                                      SchedBoundary &CurrZone,
29980b57cec5SDimitry Andric                                      SchedBoundary *OtherZone) {
29990b57cec5SDimitry Andric   // Apply preemptive heuristics based on the total latency and resources
30000b57cec5SDimitry Andric   // inside and outside this zone. Potential stalls should be considered before
30010b57cec5SDimitry Andric   // following this policy.
30020b57cec5SDimitry Andric 
30030b57cec5SDimitry Andric   // Compute the critical resource outside the zone.
30040b57cec5SDimitry Andric   unsigned OtherCritIdx = 0;
30050b57cec5SDimitry Andric   unsigned OtherCount =
30060b57cec5SDimitry Andric     OtherZone ? OtherZone->getOtherResourceCount(OtherCritIdx) : 0;
30070b57cec5SDimitry Andric 
30080b57cec5SDimitry Andric   bool OtherResLimited = false;
30090b57cec5SDimitry Andric   unsigned RemLatency = 0;
30100b57cec5SDimitry Andric   bool RemLatencyComputed = false;
30110b57cec5SDimitry Andric   if (SchedModel->hasInstrSchedModel() && OtherCount != 0) {
30120b57cec5SDimitry Andric     RemLatency = computeRemLatency(CurrZone);
30130b57cec5SDimitry Andric     RemLatencyComputed = true;
30140b57cec5SDimitry Andric     OtherResLimited = checkResourceLimit(SchedModel->getLatencyFactor(),
30150b57cec5SDimitry Andric                                          OtherCount, RemLatency, false);
30160b57cec5SDimitry Andric   }
30170b57cec5SDimitry Andric 
30180b57cec5SDimitry Andric   // Schedule aggressively for latency in PostRA mode. We don't check for
30190b57cec5SDimitry Andric   // acyclic latency during PostRA, and highly out-of-order processors will
30200b57cec5SDimitry Andric   // skip PostRA scheduling.
30210b57cec5SDimitry Andric   if (!OtherResLimited &&
30220b57cec5SDimitry Andric       (IsPostRA || shouldReduceLatency(Policy, CurrZone, !RemLatencyComputed,
30230b57cec5SDimitry Andric                                        RemLatency))) {
30240b57cec5SDimitry Andric     Policy.ReduceLatency |= true;
30250b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "  " << CurrZone.Available.getName()
30260b57cec5SDimitry Andric                       << " RemainingLatency " << RemLatency << " + "
30270b57cec5SDimitry Andric                       << CurrZone.getCurrCycle() << "c > CritPath "
30280b57cec5SDimitry Andric                       << Rem.CriticalPath << "\n");
30290b57cec5SDimitry Andric   }
30300b57cec5SDimitry Andric   // If the same resource is limiting inside and outside the zone, do nothing.
30310b57cec5SDimitry Andric   if (CurrZone.getZoneCritResIdx() == OtherCritIdx)
30320b57cec5SDimitry Andric     return;
30330b57cec5SDimitry Andric 
30340b57cec5SDimitry Andric   LLVM_DEBUG(if (CurrZone.isResourceLimited()) {
30350b57cec5SDimitry Andric     dbgs() << "  " << CurrZone.Available.getName() << " ResourceLimited: "
30360b57cec5SDimitry Andric            << SchedModel->getResourceName(CurrZone.getZoneCritResIdx()) << "\n";
30370b57cec5SDimitry Andric   } if (OtherResLimited) dbgs()
30380b57cec5SDimitry Andric                  << "  RemainingLimit: "
30390b57cec5SDimitry Andric                  << SchedModel->getResourceName(OtherCritIdx) << "\n";
30400b57cec5SDimitry Andric              if (!CurrZone.isResourceLimited() && !OtherResLimited) dbgs()
30410b57cec5SDimitry Andric              << "  Latency limited both directions.\n");
30420b57cec5SDimitry Andric 
30430b57cec5SDimitry Andric   if (CurrZone.isResourceLimited() && !Policy.ReduceResIdx)
30440b57cec5SDimitry Andric     Policy.ReduceResIdx = CurrZone.getZoneCritResIdx();
30450b57cec5SDimitry Andric 
30460b57cec5SDimitry Andric   if (OtherResLimited)
30470b57cec5SDimitry Andric     Policy.DemandResIdx = OtherCritIdx;
30480b57cec5SDimitry Andric }
30490b57cec5SDimitry Andric 
30500b57cec5SDimitry Andric #ifndef NDEBUG
getReasonStr(GenericSchedulerBase::CandReason Reason)30510b57cec5SDimitry Andric const char *GenericSchedulerBase::getReasonStr(
30520b57cec5SDimitry Andric   GenericSchedulerBase::CandReason Reason) {
30530b57cec5SDimitry Andric   switch (Reason) {
30540b57cec5SDimitry Andric   case NoCand:         return "NOCAND    ";
30550b57cec5SDimitry Andric   case Only1:          return "ONLY1     ";
30560b57cec5SDimitry Andric   case PhysReg:        return "PHYS-REG  ";
30570b57cec5SDimitry Andric   case RegExcess:      return "REG-EXCESS";
30580b57cec5SDimitry Andric   case RegCritical:    return "REG-CRIT  ";
30590b57cec5SDimitry Andric   case Stall:          return "STALL     ";
30600b57cec5SDimitry Andric   case Cluster:        return "CLUSTER   ";
30610b57cec5SDimitry Andric   case Weak:           return "WEAK      ";
30620b57cec5SDimitry Andric   case RegMax:         return "REG-MAX   ";
30630b57cec5SDimitry Andric   case ResourceReduce: return "RES-REDUCE";
30640b57cec5SDimitry Andric   case ResourceDemand: return "RES-DEMAND";
30650b57cec5SDimitry Andric   case TopDepthReduce: return "TOP-DEPTH ";
30660b57cec5SDimitry Andric   case TopPathReduce:  return "TOP-PATH  ";
30670b57cec5SDimitry Andric   case BotHeightReduce:return "BOT-HEIGHT";
30680b57cec5SDimitry Andric   case BotPathReduce:  return "BOT-PATH  ";
30690b57cec5SDimitry Andric   case NextDefUse:     return "DEF-USE   ";
30700b57cec5SDimitry Andric   case NodeOrder:      return "ORDER     ";
30710b57cec5SDimitry Andric   };
30720b57cec5SDimitry Andric   llvm_unreachable("Unknown reason!");
30730b57cec5SDimitry Andric }
30740b57cec5SDimitry Andric 
traceCandidate(const SchedCandidate & Cand)30750b57cec5SDimitry Andric void GenericSchedulerBase::traceCandidate(const SchedCandidate &Cand) {
30760b57cec5SDimitry Andric   PressureChange P;
30770b57cec5SDimitry Andric   unsigned ResIdx = 0;
30780b57cec5SDimitry Andric   unsigned Latency = 0;
30790b57cec5SDimitry Andric   switch (Cand.Reason) {
30800b57cec5SDimitry Andric   default:
30810b57cec5SDimitry Andric     break;
30820b57cec5SDimitry Andric   case RegExcess:
30830b57cec5SDimitry Andric     P = Cand.RPDelta.Excess;
30840b57cec5SDimitry Andric     break;
30850b57cec5SDimitry Andric   case RegCritical:
30860b57cec5SDimitry Andric     P = Cand.RPDelta.CriticalMax;
30870b57cec5SDimitry Andric     break;
30880b57cec5SDimitry Andric   case RegMax:
30890b57cec5SDimitry Andric     P = Cand.RPDelta.CurrentMax;
30900b57cec5SDimitry Andric     break;
30910b57cec5SDimitry Andric   case ResourceReduce:
30920b57cec5SDimitry Andric     ResIdx = Cand.Policy.ReduceResIdx;
30930b57cec5SDimitry Andric     break;
30940b57cec5SDimitry Andric   case ResourceDemand:
30950b57cec5SDimitry Andric     ResIdx = Cand.Policy.DemandResIdx;
30960b57cec5SDimitry Andric     break;
30970b57cec5SDimitry Andric   case TopDepthReduce:
30980b57cec5SDimitry Andric     Latency = Cand.SU->getDepth();
30990b57cec5SDimitry Andric     break;
31000b57cec5SDimitry Andric   case TopPathReduce:
31010b57cec5SDimitry Andric     Latency = Cand.SU->getHeight();
31020b57cec5SDimitry Andric     break;
31030b57cec5SDimitry Andric   case BotHeightReduce:
31040b57cec5SDimitry Andric     Latency = Cand.SU->getHeight();
31050b57cec5SDimitry Andric     break;
31060b57cec5SDimitry Andric   case BotPathReduce:
31070b57cec5SDimitry Andric     Latency = Cand.SU->getDepth();
31080b57cec5SDimitry Andric     break;
31090b57cec5SDimitry Andric   }
31100b57cec5SDimitry Andric   dbgs() << "  Cand SU(" << Cand.SU->NodeNum << ") " << getReasonStr(Cand.Reason);
31110b57cec5SDimitry Andric   if (P.isValid())
31120b57cec5SDimitry Andric     dbgs() << " " << TRI->getRegPressureSetName(P.getPSet())
31130b57cec5SDimitry Andric            << ":" << P.getUnitInc() << " ";
31140b57cec5SDimitry Andric   else
31150b57cec5SDimitry Andric     dbgs() << "      ";
31160b57cec5SDimitry Andric   if (ResIdx)
31170b57cec5SDimitry Andric     dbgs() << " " << SchedModel->getProcResource(ResIdx)->Name << " ";
31180b57cec5SDimitry Andric   else
31190b57cec5SDimitry Andric     dbgs() << "         ";
31200b57cec5SDimitry Andric   if (Latency)
31210b57cec5SDimitry Andric     dbgs() << " " << Latency << " cycles ";
31220b57cec5SDimitry Andric   else
31230b57cec5SDimitry Andric     dbgs() << "          ";
31240b57cec5SDimitry Andric   dbgs() << '\n';
31250b57cec5SDimitry Andric }
31260b57cec5SDimitry Andric #endif
31270b57cec5SDimitry Andric 
31280b57cec5SDimitry Andric namespace llvm {
31290b57cec5SDimitry Andric /// Return true if this heuristic determines order.
3130fe6060f1SDimitry Andric /// TODO: Consider refactor return type of these functions as integer or enum,
3131fe6060f1SDimitry Andric /// as we may need to differentiate whether TryCand is better than Cand.
tryLess(int TryVal,int CandVal,GenericSchedulerBase::SchedCandidate & TryCand,GenericSchedulerBase::SchedCandidate & Cand,GenericSchedulerBase::CandReason Reason)31320b57cec5SDimitry Andric bool tryLess(int TryVal, int CandVal,
31330b57cec5SDimitry Andric              GenericSchedulerBase::SchedCandidate &TryCand,
31340b57cec5SDimitry Andric              GenericSchedulerBase::SchedCandidate &Cand,
31350b57cec5SDimitry Andric              GenericSchedulerBase::CandReason Reason) {
31360b57cec5SDimitry Andric   if (TryVal < CandVal) {
31370b57cec5SDimitry Andric     TryCand.Reason = Reason;
31380b57cec5SDimitry Andric     return true;
31390b57cec5SDimitry Andric   }
31400b57cec5SDimitry Andric   if (TryVal > CandVal) {
31410b57cec5SDimitry Andric     if (Cand.Reason > Reason)
31420b57cec5SDimitry Andric       Cand.Reason = Reason;
31430b57cec5SDimitry Andric     return true;
31440b57cec5SDimitry Andric   }
31450b57cec5SDimitry Andric   return false;
31460b57cec5SDimitry Andric }
31470b57cec5SDimitry Andric 
tryGreater(int TryVal,int CandVal,GenericSchedulerBase::SchedCandidate & TryCand,GenericSchedulerBase::SchedCandidate & Cand,GenericSchedulerBase::CandReason Reason)31480b57cec5SDimitry Andric bool tryGreater(int TryVal, int CandVal,
31490b57cec5SDimitry Andric                 GenericSchedulerBase::SchedCandidate &TryCand,
31500b57cec5SDimitry Andric                 GenericSchedulerBase::SchedCandidate &Cand,
31510b57cec5SDimitry Andric                 GenericSchedulerBase::CandReason Reason) {
31520b57cec5SDimitry Andric   if (TryVal > CandVal) {
31530b57cec5SDimitry Andric     TryCand.Reason = Reason;
31540b57cec5SDimitry Andric     return true;
31550b57cec5SDimitry Andric   }
31560b57cec5SDimitry Andric   if (TryVal < CandVal) {
31570b57cec5SDimitry Andric     if (Cand.Reason > Reason)
31580b57cec5SDimitry Andric       Cand.Reason = Reason;
31590b57cec5SDimitry Andric     return true;
31600b57cec5SDimitry Andric   }
31610b57cec5SDimitry Andric   return false;
31620b57cec5SDimitry Andric }
31630b57cec5SDimitry Andric 
tryLatency(GenericSchedulerBase::SchedCandidate & TryCand,GenericSchedulerBase::SchedCandidate & Cand,SchedBoundary & Zone)31640b57cec5SDimitry Andric bool tryLatency(GenericSchedulerBase::SchedCandidate &TryCand,
31650b57cec5SDimitry Andric                 GenericSchedulerBase::SchedCandidate &Cand,
31660b57cec5SDimitry Andric                 SchedBoundary &Zone) {
31670b57cec5SDimitry Andric   if (Zone.isTop()) {
3168e8d8bef9SDimitry Andric     // Prefer the candidate with the lesser depth, but only if one of them has
3169e8d8bef9SDimitry Andric     // depth greater than the total latency scheduled so far, otherwise either
3170e8d8bef9SDimitry Andric     // of them could be scheduled now with no stall.
3171e8d8bef9SDimitry Andric     if (std::max(TryCand.SU->getDepth(), Cand.SU->getDepth()) >
3172e8d8bef9SDimitry Andric         Zone.getScheduledLatency()) {
31730b57cec5SDimitry Andric       if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
31740b57cec5SDimitry Andric                   TryCand, Cand, GenericSchedulerBase::TopDepthReduce))
31750b57cec5SDimitry Andric         return true;
31760b57cec5SDimitry Andric     }
31770b57cec5SDimitry Andric     if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
31780b57cec5SDimitry Andric                    TryCand, Cand, GenericSchedulerBase::TopPathReduce))
31790b57cec5SDimitry Andric       return true;
31800b57cec5SDimitry Andric   } else {
3181e8d8bef9SDimitry Andric     // Prefer the candidate with the lesser height, but only if one of them has
3182e8d8bef9SDimitry Andric     // height greater than the total latency scheduled so far, otherwise either
3183e8d8bef9SDimitry Andric     // of them could be scheduled now with no stall.
3184e8d8bef9SDimitry Andric     if (std::max(TryCand.SU->getHeight(), Cand.SU->getHeight()) >
3185e8d8bef9SDimitry Andric         Zone.getScheduledLatency()) {
31860b57cec5SDimitry Andric       if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
31870b57cec5SDimitry Andric                   TryCand, Cand, GenericSchedulerBase::BotHeightReduce))
31880b57cec5SDimitry Andric         return true;
31890b57cec5SDimitry Andric     }
31900b57cec5SDimitry Andric     if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
31910b57cec5SDimitry Andric                    TryCand, Cand, GenericSchedulerBase::BotPathReduce))
31920b57cec5SDimitry Andric       return true;
31930b57cec5SDimitry Andric   }
31940b57cec5SDimitry Andric   return false;
31950b57cec5SDimitry Andric }
31960b57cec5SDimitry Andric } // end namespace llvm
31970b57cec5SDimitry Andric 
tracePick(GenericSchedulerBase::CandReason Reason,bool IsTop)31980b57cec5SDimitry Andric static void tracePick(GenericSchedulerBase::CandReason Reason, bool IsTop) {
31990b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Pick " << (IsTop ? "Top " : "Bot ")
32000b57cec5SDimitry Andric                     << GenericSchedulerBase::getReasonStr(Reason) << '\n');
32010b57cec5SDimitry Andric }
32020b57cec5SDimitry Andric 
tracePick(const GenericSchedulerBase::SchedCandidate & Cand)32030b57cec5SDimitry Andric static void tracePick(const GenericSchedulerBase::SchedCandidate &Cand) {
32040b57cec5SDimitry Andric   tracePick(Cand.Reason, Cand.AtTop);
32050b57cec5SDimitry Andric }
32060b57cec5SDimitry Andric 
initialize(ScheduleDAGMI * dag)32070b57cec5SDimitry Andric void GenericScheduler::initialize(ScheduleDAGMI *dag) {
32080b57cec5SDimitry Andric   assert(dag->hasVRegLiveness() &&
32090b57cec5SDimitry Andric          "(PreRA)GenericScheduler needs vreg liveness");
32100b57cec5SDimitry Andric   DAG = static_cast<ScheduleDAGMILive*>(dag);
32110b57cec5SDimitry Andric   SchedModel = DAG->getSchedModel();
32120b57cec5SDimitry Andric   TRI = DAG->TRI;
32130b57cec5SDimitry Andric 
32145ffd83dbSDimitry Andric   if (RegionPolicy.ComputeDFSResult)
32155ffd83dbSDimitry Andric     DAG->computeDFSResult();
32165ffd83dbSDimitry Andric 
32170b57cec5SDimitry Andric   Rem.init(DAG, SchedModel);
32180b57cec5SDimitry Andric   Top.init(DAG, SchedModel, &Rem);
32190b57cec5SDimitry Andric   Bot.init(DAG, SchedModel, &Rem);
32200b57cec5SDimitry Andric 
32210b57cec5SDimitry Andric   // Initialize resource counts.
32220b57cec5SDimitry Andric 
32230b57cec5SDimitry Andric   // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
32240b57cec5SDimitry Andric   // are disabled, then these HazardRecs will be disabled.
32250b57cec5SDimitry Andric   const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
32260b57cec5SDimitry Andric   if (!Top.HazardRec) {
32270b57cec5SDimitry Andric     Top.HazardRec =
32280b57cec5SDimitry Andric         DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
32290b57cec5SDimitry Andric             Itin, DAG);
32300b57cec5SDimitry Andric   }
32310b57cec5SDimitry Andric   if (!Bot.HazardRec) {
32320b57cec5SDimitry Andric     Bot.HazardRec =
32330b57cec5SDimitry Andric         DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
32340b57cec5SDimitry Andric             Itin, DAG);
32350b57cec5SDimitry Andric   }
32360b57cec5SDimitry Andric   TopCand.SU = nullptr;
32370b57cec5SDimitry Andric   BotCand.SU = nullptr;
32380b57cec5SDimitry Andric }
32390b57cec5SDimitry Andric 
32400b57cec5SDimitry Andric /// Initialize the per-region scheduling policy.
initPolicy(MachineBasicBlock::iterator Begin,MachineBasicBlock::iterator End,unsigned NumRegionInstrs)32410b57cec5SDimitry Andric void GenericScheduler::initPolicy(MachineBasicBlock::iterator Begin,
32420b57cec5SDimitry Andric                                   MachineBasicBlock::iterator End,
32430b57cec5SDimitry Andric                                   unsigned NumRegionInstrs) {
32440b57cec5SDimitry Andric   const MachineFunction &MF = *Begin->getMF();
32450b57cec5SDimitry Andric   const TargetLowering *TLI = MF.getSubtarget().getTargetLowering();
32460b57cec5SDimitry Andric 
32470b57cec5SDimitry Andric   // Avoid setting up the register pressure tracker for small regions to save
32480b57cec5SDimitry Andric   // compile time. As a rough heuristic, only track pressure when the number of
32490b57cec5SDimitry Andric   // schedulable instructions exceeds half the integer register file.
32500b57cec5SDimitry Andric   RegionPolicy.ShouldTrackPressure = true;
32510b57cec5SDimitry Andric   for (unsigned VT = MVT::i32; VT > (unsigned)MVT::i1; --VT) {
32520b57cec5SDimitry Andric     MVT::SimpleValueType LegalIntVT = (MVT::SimpleValueType)VT;
32530b57cec5SDimitry Andric     if (TLI->isTypeLegal(LegalIntVT)) {
32540b57cec5SDimitry Andric       unsigned NIntRegs = Context->RegClassInfo->getNumAllocatableRegs(
32550b57cec5SDimitry Andric         TLI->getRegClassFor(LegalIntVT));
32560b57cec5SDimitry Andric       RegionPolicy.ShouldTrackPressure = NumRegionInstrs > (NIntRegs / 2);
32570b57cec5SDimitry Andric     }
32580b57cec5SDimitry Andric   }
32590b57cec5SDimitry Andric 
32600b57cec5SDimitry Andric   // For generic targets, we default to bottom-up, because it's simpler and more
32610b57cec5SDimitry Andric   // compile-time optimizations have been implemented in that direction.
32620b57cec5SDimitry Andric   RegionPolicy.OnlyBottomUp = true;
32630b57cec5SDimitry Andric 
32640b57cec5SDimitry Andric   // Allow the subtarget to override default policy.
32650b57cec5SDimitry Andric   MF.getSubtarget().overrideSchedPolicy(RegionPolicy, NumRegionInstrs);
32660b57cec5SDimitry Andric 
32670b57cec5SDimitry Andric   // After subtarget overrides, apply command line options.
32680b57cec5SDimitry Andric   if (!EnableRegPressure) {
32690b57cec5SDimitry Andric     RegionPolicy.ShouldTrackPressure = false;
32700b57cec5SDimitry Andric     RegionPolicy.ShouldTrackLaneMasks = false;
32710b57cec5SDimitry Andric   }
32720b57cec5SDimitry Andric 
32730b57cec5SDimitry Andric   // Check -misched-topdown/bottomup can force or unforce scheduling direction.
32740b57cec5SDimitry Andric   // e.g. -misched-bottomup=false allows scheduling in both directions.
32750b57cec5SDimitry Andric   assert((!ForceTopDown || !ForceBottomUp) &&
32760b57cec5SDimitry Andric          "-misched-topdown incompatible with -misched-bottomup");
32770b57cec5SDimitry Andric   if (ForceBottomUp.getNumOccurrences() > 0) {
32780b57cec5SDimitry Andric     RegionPolicy.OnlyBottomUp = ForceBottomUp;
32790b57cec5SDimitry Andric     if (RegionPolicy.OnlyBottomUp)
32800b57cec5SDimitry Andric       RegionPolicy.OnlyTopDown = false;
32810b57cec5SDimitry Andric   }
32820b57cec5SDimitry Andric   if (ForceTopDown.getNumOccurrences() > 0) {
32830b57cec5SDimitry Andric     RegionPolicy.OnlyTopDown = ForceTopDown;
32840b57cec5SDimitry Andric     if (RegionPolicy.OnlyTopDown)
32850b57cec5SDimitry Andric       RegionPolicy.OnlyBottomUp = false;
32860b57cec5SDimitry Andric   }
32870b57cec5SDimitry Andric }
32880b57cec5SDimitry Andric 
dumpPolicy() const32890b57cec5SDimitry Andric void GenericScheduler::dumpPolicy() const {
32900b57cec5SDimitry Andric   // Cannot completely remove virtual function even in release mode.
32910b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
32920b57cec5SDimitry Andric   dbgs() << "GenericScheduler RegionPolicy: "
32930b57cec5SDimitry Andric          << " ShouldTrackPressure=" << RegionPolicy.ShouldTrackPressure
32940b57cec5SDimitry Andric          << " OnlyTopDown=" << RegionPolicy.OnlyTopDown
32950b57cec5SDimitry Andric          << " OnlyBottomUp=" << RegionPolicy.OnlyBottomUp
32960b57cec5SDimitry Andric          << "\n";
32970b57cec5SDimitry Andric #endif
32980b57cec5SDimitry Andric }
32990b57cec5SDimitry Andric 
33000b57cec5SDimitry Andric /// Set IsAcyclicLatencyLimited if the acyclic path is longer than the cyclic
33010b57cec5SDimitry Andric /// critical path by more cycles than it takes to drain the instruction buffer.
33020b57cec5SDimitry Andric /// We estimate an upper bounds on in-flight instructions as:
33030b57cec5SDimitry Andric ///
33040b57cec5SDimitry Andric /// CyclesPerIteration = max( CyclicPath, Loop-Resource-Height )
33050b57cec5SDimitry Andric /// InFlightIterations = AcyclicPath / CyclesPerIteration
33060b57cec5SDimitry Andric /// InFlightResources = InFlightIterations * LoopResources
33070b57cec5SDimitry Andric ///
33080b57cec5SDimitry Andric /// TODO: Check execution resources in addition to IssueCount.
checkAcyclicLatency()33090b57cec5SDimitry Andric void GenericScheduler::checkAcyclicLatency() {
33100b57cec5SDimitry Andric   if (Rem.CyclicCritPath == 0 || Rem.CyclicCritPath >= Rem.CriticalPath)
33110b57cec5SDimitry Andric     return;
33120b57cec5SDimitry Andric 
33130b57cec5SDimitry Andric   // Scaled number of cycles per loop iteration.
33140b57cec5SDimitry Andric   unsigned IterCount =
33150b57cec5SDimitry Andric     std::max(Rem.CyclicCritPath * SchedModel->getLatencyFactor(),
33160b57cec5SDimitry Andric              Rem.RemIssueCount);
33170b57cec5SDimitry Andric   // Scaled acyclic critical path.
33180b57cec5SDimitry Andric   unsigned AcyclicCount = Rem.CriticalPath * SchedModel->getLatencyFactor();
33190b57cec5SDimitry Andric   // InFlightCount = (AcyclicPath / IterCycles) * InstrPerLoop
33200b57cec5SDimitry Andric   unsigned InFlightCount =
33210b57cec5SDimitry Andric     (AcyclicCount * Rem.RemIssueCount + IterCount-1) / IterCount;
33220b57cec5SDimitry Andric   unsigned BufferLimit =
33230b57cec5SDimitry Andric     SchedModel->getMicroOpBufferSize() * SchedModel->getMicroOpFactor();
33240b57cec5SDimitry Andric 
33250b57cec5SDimitry Andric   Rem.IsAcyclicLatencyLimited = InFlightCount > BufferLimit;
33260b57cec5SDimitry Andric 
33270b57cec5SDimitry Andric   LLVM_DEBUG(
33280b57cec5SDimitry Andric       dbgs() << "IssueCycles="
33290b57cec5SDimitry Andric              << Rem.RemIssueCount / SchedModel->getLatencyFactor() << "c "
33300b57cec5SDimitry Andric              << "IterCycles=" << IterCount / SchedModel->getLatencyFactor()
33310b57cec5SDimitry Andric              << "c NumIters=" << (AcyclicCount + IterCount - 1) / IterCount
33320b57cec5SDimitry Andric              << " InFlight=" << InFlightCount / SchedModel->getMicroOpFactor()
33330b57cec5SDimitry Andric              << "m BufferLim=" << SchedModel->getMicroOpBufferSize() << "m\n";
33340b57cec5SDimitry Andric       if (Rem.IsAcyclicLatencyLimited) dbgs() << "  ACYCLIC LATENCY LIMIT\n");
33350b57cec5SDimitry Andric }
33360b57cec5SDimitry Andric 
registerRoots()33370b57cec5SDimitry Andric void GenericScheduler::registerRoots() {
33380b57cec5SDimitry Andric   Rem.CriticalPath = DAG->ExitSU.getDepth();
33390b57cec5SDimitry Andric 
33400b57cec5SDimitry Andric   // Some roots may not feed into ExitSU. Check all of them in case.
33410b57cec5SDimitry Andric   for (const SUnit *SU : Bot.Available) {
33420b57cec5SDimitry Andric     if (SU->getDepth() > Rem.CriticalPath)
33430b57cec5SDimitry Andric       Rem.CriticalPath = SU->getDepth();
33440b57cec5SDimitry Andric   }
33450b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << '\n');
33460b57cec5SDimitry Andric   if (DumpCriticalPathLength) {
33470b57cec5SDimitry Andric     errs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << " \n";
33480b57cec5SDimitry Andric   }
33490b57cec5SDimitry Andric 
33500b57cec5SDimitry Andric   if (EnableCyclicPath && SchedModel->getMicroOpBufferSize() > 0) {
33510b57cec5SDimitry Andric     Rem.CyclicCritPath = DAG->computeCyclicCriticalPath();
33520b57cec5SDimitry Andric     checkAcyclicLatency();
33530b57cec5SDimitry Andric   }
33540b57cec5SDimitry Andric }
33550b57cec5SDimitry Andric 
33560b57cec5SDimitry 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)33570b57cec5SDimitry Andric bool tryPressure(const PressureChange &TryP,
33580b57cec5SDimitry Andric                  const PressureChange &CandP,
33590b57cec5SDimitry Andric                  GenericSchedulerBase::SchedCandidate &TryCand,
33600b57cec5SDimitry Andric                  GenericSchedulerBase::SchedCandidate &Cand,
33610b57cec5SDimitry Andric                  GenericSchedulerBase::CandReason Reason,
33620b57cec5SDimitry Andric                  const TargetRegisterInfo *TRI,
33630b57cec5SDimitry Andric                  const MachineFunction &MF) {
33640b57cec5SDimitry Andric   // If one candidate decreases and the other increases, go with it.
33650b57cec5SDimitry Andric   // Invalid candidates have UnitInc==0.
33660b57cec5SDimitry Andric   if (tryGreater(TryP.getUnitInc() < 0, CandP.getUnitInc() < 0, TryCand, Cand,
33670b57cec5SDimitry Andric                  Reason)) {
33680b57cec5SDimitry Andric     return true;
33690b57cec5SDimitry Andric   }
33700b57cec5SDimitry Andric   // Do not compare the magnitude of pressure changes between top and bottom
33710b57cec5SDimitry Andric   // boundary.
33720b57cec5SDimitry Andric   if (Cand.AtTop != TryCand.AtTop)
33730b57cec5SDimitry Andric     return false;
33740b57cec5SDimitry Andric 
33750b57cec5SDimitry Andric   // If both candidates affect the same set in the same boundary, go with the
33760b57cec5SDimitry Andric   // smallest increase.
33770b57cec5SDimitry Andric   unsigned TryPSet = TryP.getPSetOrMax();
33780b57cec5SDimitry Andric   unsigned CandPSet = CandP.getPSetOrMax();
33790b57cec5SDimitry Andric   if (TryPSet == CandPSet) {
33800b57cec5SDimitry Andric     return tryLess(TryP.getUnitInc(), CandP.getUnitInc(), TryCand, Cand,
33810b57cec5SDimitry Andric                    Reason);
33820b57cec5SDimitry Andric   }
33830b57cec5SDimitry Andric 
33840b57cec5SDimitry Andric   int TryRank = TryP.isValid() ? TRI->getRegPressureSetScore(MF, TryPSet) :
33850b57cec5SDimitry Andric                                  std::numeric_limits<int>::max();
33860b57cec5SDimitry Andric 
33870b57cec5SDimitry Andric   int CandRank = CandP.isValid() ? TRI->getRegPressureSetScore(MF, CandPSet) :
33880b57cec5SDimitry Andric                                    std::numeric_limits<int>::max();
33890b57cec5SDimitry Andric 
33900b57cec5SDimitry Andric   // If the candidates are decreasing pressure, reverse priority.
33910b57cec5SDimitry Andric   if (TryP.getUnitInc() < 0)
33920b57cec5SDimitry Andric     std::swap(TryRank, CandRank);
33930b57cec5SDimitry Andric   return tryGreater(TryRank, CandRank, TryCand, Cand, Reason);
33940b57cec5SDimitry Andric }
33950b57cec5SDimitry Andric 
getWeakLeft(const SUnit * SU,bool isTop)33960b57cec5SDimitry Andric unsigned getWeakLeft(const SUnit *SU, bool isTop) {
33970b57cec5SDimitry Andric   return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
33980b57cec5SDimitry Andric }
33990b57cec5SDimitry Andric 
34000b57cec5SDimitry Andric /// Minimize physical register live ranges. Regalloc wants them adjacent to
34010b57cec5SDimitry Andric /// their physreg def/use.
34020b57cec5SDimitry Andric ///
34030b57cec5SDimitry Andric /// FIXME: This is an unnecessary check on the critical path. Most are root/leaf
34040b57cec5SDimitry Andric /// copies which can be prescheduled. The rest (e.g. x86 MUL) could be bundled
34050b57cec5SDimitry Andric /// with the operation that produces or consumes the physreg. We'll do this when
34060b57cec5SDimitry Andric /// regalloc has support for parallel copies.
biasPhysReg(const SUnit * SU,bool isTop)34070b57cec5SDimitry Andric int biasPhysReg(const SUnit *SU, bool isTop) {
34080b57cec5SDimitry Andric   const MachineInstr *MI = SU->getInstr();
34090b57cec5SDimitry Andric 
34100b57cec5SDimitry Andric   if (MI->isCopy()) {
34110b57cec5SDimitry Andric     unsigned ScheduledOper = isTop ? 1 : 0;
34120b57cec5SDimitry Andric     unsigned UnscheduledOper = isTop ? 0 : 1;
34130b57cec5SDimitry Andric     // If we have already scheduled the physreg produce/consumer, immediately
34140b57cec5SDimitry Andric     // schedule the copy.
3415bdd1243dSDimitry Andric     if (MI->getOperand(ScheduledOper).getReg().isPhysical())
34160b57cec5SDimitry Andric       return 1;
34170b57cec5SDimitry Andric     // If the physreg is at the boundary, defer it. Otherwise schedule it
34180b57cec5SDimitry Andric     // immediately to free the dependent. We can hoist the copy later.
34190b57cec5SDimitry Andric     bool AtBoundary = isTop ? !SU->NumSuccsLeft : !SU->NumPredsLeft;
3420bdd1243dSDimitry Andric     if (MI->getOperand(UnscheduledOper).getReg().isPhysical())
34210b57cec5SDimitry Andric       return AtBoundary ? -1 : 1;
34220b57cec5SDimitry Andric   }
34230b57cec5SDimitry Andric 
34240b57cec5SDimitry Andric   if (MI->isMoveImmediate()) {
34250b57cec5SDimitry Andric     // If we have a move immediate and all successors have been assigned, bias
34260b57cec5SDimitry Andric     // towards scheduling this later. Make sure all register defs are to
34270b57cec5SDimitry Andric     // physical registers.
34280b57cec5SDimitry Andric     bool DoBias = true;
34290b57cec5SDimitry Andric     for (const MachineOperand &Op : MI->defs()) {
3430bdd1243dSDimitry Andric       if (Op.isReg() && !Op.getReg().isPhysical()) {
34310b57cec5SDimitry Andric         DoBias = false;
34320b57cec5SDimitry Andric         break;
34330b57cec5SDimitry Andric       }
34340b57cec5SDimitry Andric     }
34350b57cec5SDimitry Andric 
34360b57cec5SDimitry Andric     if (DoBias)
34370b57cec5SDimitry Andric       return isTop ? -1 : 1;
34380b57cec5SDimitry Andric   }
34390b57cec5SDimitry Andric 
34400b57cec5SDimitry Andric   return 0;
34410b57cec5SDimitry Andric }
34420b57cec5SDimitry Andric } // end namespace llvm
34430b57cec5SDimitry Andric 
initCandidate(SchedCandidate & Cand,SUnit * SU,bool AtTop,const RegPressureTracker & RPTracker,RegPressureTracker & TempTracker)34440b57cec5SDimitry Andric void GenericScheduler::initCandidate(SchedCandidate &Cand, SUnit *SU,
34450b57cec5SDimitry Andric                                      bool AtTop,
34460b57cec5SDimitry Andric                                      const RegPressureTracker &RPTracker,
34470b57cec5SDimitry Andric                                      RegPressureTracker &TempTracker) {
34480b57cec5SDimitry Andric   Cand.SU = SU;
34490b57cec5SDimitry Andric   Cand.AtTop = AtTop;
34500b57cec5SDimitry Andric   if (DAG->isTrackingPressure()) {
34510b57cec5SDimitry Andric     if (AtTop) {
34520b57cec5SDimitry Andric       TempTracker.getMaxDownwardPressureDelta(
34530b57cec5SDimitry Andric         Cand.SU->getInstr(),
34540b57cec5SDimitry Andric         Cand.RPDelta,
34550b57cec5SDimitry Andric         DAG->getRegionCriticalPSets(),
34560b57cec5SDimitry Andric         DAG->getRegPressure().MaxSetPressure);
34570b57cec5SDimitry Andric     } else {
34580b57cec5SDimitry Andric       if (VerifyScheduling) {
34590b57cec5SDimitry Andric         TempTracker.getMaxUpwardPressureDelta(
34600b57cec5SDimitry Andric           Cand.SU->getInstr(),
34610b57cec5SDimitry Andric           &DAG->getPressureDiff(Cand.SU),
34620b57cec5SDimitry Andric           Cand.RPDelta,
34630b57cec5SDimitry Andric           DAG->getRegionCriticalPSets(),
34640b57cec5SDimitry Andric           DAG->getRegPressure().MaxSetPressure);
34650b57cec5SDimitry Andric       } else {
34660b57cec5SDimitry Andric         RPTracker.getUpwardPressureDelta(
34670b57cec5SDimitry Andric           Cand.SU->getInstr(),
34680b57cec5SDimitry Andric           DAG->getPressureDiff(Cand.SU),
34690b57cec5SDimitry Andric           Cand.RPDelta,
34700b57cec5SDimitry Andric           DAG->getRegionCriticalPSets(),
34710b57cec5SDimitry Andric           DAG->getRegPressure().MaxSetPressure);
34720b57cec5SDimitry Andric       }
34730b57cec5SDimitry Andric     }
34740b57cec5SDimitry Andric   }
34750b57cec5SDimitry Andric   LLVM_DEBUG(if (Cand.RPDelta.Excess.isValid()) dbgs()
34760b57cec5SDimitry Andric              << "  Try  SU(" << Cand.SU->NodeNum << ") "
34770b57cec5SDimitry Andric              << TRI->getRegPressureSetName(Cand.RPDelta.Excess.getPSet()) << ":"
34780b57cec5SDimitry Andric              << Cand.RPDelta.Excess.getUnitInc() << "\n");
34790b57cec5SDimitry Andric }
34800b57cec5SDimitry Andric 
34810b57cec5SDimitry Andric /// Apply a set of heuristics to a new candidate. Heuristics are currently
34820b57cec5SDimitry Andric /// hierarchical. This may be more efficient than a graduated cost model because
34830b57cec5SDimitry Andric /// we don't need to evaluate all aspects of the model for each node in the
34840b57cec5SDimitry Andric /// queue. But it's really done to make the heuristics easier to debug and
34850b57cec5SDimitry Andric /// statistically analyze.
34860b57cec5SDimitry Andric ///
34870b57cec5SDimitry Andric /// \param Cand provides the policy and current best candidate.
34880b57cec5SDimitry Andric /// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
34890b57cec5SDimitry Andric /// \param Zone describes the scheduled zone that we are extending, or nullptr
3490fe6060f1SDimitry Andric ///             if Cand is from a different zone than TryCand.
3491fe6060f1SDimitry Andric /// \return \c true if TryCand is better than Cand (Reason is NOT NoCand)
tryCandidate(SchedCandidate & Cand,SchedCandidate & TryCand,SchedBoundary * Zone) const3492fe6060f1SDimitry Andric bool GenericScheduler::tryCandidate(SchedCandidate &Cand,
34930b57cec5SDimitry Andric                                     SchedCandidate &TryCand,
34940b57cec5SDimitry Andric                                     SchedBoundary *Zone) const {
34950b57cec5SDimitry Andric   // Initialize the candidate if needed.
34960b57cec5SDimitry Andric   if (!Cand.isValid()) {
34970b57cec5SDimitry Andric     TryCand.Reason = NodeOrder;
3498fe6060f1SDimitry Andric     return true;
34990b57cec5SDimitry Andric   }
35000b57cec5SDimitry Andric 
35010b57cec5SDimitry Andric   // Bias PhysReg Defs and copies to their uses and defined respectively.
35020b57cec5SDimitry Andric   if (tryGreater(biasPhysReg(TryCand.SU, TryCand.AtTop),
35030b57cec5SDimitry Andric                  biasPhysReg(Cand.SU, Cand.AtTop), TryCand, Cand, PhysReg))
3504fe6060f1SDimitry Andric     return TryCand.Reason != NoCand;
35050b57cec5SDimitry Andric 
35060b57cec5SDimitry Andric   // Avoid exceeding the target's limit.
35070b57cec5SDimitry Andric   if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.Excess,
35080b57cec5SDimitry Andric                                                Cand.RPDelta.Excess,
35090b57cec5SDimitry Andric                                                TryCand, Cand, RegExcess, TRI,
35100b57cec5SDimitry Andric                                                DAG->MF))
3511fe6060f1SDimitry Andric     return TryCand.Reason != NoCand;
35120b57cec5SDimitry Andric 
35130b57cec5SDimitry Andric   // Avoid increasing the max critical pressure in the scheduled region.
35140b57cec5SDimitry Andric   if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CriticalMax,
35150b57cec5SDimitry Andric                                                Cand.RPDelta.CriticalMax,
35160b57cec5SDimitry Andric                                                TryCand, Cand, RegCritical, TRI,
35170b57cec5SDimitry Andric                                                DAG->MF))
3518fe6060f1SDimitry Andric     return TryCand.Reason != NoCand;
35190b57cec5SDimitry Andric 
35200b57cec5SDimitry Andric   // We only compare a subset of features when comparing nodes between
35210b57cec5SDimitry Andric   // Top and Bottom boundary. Some properties are simply incomparable, in many
35220b57cec5SDimitry Andric   // other instances we should only override the other boundary if something
35230b57cec5SDimitry Andric   // is a clear good pick on one boundary. Skip heuristics that are more
35240b57cec5SDimitry Andric   // "tie-breaking" in nature.
35250b57cec5SDimitry Andric   bool SameBoundary = Zone != nullptr;
35260b57cec5SDimitry Andric   if (SameBoundary) {
35270b57cec5SDimitry Andric     // For loops that are acyclic path limited, aggressively schedule for
35280b57cec5SDimitry Andric     // latency. Within an single cycle, whenever CurrMOps > 0, allow normal
35290b57cec5SDimitry Andric     // heuristics to take precedence.
35300b57cec5SDimitry Andric     if (Rem.IsAcyclicLatencyLimited && !Zone->getCurrMOps() &&
35310b57cec5SDimitry Andric         tryLatency(TryCand, Cand, *Zone))
3532fe6060f1SDimitry Andric       return TryCand.Reason != NoCand;
35330b57cec5SDimitry Andric 
35340b57cec5SDimitry Andric     // Prioritize instructions that read unbuffered resources by stall cycles.
35350b57cec5SDimitry Andric     if (tryLess(Zone->getLatencyStallCycles(TryCand.SU),
35360b57cec5SDimitry Andric                 Zone->getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
3537fe6060f1SDimitry Andric       return TryCand.Reason != NoCand;
35380b57cec5SDimitry Andric   }
35390b57cec5SDimitry Andric 
35400b57cec5SDimitry Andric   // Keep clustered nodes together to encourage downstream peephole
35410b57cec5SDimitry Andric   // optimizations which may reduce resource requirements.
35420b57cec5SDimitry Andric   //
35430b57cec5SDimitry Andric   // This is a best effort to set things up for a post-RA pass. Optimizations
35440b57cec5SDimitry Andric   // like generating loads of multiple registers should ideally be done within
35450b57cec5SDimitry Andric   // the scheduler pass by combining the loads during DAG postprocessing.
35460b57cec5SDimitry Andric   const SUnit *CandNextClusterSU =
35470b57cec5SDimitry Andric     Cand.AtTop ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
35480b57cec5SDimitry Andric   const SUnit *TryCandNextClusterSU =
35490b57cec5SDimitry Andric     TryCand.AtTop ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
35500b57cec5SDimitry Andric   if (tryGreater(TryCand.SU == TryCandNextClusterSU,
35510b57cec5SDimitry Andric                  Cand.SU == CandNextClusterSU,
35520b57cec5SDimitry Andric                  TryCand, Cand, Cluster))
3553fe6060f1SDimitry Andric     return TryCand.Reason != NoCand;
35540b57cec5SDimitry Andric 
35550b57cec5SDimitry Andric   if (SameBoundary) {
35560b57cec5SDimitry Andric     // Weak edges are for clustering and other constraints.
35570b57cec5SDimitry Andric     if (tryLess(getWeakLeft(TryCand.SU, TryCand.AtTop),
35580b57cec5SDimitry Andric                 getWeakLeft(Cand.SU, Cand.AtTop),
35590b57cec5SDimitry Andric                 TryCand, Cand, Weak))
3560fe6060f1SDimitry Andric       return TryCand.Reason != NoCand;
35610b57cec5SDimitry Andric   }
35620b57cec5SDimitry Andric 
35630b57cec5SDimitry Andric   // Avoid increasing the max pressure of the entire region.
35640b57cec5SDimitry Andric   if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CurrentMax,
35650b57cec5SDimitry Andric                                                Cand.RPDelta.CurrentMax,
35660b57cec5SDimitry Andric                                                TryCand, Cand, RegMax, TRI,
35670b57cec5SDimitry Andric                                                DAG->MF))
3568fe6060f1SDimitry Andric     return TryCand.Reason != NoCand;
35690b57cec5SDimitry Andric 
35700b57cec5SDimitry Andric   if (SameBoundary) {
35710b57cec5SDimitry Andric     // Avoid critical resource consumption and balance the schedule.
35720b57cec5SDimitry Andric     TryCand.initResourceDelta(DAG, SchedModel);
35730b57cec5SDimitry Andric     if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
35740b57cec5SDimitry Andric                 TryCand, Cand, ResourceReduce))
3575fe6060f1SDimitry Andric       return TryCand.Reason != NoCand;
35760b57cec5SDimitry Andric     if (tryGreater(TryCand.ResDelta.DemandedResources,
35770b57cec5SDimitry Andric                    Cand.ResDelta.DemandedResources,
35780b57cec5SDimitry Andric                    TryCand, Cand, ResourceDemand))
3579fe6060f1SDimitry Andric       return TryCand.Reason != NoCand;
35800b57cec5SDimitry Andric 
35810b57cec5SDimitry Andric     // Avoid serializing long latency dependence chains.
35820b57cec5SDimitry Andric     // For acyclic path limited loops, latency was already checked above.
35830b57cec5SDimitry Andric     if (!RegionPolicy.DisableLatencyHeuristic && TryCand.Policy.ReduceLatency &&
35840b57cec5SDimitry Andric         !Rem.IsAcyclicLatencyLimited && tryLatency(TryCand, Cand, *Zone))
3585fe6060f1SDimitry Andric       return TryCand.Reason != NoCand;
35860b57cec5SDimitry Andric 
35870b57cec5SDimitry Andric     // Fall through to original instruction order.
35880b57cec5SDimitry Andric     if ((Zone->isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
35890b57cec5SDimitry Andric         || (!Zone->isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
35900b57cec5SDimitry Andric       TryCand.Reason = NodeOrder;
3591fe6060f1SDimitry Andric       return true;
35920b57cec5SDimitry Andric     }
35930b57cec5SDimitry Andric   }
3594fe6060f1SDimitry Andric 
3595fe6060f1SDimitry Andric   return false;
35960b57cec5SDimitry Andric }
35970b57cec5SDimitry Andric 
35980b57cec5SDimitry Andric /// Pick the best candidate from the queue.
35990b57cec5SDimitry Andric ///
36000b57cec5SDimitry Andric /// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
36010b57cec5SDimitry Andric /// DAG building. To adjust for the current scheduling location we need to
36020b57cec5SDimitry Andric /// maintain the number of vreg uses remaining to be top-scheduled.
pickNodeFromQueue(SchedBoundary & Zone,const CandPolicy & ZonePolicy,const RegPressureTracker & RPTracker,SchedCandidate & Cand)36030b57cec5SDimitry Andric void GenericScheduler::pickNodeFromQueue(SchedBoundary &Zone,
36040b57cec5SDimitry Andric                                          const CandPolicy &ZonePolicy,
36050b57cec5SDimitry Andric                                          const RegPressureTracker &RPTracker,
36060b57cec5SDimitry Andric                                          SchedCandidate &Cand) {
36070b57cec5SDimitry Andric   // getMaxPressureDelta temporarily modifies the tracker.
36080b57cec5SDimitry Andric   RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
36090b57cec5SDimitry Andric 
36100b57cec5SDimitry Andric   ReadyQueue &Q = Zone.Available;
36110b57cec5SDimitry Andric   for (SUnit *SU : Q) {
36120b57cec5SDimitry Andric 
36130b57cec5SDimitry Andric     SchedCandidate TryCand(ZonePolicy);
36140b57cec5SDimitry Andric     initCandidate(TryCand, SU, Zone.isTop(), RPTracker, TempTracker);
36150b57cec5SDimitry Andric     // Pass SchedBoundary only when comparing nodes from the same boundary.
36160b57cec5SDimitry Andric     SchedBoundary *ZoneArg = Cand.AtTop == TryCand.AtTop ? &Zone : nullptr;
3617fe6060f1SDimitry Andric     if (tryCandidate(Cand, TryCand, ZoneArg)) {
36180b57cec5SDimitry Andric       // Initialize resource delta if needed in case future heuristics query it.
36190b57cec5SDimitry Andric       if (TryCand.ResDelta == SchedResourceDelta())
36200b57cec5SDimitry Andric         TryCand.initResourceDelta(DAG, SchedModel);
36210b57cec5SDimitry Andric       Cand.setBest(TryCand);
36220b57cec5SDimitry Andric       LLVM_DEBUG(traceCandidate(Cand));
36230b57cec5SDimitry Andric     }
36240b57cec5SDimitry Andric   }
36250b57cec5SDimitry Andric }
36260b57cec5SDimitry Andric 
36270b57cec5SDimitry Andric /// Pick the best candidate node from either the top or bottom queue.
pickNodeBidirectional(bool & IsTopNode)36280b57cec5SDimitry Andric SUnit *GenericScheduler::pickNodeBidirectional(bool &IsTopNode) {
36290b57cec5SDimitry Andric   // Schedule as far as possible in the direction of no choice. This is most
36300b57cec5SDimitry Andric   // efficient, but also provides the best heuristics for CriticalPSets.
36310b57cec5SDimitry Andric   if (SUnit *SU = Bot.pickOnlyChoice()) {
36320b57cec5SDimitry Andric     IsTopNode = false;
36330b57cec5SDimitry Andric     tracePick(Only1, false);
36340b57cec5SDimitry Andric     return SU;
36350b57cec5SDimitry Andric   }
36360b57cec5SDimitry Andric   if (SUnit *SU = Top.pickOnlyChoice()) {
36370b57cec5SDimitry Andric     IsTopNode = true;
36380b57cec5SDimitry Andric     tracePick(Only1, true);
36390b57cec5SDimitry Andric     return SU;
36400b57cec5SDimitry Andric   }
36410b57cec5SDimitry Andric   // Set the bottom-up policy based on the state of the current bottom zone and
36420b57cec5SDimitry Andric   // the instructions outside the zone, including the top zone.
36430b57cec5SDimitry Andric   CandPolicy BotPolicy;
36440b57cec5SDimitry Andric   setPolicy(BotPolicy, /*IsPostRA=*/false, Bot, &Top);
36450b57cec5SDimitry Andric   // Set the top-down policy based on the state of the current top zone and
36460b57cec5SDimitry Andric   // the instructions outside the zone, including the bottom zone.
36470b57cec5SDimitry Andric   CandPolicy TopPolicy;
36480b57cec5SDimitry Andric   setPolicy(TopPolicy, /*IsPostRA=*/false, Top, &Bot);
36490b57cec5SDimitry Andric 
36500b57cec5SDimitry Andric   // See if BotCand is still valid (because we previously scheduled from Top).
36510b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Picking from Bot:\n");
36520b57cec5SDimitry Andric   if (!BotCand.isValid() || BotCand.SU->isScheduled ||
36530b57cec5SDimitry Andric       BotCand.Policy != BotPolicy) {
36540b57cec5SDimitry Andric     BotCand.reset(CandPolicy());
36550b57cec5SDimitry Andric     pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), BotCand);
36560b57cec5SDimitry Andric     assert(BotCand.Reason != NoCand && "failed to find the first candidate");
36570b57cec5SDimitry Andric   } else {
36580b57cec5SDimitry Andric     LLVM_DEBUG(traceCandidate(BotCand));
36590b57cec5SDimitry Andric #ifndef NDEBUG
36600b57cec5SDimitry Andric     if (VerifyScheduling) {
36610b57cec5SDimitry Andric       SchedCandidate TCand;
36620b57cec5SDimitry Andric       TCand.reset(CandPolicy());
36630b57cec5SDimitry Andric       pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), TCand);
36640b57cec5SDimitry Andric       assert(TCand.SU == BotCand.SU &&
36650b57cec5SDimitry Andric              "Last pick result should correspond to re-picking right now");
36660b57cec5SDimitry Andric     }
36670b57cec5SDimitry Andric #endif
36680b57cec5SDimitry Andric   }
36690b57cec5SDimitry Andric 
36700b57cec5SDimitry Andric   // Check if the top Q has a better candidate.
36710b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Picking from Top:\n");
36720b57cec5SDimitry Andric   if (!TopCand.isValid() || TopCand.SU->isScheduled ||
36730b57cec5SDimitry Andric       TopCand.Policy != TopPolicy) {
36740b57cec5SDimitry Andric     TopCand.reset(CandPolicy());
36750b57cec5SDimitry Andric     pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TopCand);
36760b57cec5SDimitry Andric     assert(TopCand.Reason != NoCand && "failed to find the first candidate");
36770b57cec5SDimitry Andric   } else {
36780b57cec5SDimitry Andric     LLVM_DEBUG(traceCandidate(TopCand));
36790b57cec5SDimitry Andric #ifndef NDEBUG
36800b57cec5SDimitry Andric     if (VerifyScheduling) {
36810b57cec5SDimitry Andric       SchedCandidate TCand;
36820b57cec5SDimitry Andric       TCand.reset(CandPolicy());
36830b57cec5SDimitry Andric       pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TCand);
36840b57cec5SDimitry Andric       assert(TCand.SU == TopCand.SU &&
36850b57cec5SDimitry Andric            "Last pick result should correspond to re-picking right now");
36860b57cec5SDimitry Andric     }
36870b57cec5SDimitry Andric #endif
36880b57cec5SDimitry Andric   }
36890b57cec5SDimitry Andric 
36900b57cec5SDimitry Andric   // Pick best from BotCand and TopCand.
36910b57cec5SDimitry Andric   assert(BotCand.isValid());
36920b57cec5SDimitry Andric   assert(TopCand.isValid());
36930b57cec5SDimitry Andric   SchedCandidate Cand = BotCand;
36940b57cec5SDimitry Andric   TopCand.Reason = NoCand;
3695fe6060f1SDimitry Andric   if (tryCandidate(Cand, TopCand, nullptr)) {
36960b57cec5SDimitry Andric     Cand.setBest(TopCand);
36970b57cec5SDimitry Andric     LLVM_DEBUG(traceCandidate(Cand));
36980b57cec5SDimitry Andric   }
36990b57cec5SDimitry Andric 
37000b57cec5SDimitry Andric   IsTopNode = Cand.AtTop;
37010b57cec5SDimitry Andric   tracePick(Cand);
37020b57cec5SDimitry Andric   return Cand.SU;
37030b57cec5SDimitry Andric }
37040b57cec5SDimitry Andric 
37050b57cec5SDimitry Andric /// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
pickNode(bool & IsTopNode)37060b57cec5SDimitry Andric SUnit *GenericScheduler::pickNode(bool &IsTopNode) {
37070b57cec5SDimitry Andric   if (DAG->top() == DAG->bottom()) {
37080b57cec5SDimitry Andric     assert(Top.Available.empty() && Top.Pending.empty() &&
37090b57cec5SDimitry Andric            Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
37100b57cec5SDimitry Andric     return nullptr;
37110b57cec5SDimitry Andric   }
37120b57cec5SDimitry Andric   SUnit *SU;
37130b57cec5SDimitry Andric   do {
37140b57cec5SDimitry Andric     if (RegionPolicy.OnlyTopDown) {
37150b57cec5SDimitry Andric       SU = Top.pickOnlyChoice();
37160b57cec5SDimitry Andric       if (!SU) {
37170b57cec5SDimitry Andric         CandPolicy NoPolicy;
37180b57cec5SDimitry Andric         TopCand.reset(NoPolicy);
37190b57cec5SDimitry Andric         pickNodeFromQueue(Top, NoPolicy, DAG->getTopRPTracker(), TopCand);
37200b57cec5SDimitry Andric         assert(TopCand.Reason != NoCand && "failed to find a candidate");
37210b57cec5SDimitry Andric         tracePick(TopCand);
37220b57cec5SDimitry Andric         SU = TopCand.SU;
37230b57cec5SDimitry Andric       }
37240b57cec5SDimitry Andric       IsTopNode = true;
37250b57cec5SDimitry Andric     } else if (RegionPolicy.OnlyBottomUp) {
37260b57cec5SDimitry Andric       SU = Bot.pickOnlyChoice();
37270b57cec5SDimitry Andric       if (!SU) {
37280b57cec5SDimitry Andric         CandPolicy NoPolicy;
37290b57cec5SDimitry Andric         BotCand.reset(NoPolicy);
37300b57cec5SDimitry Andric         pickNodeFromQueue(Bot, NoPolicy, DAG->getBotRPTracker(), BotCand);
37310b57cec5SDimitry Andric         assert(BotCand.Reason != NoCand && "failed to find a candidate");
37320b57cec5SDimitry Andric         tracePick(BotCand);
37330b57cec5SDimitry Andric         SU = BotCand.SU;
37340b57cec5SDimitry Andric       }
37350b57cec5SDimitry Andric       IsTopNode = false;
37360b57cec5SDimitry Andric     } else {
37370b57cec5SDimitry Andric       SU = pickNodeBidirectional(IsTopNode);
37380b57cec5SDimitry Andric     }
37390b57cec5SDimitry Andric   } while (SU->isScheduled);
37400b57cec5SDimitry Andric 
37410b57cec5SDimitry Andric   if (SU->isTopReady())
37420b57cec5SDimitry Andric     Top.removeReady(SU);
37430b57cec5SDimitry Andric   if (SU->isBottomReady())
37440b57cec5SDimitry Andric     Bot.removeReady(SU);
37450b57cec5SDimitry Andric 
37460b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") "
37470b57cec5SDimitry Andric                     << *SU->getInstr());
37480b57cec5SDimitry Andric   return SU;
37490b57cec5SDimitry Andric }
37500b57cec5SDimitry Andric 
reschedulePhysReg(SUnit * SU,bool isTop)37510b57cec5SDimitry Andric void GenericScheduler::reschedulePhysReg(SUnit *SU, bool isTop) {
37520b57cec5SDimitry Andric   MachineBasicBlock::iterator InsertPos = SU->getInstr();
37530b57cec5SDimitry Andric   if (!isTop)
37540b57cec5SDimitry Andric     ++InsertPos;
37550b57cec5SDimitry Andric   SmallVectorImpl<SDep> &Deps = isTop ? SU->Preds : SU->Succs;
37560b57cec5SDimitry Andric 
37570b57cec5SDimitry Andric   // Find already scheduled copies with a single physreg dependence and move
37580b57cec5SDimitry Andric   // them just above the scheduled instruction.
37590b57cec5SDimitry Andric   for (SDep &Dep : Deps) {
37608bcb0991SDimitry Andric     if (Dep.getKind() != SDep::Data ||
37618bcb0991SDimitry Andric         !Register::isPhysicalRegister(Dep.getReg()))
37620b57cec5SDimitry Andric       continue;
37630b57cec5SDimitry Andric     SUnit *DepSU = Dep.getSUnit();
37640b57cec5SDimitry Andric     if (isTop ? DepSU->Succs.size() > 1 : DepSU->Preds.size() > 1)
37650b57cec5SDimitry Andric       continue;
37660b57cec5SDimitry Andric     MachineInstr *Copy = DepSU->getInstr();
37670b57cec5SDimitry Andric     if (!Copy->isCopy() && !Copy->isMoveImmediate())
37680b57cec5SDimitry Andric       continue;
37690b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "  Rescheduling physreg copy ";
37700b57cec5SDimitry Andric                DAG->dumpNode(*Dep.getSUnit()));
37710b57cec5SDimitry Andric     DAG->moveInstruction(Copy, InsertPos);
37720b57cec5SDimitry Andric   }
37730b57cec5SDimitry Andric }
37740b57cec5SDimitry Andric 
37750b57cec5SDimitry Andric /// Update the scheduler's state after scheduling a node. This is the same node
37760b57cec5SDimitry Andric /// that was just returned by pickNode(). However, ScheduleDAGMILive needs to
37770b57cec5SDimitry Andric /// update it's state based on the current cycle before MachineSchedStrategy
37780b57cec5SDimitry Andric /// does.
37790b57cec5SDimitry Andric ///
37800b57cec5SDimitry Andric /// FIXME: Eventually, we may bundle physreg copies rather than rescheduling
37810b57cec5SDimitry Andric /// them here. See comments in biasPhysReg.
schedNode(SUnit * SU,bool IsTopNode)37820b57cec5SDimitry Andric void GenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
37830b57cec5SDimitry Andric   if (IsTopNode) {
37840b57cec5SDimitry Andric     SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
37850b57cec5SDimitry Andric     Top.bumpNode(SU);
37860b57cec5SDimitry Andric     if (SU->hasPhysRegUses)
37870b57cec5SDimitry Andric       reschedulePhysReg(SU, true);
37880b57cec5SDimitry Andric   } else {
37890b57cec5SDimitry Andric     SU->BotReadyCycle = std::max(SU->BotReadyCycle, Bot.getCurrCycle());
37900b57cec5SDimitry Andric     Bot.bumpNode(SU);
37910b57cec5SDimitry Andric     if (SU->hasPhysRegDefs)
37920b57cec5SDimitry Andric       reschedulePhysReg(SU, false);
37930b57cec5SDimitry Andric   }
37940b57cec5SDimitry Andric }
37950b57cec5SDimitry Andric 
37960b57cec5SDimitry Andric /// Create the standard converging machine scheduler. This will be used as the
37970b57cec5SDimitry Andric /// default scheduler if the target does not set a default.
createGenericSchedLive(MachineSchedContext * C)37980b57cec5SDimitry Andric ScheduleDAGMILive *llvm::createGenericSchedLive(MachineSchedContext *C) {
37990b57cec5SDimitry Andric   ScheduleDAGMILive *DAG =
38008bcb0991SDimitry Andric       new ScheduleDAGMILive(C, std::make_unique<GenericScheduler>(C));
38010b57cec5SDimitry Andric   // Register DAG post-processors.
38020b57cec5SDimitry Andric   //
38030b57cec5SDimitry Andric   // FIXME: extend the mutation API to allow earlier mutations to instantiate
38040b57cec5SDimitry Andric   // data and pass it to later mutations. Have a single mutation that gathers
38050b57cec5SDimitry Andric   // the interesting nodes in one pass.
38060b57cec5SDimitry Andric   DAG->addMutation(createCopyConstrainDAGMutation(DAG->TII, DAG->TRI));
38070b57cec5SDimitry Andric   return DAG;
38080b57cec5SDimitry Andric }
38090b57cec5SDimitry Andric 
createConvergingSched(MachineSchedContext * C)3810e8d8bef9SDimitry Andric static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C) {
38110b57cec5SDimitry Andric   return createGenericSchedLive(C);
38120b57cec5SDimitry Andric }
38130b57cec5SDimitry Andric 
38140b57cec5SDimitry Andric static MachineSchedRegistry
38150b57cec5SDimitry Andric GenericSchedRegistry("converge", "Standard converging scheduler.",
3816e8d8bef9SDimitry Andric                      createConvergingSched);
38170b57cec5SDimitry Andric 
38180b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
38190b57cec5SDimitry Andric // PostGenericScheduler - Generic PostRA implementation of MachineSchedStrategy.
38200b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
38210b57cec5SDimitry Andric 
initialize(ScheduleDAGMI * Dag)38220b57cec5SDimitry Andric void PostGenericScheduler::initialize(ScheduleDAGMI *Dag) {
38230b57cec5SDimitry Andric   DAG = Dag;
38240b57cec5SDimitry Andric   SchedModel = DAG->getSchedModel();
38250b57cec5SDimitry Andric   TRI = DAG->TRI;
38260b57cec5SDimitry Andric 
38270b57cec5SDimitry Andric   Rem.init(DAG, SchedModel);
38280b57cec5SDimitry Andric   Top.init(DAG, SchedModel, &Rem);
38290b57cec5SDimitry Andric   BotRoots.clear();
38300b57cec5SDimitry Andric 
38310b57cec5SDimitry Andric   // Initialize the HazardRecognizers. If itineraries don't exist, are empty,
38320b57cec5SDimitry Andric   // or are disabled, then these HazardRecs will be disabled.
38330b57cec5SDimitry Andric   const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
38340b57cec5SDimitry Andric   if (!Top.HazardRec) {
38350b57cec5SDimitry Andric     Top.HazardRec =
38360b57cec5SDimitry Andric         DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
38370b57cec5SDimitry Andric             Itin, DAG);
38380b57cec5SDimitry Andric   }
38390b57cec5SDimitry Andric }
38400b57cec5SDimitry Andric 
registerRoots()38410b57cec5SDimitry Andric void PostGenericScheduler::registerRoots() {
38420b57cec5SDimitry Andric   Rem.CriticalPath = DAG->ExitSU.getDepth();
38430b57cec5SDimitry Andric 
38440b57cec5SDimitry Andric   // Some roots may not feed into ExitSU. Check all of them in case.
38450b57cec5SDimitry Andric   for (const SUnit *SU : BotRoots) {
38460b57cec5SDimitry Andric     if (SU->getDepth() > Rem.CriticalPath)
38470b57cec5SDimitry Andric       Rem.CriticalPath = SU->getDepth();
38480b57cec5SDimitry Andric   }
38490b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Critical Path: (PGS-RR) " << Rem.CriticalPath << '\n');
38500b57cec5SDimitry Andric   if (DumpCriticalPathLength) {
38510b57cec5SDimitry Andric     errs() << "Critical Path(PGS-RR ): " << Rem.CriticalPath << " \n";
38520b57cec5SDimitry Andric   }
38530b57cec5SDimitry Andric }
38540b57cec5SDimitry Andric 
38550b57cec5SDimitry Andric /// Apply a set of heuristics to a new candidate for PostRA scheduling.
38560b57cec5SDimitry Andric ///
38570b57cec5SDimitry Andric /// \param Cand provides the policy and current best candidate.
38580b57cec5SDimitry Andric /// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
3859fe6060f1SDimitry Andric /// \return \c true if TryCand is better than Cand (Reason is NOT NoCand)
tryCandidate(SchedCandidate & Cand,SchedCandidate & TryCand)3860fe6060f1SDimitry Andric bool PostGenericScheduler::tryCandidate(SchedCandidate &Cand,
38610b57cec5SDimitry Andric                                         SchedCandidate &TryCand) {
38620b57cec5SDimitry Andric   // Initialize the candidate if needed.
38630b57cec5SDimitry Andric   if (!Cand.isValid()) {
38640b57cec5SDimitry Andric     TryCand.Reason = NodeOrder;
3865fe6060f1SDimitry Andric     return true;
38660b57cec5SDimitry Andric   }
38670b57cec5SDimitry Andric 
38680b57cec5SDimitry Andric   // Prioritize instructions that read unbuffered resources by stall cycles.
38690b57cec5SDimitry Andric   if (tryLess(Top.getLatencyStallCycles(TryCand.SU),
38700b57cec5SDimitry Andric               Top.getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
3871fe6060f1SDimitry Andric     return TryCand.Reason != NoCand;
38720b57cec5SDimitry Andric 
38730b57cec5SDimitry Andric   // Keep clustered nodes together.
38740b57cec5SDimitry Andric   if (tryGreater(TryCand.SU == DAG->getNextClusterSucc(),
38750b57cec5SDimitry Andric                  Cand.SU == DAG->getNextClusterSucc(),
38760b57cec5SDimitry Andric                  TryCand, Cand, Cluster))
3877fe6060f1SDimitry Andric     return TryCand.Reason != NoCand;
38780b57cec5SDimitry Andric 
38790b57cec5SDimitry Andric   // Avoid critical resource consumption and balance the schedule.
38800b57cec5SDimitry Andric   if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
38810b57cec5SDimitry Andric               TryCand, Cand, ResourceReduce))
3882fe6060f1SDimitry Andric     return TryCand.Reason != NoCand;
38830b57cec5SDimitry Andric   if (tryGreater(TryCand.ResDelta.DemandedResources,
38840b57cec5SDimitry Andric                  Cand.ResDelta.DemandedResources,
38850b57cec5SDimitry Andric                  TryCand, Cand, ResourceDemand))
3886fe6060f1SDimitry Andric     return TryCand.Reason != NoCand;
38870b57cec5SDimitry Andric 
38880b57cec5SDimitry Andric   // Avoid serializing long latency dependence chains.
38890b57cec5SDimitry Andric   if (Cand.Policy.ReduceLatency && tryLatency(TryCand, Cand, Top)) {
3890fe6060f1SDimitry Andric     return TryCand.Reason != NoCand;
38910b57cec5SDimitry Andric   }
38920b57cec5SDimitry Andric 
38930b57cec5SDimitry Andric   // Fall through to original instruction order.
3894fe6060f1SDimitry Andric   if (TryCand.SU->NodeNum < Cand.SU->NodeNum) {
38950b57cec5SDimitry Andric     TryCand.Reason = NodeOrder;
3896fe6060f1SDimitry Andric     return true;
3897fe6060f1SDimitry Andric   }
3898fe6060f1SDimitry Andric 
3899fe6060f1SDimitry Andric   return false;
39000b57cec5SDimitry Andric }
39010b57cec5SDimitry Andric 
pickNodeFromQueue(SchedCandidate & Cand)39020b57cec5SDimitry Andric void PostGenericScheduler::pickNodeFromQueue(SchedCandidate &Cand) {
39030b57cec5SDimitry Andric   ReadyQueue &Q = Top.Available;
39040b57cec5SDimitry Andric   for (SUnit *SU : Q) {
39050b57cec5SDimitry Andric     SchedCandidate TryCand(Cand.Policy);
39060b57cec5SDimitry Andric     TryCand.SU = SU;
39070b57cec5SDimitry Andric     TryCand.AtTop = true;
39080b57cec5SDimitry Andric     TryCand.initResourceDelta(DAG, SchedModel);
3909fe6060f1SDimitry Andric     if (tryCandidate(Cand, TryCand)) {
39100b57cec5SDimitry Andric       Cand.setBest(TryCand);
39110b57cec5SDimitry Andric       LLVM_DEBUG(traceCandidate(Cand));
39120b57cec5SDimitry Andric     }
39130b57cec5SDimitry Andric   }
39140b57cec5SDimitry Andric }
39150b57cec5SDimitry Andric 
39160b57cec5SDimitry Andric /// Pick the next node to schedule.
pickNode(bool & IsTopNode)39170b57cec5SDimitry Andric SUnit *PostGenericScheduler::pickNode(bool &IsTopNode) {
39180b57cec5SDimitry Andric   if (DAG->top() == DAG->bottom()) {
39190b57cec5SDimitry Andric     assert(Top.Available.empty() && Top.Pending.empty() && "ReadyQ garbage");
39200b57cec5SDimitry Andric     return nullptr;
39210b57cec5SDimitry Andric   }
39220b57cec5SDimitry Andric   SUnit *SU;
39230b57cec5SDimitry Andric   do {
39240b57cec5SDimitry Andric     SU = Top.pickOnlyChoice();
39250b57cec5SDimitry Andric     if (SU) {
39260b57cec5SDimitry Andric       tracePick(Only1, true);
39270b57cec5SDimitry Andric     } else {
39280b57cec5SDimitry Andric       CandPolicy NoPolicy;
39290b57cec5SDimitry Andric       SchedCandidate TopCand(NoPolicy);
39300b57cec5SDimitry Andric       // Set the top-down policy based on the state of the current top zone and
39310b57cec5SDimitry Andric       // the instructions outside the zone, including the bottom zone.
39320b57cec5SDimitry Andric       setPolicy(TopCand.Policy, /*IsPostRA=*/true, Top, nullptr);
39330b57cec5SDimitry Andric       pickNodeFromQueue(TopCand);
39340b57cec5SDimitry Andric       assert(TopCand.Reason != NoCand && "failed to find a candidate");
39350b57cec5SDimitry Andric       tracePick(TopCand);
39360b57cec5SDimitry Andric       SU = TopCand.SU;
39370b57cec5SDimitry Andric     }
39380b57cec5SDimitry Andric   } while (SU->isScheduled);
39390b57cec5SDimitry Andric 
39400b57cec5SDimitry Andric   IsTopNode = true;
39410b57cec5SDimitry Andric   Top.removeReady(SU);
39420b57cec5SDimitry Andric 
39430b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") "
39440b57cec5SDimitry Andric                     << *SU->getInstr());
39450b57cec5SDimitry Andric   return SU;
39460b57cec5SDimitry Andric }
39470b57cec5SDimitry Andric 
39480b57cec5SDimitry Andric /// Called after ScheduleDAGMI has scheduled an instruction and updated
39490b57cec5SDimitry Andric /// scheduled/remaining flags in the DAG nodes.
schedNode(SUnit * SU,bool IsTopNode)39500b57cec5SDimitry Andric void PostGenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
39510b57cec5SDimitry Andric   SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
39520b57cec5SDimitry Andric   Top.bumpNode(SU);
39530b57cec5SDimitry Andric }
39540b57cec5SDimitry Andric 
createGenericSchedPostRA(MachineSchedContext * C)39550b57cec5SDimitry Andric ScheduleDAGMI *llvm::createGenericSchedPostRA(MachineSchedContext *C) {
39568bcb0991SDimitry Andric   return new ScheduleDAGMI(C, std::make_unique<PostGenericScheduler>(C),
39570b57cec5SDimitry Andric                            /*RemoveKillFlags=*/true);
39580b57cec5SDimitry Andric }
39590b57cec5SDimitry Andric 
39600b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
39610b57cec5SDimitry Andric // ILP Scheduler. Currently for experimental analysis of heuristics.
39620b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
39630b57cec5SDimitry Andric 
39640b57cec5SDimitry Andric namespace {
39650b57cec5SDimitry Andric 
39660b57cec5SDimitry Andric /// Order nodes by the ILP metric.
39670b57cec5SDimitry Andric struct ILPOrder {
39680b57cec5SDimitry Andric   const SchedDFSResult *DFSResult = nullptr;
39690b57cec5SDimitry Andric   const BitVector *ScheduledTrees = nullptr;
39700b57cec5SDimitry Andric   bool MaximizeILP;
39710b57cec5SDimitry Andric 
ILPOrder__anon83be91fe0711::ILPOrder39720b57cec5SDimitry Andric   ILPOrder(bool MaxILP) : MaximizeILP(MaxILP) {}
39730b57cec5SDimitry Andric 
39740b57cec5SDimitry Andric   /// Apply a less-than relation on node priority.
39750b57cec5SDimitry Andric   ///
39760b57cec5SDimitry Andric   /// (Return true if A comes after B in the Q.)
operator ()__anon83be91fe0711::ILPOrder39770b57cec5SDimitry Andric   bool operator()(const SUnit *A, const SUnit *B) const {
39780b57cec5SDimitry Andric     unsigned SchedTreeA = DFSResult->getSubtreeID(A);
39790b57cec5SDimitry Andric     unsigned SchedTreeB = DFSResult->getSubtreeID(B);
39800b57cec5SDimitry Andric     if (SchedTreeA != SchedTreeB) {
39810b57cec5SDimitry Andric       // Unscheduled trees have lower priority.
39820b57cec5SDimitry Andric       if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
39830b57cec5SDimitry Andric         return ScheduledTrees->test(SchedTreeB);
39840b57cec5SDimitry Andric 
3985c9157d92SDimitry Andric       // Trees with shallower connections have lower priority.
39860b57cec5SDimitry Andric       if (DFSResult->getSubtreeLevel(SchedTreeA)
39870b57cec5SDimitry Andric           != DFSResult->getSubtreeLevel(SchedTreeB)) {
39880b57cec5SDimitry Andric         return DFSResult->getSubtreeLevel(SchedTreeA)
39890b57cec5SDimitry Andric           < DFSResult->getSubtreeLevel(SchedTreeB);
39900b57cec5SDimitry Andric       }
39910b57cec5SDimitry Andric     }
39920b57cec5SDimitry Andric     if (MaximizeILP)
39930b57cec5SDimitry Andric       return DFSResult->getILP(A) < DFSResult->getILP(B);
39940b57cec5SDimitry Andric     else
39950b57cec5SDimitry Andric       return DFSResult->getILP(A) > DFSResult->getILP(B);
39960b57cec5SDimitry Andric   }
39970b57cec5SDimitry Andric };
39980b57cec5SDimitry Andric 
39990b57cec5SDimitry Andric /// Schedule based on the ILP metric.
40000b57cec5SDimitry Andric class ILPScheduler : public MachineSchedStrategy {
40010b57cec5SDimitry Andric   ScheduleDAGMILive *DAG = nullptr;
40020b57cec5SDimitry Andric   ILPOrder Cmp;
40030b57cec5SDimitry Andric 
40040b57cec5SDimitry Andric   std::vector<SUnit*> ReadyQ;
40050b57cec5SDimitry Andric 
40060b57cec5SDimitry Andric public:
ILPScheduler(bool MaximizeILP)40070b57cec5SDimitry Andric   ILPScheduler(bool MaximizeILP) : Cmp(MaximizeILP) {}
40080b57cec5SDimitry Andric 
initialize(ScheduleDAGMI * dag)40090b57cec5SDimitry Andric   void initialize(ScheduleDAGMI *dag) override {
40100b57cec5SDimitry Andric     assert(dag->hasVRegLiveness() && "ILPScheduler needs vreg liveness");
40110b57cec5SDimitry Andric     DAG = static_cast<ScheduleDAGMILive*>(dag);
40120b57cec5SDimitry Andric     DAG->computeDFSResult();
40130b57cec5SDimitry Andric     Cmp.DFSResult = DAG->getDFSResult();
40140b57cec5SDimitry Andric     Cmp.ScheduledTrees = &DAG->getScheduledTrees();
40150b57cec5SDimitry Andric     ReadyQ.clear();
40160b57cec5SDimitry Andric   }
40170b57cec5SDimitry Andric 
registerRoots()40180b57cec5SDimitry Andric   void registerRoots() override {
40190b57cec5SDimitry Andric     // Restore the heap in ReadyQ with the updated DFS results.
40200b57cec5SDimitry Andric     std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
40210b57cec5SDimitry Andric   }
40220b57cec5SDimitry Andric 
40230b57cec5SDimitry Andric   /// Implement MachineSchedStrategy interface.
40240b57cec5SDimitry Andric   /// -----------------------------------------
40250b57cec5SDimitry Andric 
40260b57cec5SDimitry Andric   /// Callback to select the highest priority node from the ready Q.
pickNode(bool & IsTopNode)40270b57cec5SDimitry Andric   SUnit *pickNode(bool &IsTopNode) override {
40280b57cec5SDimitry Andric     if (ReadyQ.empty()) return nullptr;
40290b57cec5SDimitry Andric     std::pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
40300b57cec5SDimitry Andric     SUnit *SU = ReadyQ.back();
40310b57cec5SDimitry Andric     ReadyQ.pop_back();
40320b57cec5SDimitry Andric     IsTopNode = false;
40330b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Pick node "
40340b57cec5SDimitry Andric                       << "SU(" << SU->NodeNum << ") "
40350b57cec5SDimitry Andric                       << " ILP: " << DAG->getDFSResult()->getILP(SU)
40360b57cec5SDimitry Andric                       << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU)
40370b57cec5SDimitry Andric                       << " @"
40380b57cec5SDimitry Andric                       << DAG->getDFSResult()->getSubtreeLevel(
40390b57cec5SDimitry Andric                              DAG->getDFSResult()->getSubtreeID(SU))
40400b57cec5SDimitry Andric                       << '\n'
40410b57cec5SDimitry Andric                       << "Scheduling " << *SU->getInstr());
40420b57cec5SDimitry Andric     return SU;
40430b57cec5SDimitry Andric   }
40440b57cec5SDimitry Andric 
40450b57cec5SDimitry Andric   /// Scheduler callback to notify that a new subtree is scheduled.
scheduleTree(unsigned SubtreeID)40460b57cec5SDimitry Andric   void scheduleTree(unsigned SubtreeID) override {
40470b57cec5SDimitry Andric     std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
40480b57cec5SDimitry Andric   }
40490b57cec5SDimitry Andric 
40500b57cec5SDimitry Andric   /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
40510b57cec5SDimitry Andric   /// DFSResults, and resort the priority Q.
schedNode(SUnit * SU,bool IsTopNode)40520b57cec5SDimitry Andric   void schedNode(SUnit *SU, bool IsTopNode) override {
40530b57cec5SDimitry Andric     assert(!IsTopNode && "SchedDFSResult needs bottom-up");
40540b57cec5SDimitry Andric   }
40550b57cec5SDimitry Andric 
releaseTopNode(SUnit *)40560b57cec5SDimitry Andric   void releaseTopNode(SUnit *) override { /*only called for top roots*/ }
40570b57cec5SDimitry Andric 
releaseBottomNode(SUnit * SU)40580b57cec5SDimitry Andric   void releaseBottomNode(SUnit *SU) override {
40590b57cec5SDimitry Andric     ReadyQ.push_back(SU);
40600b57cec5SDimitry Andric     std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
40610b57cec5SDimitry Andric   }
40620b57cec5SDimitry Andric };
40630b57cec5SDimitry Andric 
40640b57cec5SDimitry Andric } // end anonymous namespace
40650b57cec5SDimitry Andric 
createILPMaxScheduler(MachineSchedContext * C)40660b57cec5SDimitry Andric static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
40678bcb0991SDimitry Andric   return new ScheduleDAGMILive(C, std::make_unique<ILPScheduler>(true));
40680b57cec5SDimitry Andric }
createILPMinScheduler(MachineSchedContext * C)40690b57cec5SDimitry Andric static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
40708bcb0991SDimitry Andric   return new ScheduleDAGMILive(C, std::make_unique<ILPScheduler>(false));
40710b57cec5SDimitry Andric }
40720b57cec5SDimitry Andric 
40730b57cec5SDimitry Andric static MachineSchedRegistry ILPMaxRegistry(
40740b57cec5SDimitry Andric   "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
40750b57cec5SDimitry Andric static MachineSchedRegistry ILPMinRegistry(
40760b57cec5SDimitry Andric   "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
40770b57cec5SDimitry Andric 
40780b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
40790b57cec5SDimitry Andric // Machine Instruction Shuffler for Correctness Testing
40800b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
40810b57cec5SDimitry Andric 
40820b57cec5SDimitry Andric #ifndef NDEBUG
40830b57cec5SDimitry Andric namespace {
40840b57cec5SDimitry Andric 
40850b57cec5SDimitry Andric /// Apply a less-than relation on the node order, which corresponds to the
40860b57cec5SDimitry Andric /// instruction order prior to scheduling. IsReverse implements greater-than.
40870b57cec5SDimitry Andric template<bool IsReverse>
40880b57cec5SDimitry Andric struct SUnitOrder {
operator ()__anon83be91fe0811::SUnitOrder40890b57cec5SDimitry Andric   bool operator()(SUnit *A, SUnit *B) const {
40900b57cec5SDimitry Andric     if (IsReverse)
40910b57cec5SDimitry Andric       return A->NodeNum > B->NodeNum;
40920b57cec5SDimitry Andric     else
40930b57cec5SDimitry Andric       return A->NodeNum < B->NodeNum;
40940b57cec5SDimitry Andric   }
40950b57cec5SDimitry Andric };
40960b57cec5SDimitry Andric 
40970b57cec5SDimitry Andric /// Reorder instructions as much as possible.
40980b57cec5SDimitry Andric class InstructionShuffler : public MachineSchedStrategy {
40990b57cec5SDimitry Andric   bool IsAlternating;
41000b57cec5SDimitry Andric   bool IsTopDown;
41010b57cec5SDimitry Andric 
41020b57cec5SDimitry Andric   // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
41030b57cec5SDimitry Andric   // gives nodes with a higher number higher priority causing the latest
41040b57cec5SDimitry Andric   // instructions to be scheduled first.
41050b57cec5SDimitry Andric   PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false>>
41060b57cec5SDimitry Andric     TopQ;
41070b57cec5SDimitry Andric 
41080b57cec5SDimitry Andric   // When scheduling bottom-up, use greater-than as the queue priority.
41090b57cec5SDimitry Andric   PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true>>
41100b57cec5SDimitry Andric     BottomQ;
41110b57cec5SDimitry Andric 
41120b57cec5SDimitry Andric public:
InstructionShuffler(bool alternate,bool topdown)41130b57cec5SDimitry Andric   InstructionShuffler(bool alternate, bool topdown)
41140b57cec5SDimitry Andric     : IsAlternating(alternate), IsTopDown(topdown) {}
41150b57cec5SDimitry Andric 
initialize(ScheduleDAGMI *)41160b57cec5SDimitry Andric   void initialize(ScheduleDAGMI*) override {
41170b57cec5SDimitry Andric     TopQ.clear();
41180b57cec5SDimitry Andric     BottomQ.clear();
41190b57cec5SDimitry Andric   }
41200b57cec5SDimitry Andric 
41210b57cec5SDimitry Andric   /// Implement MachineSchedStrategy interface.
41220b57cec5SDimitry Andric   /// -----------------------------------------
41230b57cec5SDimitry Andric 
pickNode(bool & IsTopNode)41240b57cec5SDimitry Andric   SUnit *pickNode(bool &IsTopNode) override {
41250b57cec5SDimitry Andric     SUnit *SU;
41260b57cec5SDimitry Andric     if (IsTopDown) {
41270b57cec5SDimitry Andric       do {
41280b57cec5SDimitry Andric         if (TopQ.empty()) return nullptr;
41290b57cec5SDimitry Andric         SU = TopQ.top();
41300b57cec5SDimitry Andric         TopQ.pop();
41310b57cec5SDimitry Andric       } while (SU->isScheduled);
41320b57cec5SDimitry Andric       IsTopNode = true;
41330b57cec5SDimitry Andric     } else {
41340b57cec5SDimitry Andric       do {
41350b57cec5SDimitry Andric         if (BottomQ.empty()) return nullptr;
41360b57cec5SDimitry Andric         SU = BottomQ.top();
41370b57cec5SDimitry Andric         BottomQ.pop();
41380b57cec5SDimitry Andric       } while (SU->isScheduled);
41390b57cec5SDimitry Andric       IsTopNode = false;
41400b57cec5SDimitry Andric     }
41410b57cec5SDimitry Andric     if (IsAlternating)
41420b57cec5SDimitry Andric       IsTopDown = !IsTopDown;
41430b57cec5SDimitry Andric     return SU;
41440b57cec5SDimitry Andric   }
41450b57cec5SDimitry Andric 
schedNode(SUnit * SU,bool IsTopNode)41460b57cec5SDimitry Andric   void schedNode(SUnit *SU, bool IsTopNode) override {}
41470b57cec5SDimitry Andric 
releaseTopNode(SUnit * SU)41480b57cec5SDimitry Andric   void releaseTopNode(SUnit *SU) override {
41490b57cec5SDimitry Andric     TopQ.push(SU);
41500b57cec5SDimitry Andric   }
releaseBottomNode(SUnit * SU)41510b57cec5SDimitry Andric   void releaseBottomNode(SUnit *SU) override {
41520b57cec5SDimitry Andric     BottomQ.push(SU);
41530b57cec5SDimitry Andric   }
41540b57cec5SDimitry Andric };
41550b57cec5SDimitry Andric 
41560b57cec5SDimitry Andric } // end anonymous namespace
41570b57cec5SDimitry Andric 
createInstructionShuffler(MachineSchedContext * C)41580b57cec5SDimitry Andric static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
41590b57cec5SDimitry Andric   bool Alternate = !ForceTopDown && !ForceBottomUp;
41600b57cec5SDimitry Andric   bool TopDown = !ForceBottomUp;
41610b57cec5SDimitry Andric   assert((TopDown || !ForceTopDown) &&
41620b57cec5SDimitry Andric          "-misched-topdown incompatible with -misched-bottomup");
41630b57cec5SDimitry Andric   return new ScheduleDAGMILive(
41648bcb0991SDimitry Andric       C, std::make_unique<InstructionShuffler>(Alternate, TopDown));
41650b57cec5SDimitry Andric }
41660b57cec5SDimitry Andric 
41670b57cec5SDimitry Andric static MachineSchedRegistry ShufflerRegistry(
41680b57cec5SDimitry Andric   "shuffle", "Shuffle machine instructions alternating directions",
41690b57cec5SDimitry Andric   createInstructionShuffler);
41700b57cec5SDimitry Andric #endif // !NDEBUG
41710b57cec5SDimitry Andric 
41720b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
41730b57cec5SDimitry Andric // GraphWriter support for ScheduleDAGMILive.
41740b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
41750b57cec5SDimitry Andric 
41760b57cec5SDimitry Andric #ifndef NDEBUG
41770b57cec5SDimitry Andric namespace llvm {
41780b57cec5SDimitry Andric 
41790b57cec5SDimitry Andric template<> struct GraphTraits<
41800b57cec5SDimitry Andric   ScheduleDAGMI*> : public GraphTraits<ScheduleDAG*> {};
41810b57cec5SDimitry Andric 
41820b57cec5SDimitry Andric template<>
41830b57cec5SDimitry Andric struct DOTGraphTraits<ScheduleDAGMI*> : public DefaultDOTGraphTraits {
DOTGraphTraitsllvm::DOTGraphTraits41840b57cec5SDimitry Andric   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
41850b57cec5SDimitry Andric 
getGraphNamellvm::DOTGraphTraits41860b57cec5SDimitry Andric   static std::string getGraphName(const ScheduleDAG *G) {
41875ffd83dbSDimitry Andric     return std::string(G->MF.getName());
41880b57cec5SDimitry Andric   }
41890b57cec5SDimitry Andric 
renderGraphFromBottomUpllvm::DOTGraphTraits41900b57cec5SDimitry Andric   static bool renderGraphFromBottomUp() {
41910b57cec5SDimitry Andric     return true;
41920b57cec5SDimitry Andric   }
41930b57cec5SDimitry Andric 
isNodeHiddenllvm::DOTGraphTraits4194e8d8bef9SDimitry Andric   static bool isNodeHidden(const SUnit *Node, const ScheduleDAG *G) {
41950b57cec5SDimitry Andric     if (ViewMISchedCutoff == 0)
41960b57cec5SDimitry Andric       return false;
41970b57cec5SDimitry Andric     return (Node->Preds.size() > ViewMISchedCutoff
41980b57cec5SDimitry Andric          || Node->Succs.size() > ViewMISchedCutoff);
41990b57cec5SDimitry Andric   }
42000b57cec5SDimitry Andric 
42010b57cec5SDimitry Andric   /// If you want to override the dot attributes printed for a particular
42020b57cec5SDimitry Andric   /// edge, override this method.
getEdgeAttributesllvm::DOTGraphTraits42030b57cec5SDimitry Andric   static std::string getEdgeAttributes(const SUnit *Node,
42040b57cec5SDimitry Andric                                        SUnitIterator EI,
42050b57cec5SDimitry Andric                                        const ScheduleDAG *Graph) {
42060b57cec5SDimitry Andric     if (EI.isArtificialDep())
42070b57cec5SDimitry Andric       return "color=cyan,style=dashed";
42080b57cec5SDimitry Andric     if (EI.isCtrlDep())
42090b57cec5SDimitry Andric       return "color=blue,style=dashed";
42100b57cec5SDimitry Andric     return "";
42110b57cec5SDimitry Andric   }
42120b57cec5SDimitry Andric 
getNodeLabelllvm::DOTGraphTraits42130b57cec5SDimitry Andric   static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) {
42140b57cec5SDimitry Andric     std::string Str;
42150b57cec5SDimitry Andric     raw_string_ostream SS(Str);
42160b57cec5SDimitry Andric     const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
42170b57cec5SDimitry Andric     const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
42180b57cec5SDimitry Andric       static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
42190b57cec5SDimitry Andric     SS << "SU:" << SU->NodeNum;
42200b57cec5SDimitry Andric     if (DFS)
42210b57cec5SDimitry Andric       SS << " I:" << DFS->getNumInstrs(SU);
42220b57cec5SDimitry Andric     return SS.str();
42230b57cec5SDimitry Andric   }
42240b57cec5SDimitry Andric 
getNodeDescriptionllvm::DOTGraphTraits42250b57cec5SDimitry Andric   static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G) {
42260b57cec5SDimitry Andric     return G->getGraphNodeLabel(SU);
42270b57cec5SDimitry Andric   }
42280b57cec5SDimitry Andric 
getNodeAttributesllvm::DOTGraphTraits42290b57cec5SDimitry Andric   static std::string getNodeAttributes(const SUnit *N, const ScheduleDAG *G) {
42300b57cec5SDimitry Andric     std::string Str("shape=Mrecord");
42310b57cec5SDimitry Andric     const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
42320b57cec5SDimitry Andric     const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
42330b57cec5SDimitry Andric       static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
42340b57cec5SDimitry Andric     if (DFS) {
42350b57cec5SDimitry Andric       Str += ",style=filled,fillcolor=\"#";
42360b57cec5SDimitry Andric       Str += DOT::getColorString(DFS->getSubtreeID(N));
42370b57cec5SDimitry Andric       Str += '"';
42380b57cec5SDimitry Andric     }
42390b57cec5SDimitry Andric     return Str;
42400b57cec5SDimitry Andric   }
42410b57cec5SDimitry Andric };
42420b57cec5SDimitry Andric 
42430b57cec5SDimitry Andric } // end namespace llvm
42440b57cec5SDimitry Andric #endif // NDEBUG
42450b57cec5SDimitry Andric 
42460b57cec5SDimitry Andric /// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
42470b57cec5SDimitry Andric /// rendered using 'dot'.
viewGraph(const Twine & Name,const Twine & Title)42480b57cec5SDimitry Andric void ScheduleDAGMI::viewGraph(const Twine &Name, const Twine &Title) {
42490b57cec5SDimitry Andric #ifndef NDEBUG
42500b57cec5SDimitry Andric   ViewGraph(this, Name, false, Title);
42510b57cec5SDimitry Andric #else
42520b57cec5SDimitry Andric   errs() << "ScheduleDAGMI::viewGraph is only available in debug builds on "
42530b57cec5SDimitry Andric          << "systems with Graphviz or gv!\n";
42540b57cec5SDimitry Andric #endif  // NDEBUG
42550b57cec5SDimitry Andric }
42560b57cec5SDimitry Andric 
42570b57cec5SDimitry Andric /// Out-of-line implementation with no arguments is handy for gdb.
viewGraph()42580b57cec5SDimitry Andric void ScheduleDAGMI::viewGraph() {
42590b57cec5SDimitry Andric   viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName());
42600b57cec5SDimitry Andric }
4261fe013be4SDimitry Andric 
4262fe013be4SDimitry Andric /// Sort predicate for the intervals stored in an instance of
4263fe013be4SDimitry Andric /// ResourceSegments. Intervals are always disjoint (no intersection
4264fe013be4SDimitry Andric /// for any pairs of intervals), therefore we can sort the totality of
4265fe013be4SDimitry Andric /// the intervals by looking only at the left boundary.
sortIntervals(const ResourceSegments::IntervalTy & A,const ResourceSegments::IntervalTy & B)4266fe013be4SDimitry Andric static bool sortIntervals(const ResourceSegments::IntervalTy &A,
4267fe013be4SDimitry Andric                           const ResourceSegments::IntervalTy &B) {
4268fe013be4SDimitry Andric   return A.first < B.first;
4269fe013be4SDimitry Andric }
4270fe013be4SDimitry Andric 
getFirstAvailableAt(unsigned CurrCycle,unsigned AcquireAtCycle,unsigned ReleaseAtCycle,std::function<ResourceSegments::IntervalTy (unsigned,unsigned,unsigned)> IntervalBuilder) const4271fe013be4SDimitry Andric unsigned ResourceSegments::getFirstAvailableAt(
4272*a58f00eaSDimitry Andric     unsigned CurrCycle, unsigned AcquireAtCycle, unsigned ReleaseAtCycle,
4273fe013be4SDimitry Andric     std::function<ResourceSegments::IntervalTy(unsigned, unsigned, unsigned)>
4274fe013be4SDimitry Andric         IntervalBuilder) const {
4275fe013be4SDimitry Andric   assert(std::is_sorted(std::begin(_Intervals), std::end(_Intervals),
4276fe013be4SDimitry Andric                         sortIntervals) &&
4277fe013be4SDimitry Andric          "Cannot execute on an un-sorted set of intervals.");
4278fe013be4SDimitry Andric   unsigned RetCycle = CurrCycle;
4279fe013be4SDimitry Andric   ResourceSegments::IntervalTy NewInterval =
4280*a58f00eaSDimitry Andric       IntervalBuilder(RetCycle, AcquireAtCycle, ReleaseAtCycle);
4281fe013be4SDimitry Andric   for (auto &Interval : _Intervals) {
4282fe013be4SDimitry Andric     if (!intersects(NewInterval, Interval))
4283fe013be4SDimitry Andric       continue;
4284fe013be4SDimitry Andric 
4285fe013be4SDimitry Andric     // Move the interval right next to the top of the one it
4286fe013be4SDimitry Andric     // intersects.
4287fe013be4SDimitry Andric     assert(Interval.second > NewInterval.first &&
4288fe013be4SDimitry Andric            "Invalid intervals configuration.");
4289fe013be4SDimitry Andric     RetCycle += (unsigned)Interval.second - (unsigned)NewInterval.first;
4290*a58f00eaSDimitry Andric     NewInterval = IntervalBuilder(RetCycle, AcquireAtCycle, ReleaseAtCycle);
4291fe013be4SDimitry Andric   }
4292fe013be4SDimitry Andric   return RetCycle;
4293fe013be4SDimitry Andric }
4294fe013be4SDimitry Andric 
add(ResourceSegments::IntervalTy A,const unsigned CutOff)4295fe013be4SDimitry Andric void ResourceSegments::add(ResourceSegments::IntervalTy A,
4296fe013be4SDimitry Andric                            const unsigned CutOff) {
4297fe013be4SDimitry Andric   assert(A.first < A.second && "Cannot add empty resource usage");
4298fe013be4SDimitry Andric   assert(CutOff > 0 && "0-size interval history has no use.");
4299fe013be4SDimitry Andric   assert(all_of(_Intervals,
4300fe013be4SDimitry Andric                 [&A](const ResourceSegments::IntervalTy &Interval) -> bool {
4301fe013be4SDimitry Andric                   return !intersects(A, Interval);
4302fe013be4SDimitry Andric                 }) &&
4303fe013be4SDimitry Andric          "A resource is being overwritten");
4304fe013be4SDimitry Andric   _Intervals.push_back(A);
4305fe013be4SDimitry Andric 
4306fe013be4SDimitry Andric   sortAndMerge();
4307fe013be4SDimitry Andric 
4308fe013be4SDimitry Andric   // Do not keep the full history of the intervals, just the
4309fe013be4SDimitry Andric   // latest #CutOff.
4310fe013be4SDimitry Andric   while (_Intervals.size() > CutOff)
4311fe013be4SDimitry Andric     _Intervals.pop_front();
4312fe013be4SDimitry Andric }
4313fe013be4SDimitry Andric 
intersects(ResourceSegments::IntervalTy A,ResourceSegments::IntervalTy B)4314fe013be4SDimitry Andric bool ResourceSegments::intersects(ResourceSegments::IntervalTy A,
4315fe013be4SDimitry Andric                                   ResourceSegments::IntervalTy B) {
4316fe013be4SDimitry Andric   assert(A.first <= A.second && "Invalid interval");
4317fe013be4SDimitry Andric   assert(B.first <= B.second && "Invalid interval");
4318fe013be4SDimitry Andric 
4319fe013be4SDimitry Andric   // Share one boundary.
4320fe013be4SDimitry Andric   if ((A.first == B.first) || (A.second == B.second))
4321fe013be4SDimitry Andric     return true;
4322fe013be4SDimitry Andric 
4323fe013be4SDimitry Andric   // full intersersect: [    ***     )  B
4324fe013be4SDimitry Andric   //                        [***)       A
4325fe013be4SDimitry Andric   if ((A.first > B.first) && (A.second < B.second))
4326fe013be4SDimitry Andric     return true;
4327fe013be4SDimitry Andric 
4328fe013be4SDimitry Andric   // right intersect: [     ***)        B
4329fe013be4SDimitry Andric   //                       [***      )  A
4330fe013be4SDimitry Andric   if ((A.first > B.first) && (A.first < B.second) && (A.second > B.second))
4331fe013be4SDimitry Andric     return true;
4332fe013be4SDimitry Andric 
4333fe013be4SDimitry Andric   // left intersect:      [***      )  B
4334fe013be4SDimitry Andric   //                 [     ***)        A
4335fe013be4SDimitry Andric   if ((A.first < B.first) && (B.first < A.second) && (B.second > B.first))
4336fe013be4SDimitry Andric     return true;
4337fe013be4SDimitry Andric 
4338fe013be4SDimitry Andric   return false;
4339fe013be4SDimitry Andric }
4340fe013be4SDimitry Andric 
sortAndMerge()4341fe013be4SDimitry Andric void ResourceSegments::sortAndMerge() {
4342fe013be4SDimitry Andric   if (_Intervals.size() <= 1)
4343fe013be4SDimitry Andric     return;
4344fe013be4SDimitry Andric 
4345fe013be4SDimitry Andric   // First sort the collection.
4346fe013be4SDimitry Andric   _Intervals.sort(sortIntervals);
4347fe013be4SDimitry Andric 
4348fe013be4SDimitry Andric   // can use next because I have at least 2 elements in the list
4349fe013be4SDimitry Andric   auto next = std::next(std::begin(_Intervals));
4350fe013be4SDimitry Andric   auto E = std::end(_Intervals);
4351fe013be4SDimitry Andric   for (; next != E; ++next) {
4352fe013be4SDimitry Andric     if (std::prev(next)->second >= next->first) {
4353fe013be4SDimitry Andric       next->first = std::prev(next)->first;
4354fe013be4SDimitry Andric       _Intervals.erase(std::prev(next));
4355fe013be4SDimitry Andric       continue;
4356fe013be4SDimitry Andric     }
4357fe013be4SDimitry Andric   }
4358fe013be4SDimitry Andric }
4359