xref: /freebsd-src/contrib/llvm-project/llvm/lib/CodeGen/MachinePipeliner.cpp (revision 6c4b055cfb6bf549e9145dde6454cc6b178c35e4)
10b57cec5SDimitry Andric //===- MachinePipeliner.cpp - Machine Software Pipeliner Pass -------------===//
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 // An implementation of the Swing Modulo Scheduling (SMS) software pipeliner.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric // This SMS implementation is a target-independent back-end pass. When enabled,
120b57cec5SDimitry Andric // the pass runs just prior to the register allocation pass, while the machine
130b57cec5SDimitry Andric // IR is in SSA form. If software pipelining is successful, then the original
140b57cec5SDimitry Andric // loop is replaced by the optimized loop. The optimized loop contains one or
150b57cec5SDimitry Andric // more prolog blocks, the pipelined kernel, and one or more epilog blocks. If
160b57cec5SDimitry Andric // the instructions cannot be scheduled in a given MII, we increase the MII by
170b57cec5SDimitry Andric // one and try again.
180b57cec5SDimitry Andric //
190b57cec5SDimitry Andric // The SMS implementation is an extension of the ScheduleDAGInstrs class. We
200b57cec5SDimitry Andric // represent loop carried dependences in the DAG as order edges to the Phi
210b57cec5SDimitry Andric // nodes. We also perform several passes over the DAG to eliminate unnecessary
220b57cec5SDimitry Andric // edges that inhibit the ability to pipeline. The implementation uses the
230b57cec5SDimitry Andric // DFAPacketizer class to compute the minimum initiation interval and the check
240b57cec5SDimitry Andric // where an instruction may be inserted in the pipelined schedule.
250b57cec5SDimitry Andric //
260b57cec5SDimitry Andric // In order for the SMS pass to work, several target specific hooks need to be
270b57cec5SDimitry Andric // implemented to get information about the loop structure and to rewrite
280b57cec5SDimitry Andric // instructions.
290b57cec5SDimitry Andric //
300b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
310b57cec5SDimitry Andric 
3281ad6265SDimitry Andric #include "llvm/CodeGen/MachinePipeliner.h"
330b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
340b57cec5SDimitry Andric #include "llvm/ADT/BitVector.h"
350b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
360b57cec5SDimitry Andric #include "llvm/ADT/MapVector.h"
370b57cec5SDimitry Andric #include "llvm/ADT/PriorityQueue.h"
387a6dacacSDimitry Andric #include "llvm/ADT/STLExtras.h"
39fe6060f1SDimitry Andric #include "llvm/ADT/SetOperations.h"
400b57cec5SDimitry Andric #include "llvm/ADT/SetVector.h"
410b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
420b57cec5SDimitry Andric #include "llvm/ADT/SmallSet.h"
430b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
440b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
450b57cec5SDimitry Andric #include "llvm/ADT/iterator_range.h"
460b57cec5SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
47bdd1243dSDimitry Andric #include "llvm/Analysis/CycleAnalysis.h"
480b57cec5SDimitry Andric #include "llvm/Analysis/MemoryLocation.h"
4981ad6265SDimitry Andric #include "llvm/Analysis/OptimizationRemarkEmitter.h"
500b57cec5SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
510b57cec5SDimitry Andric #include "llvm/CodeGen/DFAPacketizer.h"
520b57cec5SDimitry Andric #include "llvm/CodeGen/LiveIntervals.h"
530b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
540b57cec5SDimitry Andric #include "llvm/CodeGen/MachineDominators.h"
550b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
560b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
570b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
580b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
590b57cec5SDimitry Andric #include "llvm/CodeGen/MachineLoopInfo.h"
600b57cec5SDimitry Andric #include "llvm/CodeGen/MachineMemOperand.h"
610b57cec5SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
620b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
638bcb0991SDimitry Andric #include "llvm/CodeGen/ModuloSchedule.h"
647a6dacacSDimitry Andric #include "llvm/CodeGen/Register.h"
657a6dacacSDimitry Andric #include "llvm/CodeGen/RegisterClassInfo.h"
660b57cec5SDimitry Andric #include "llvm/CodeGen/RegisterPressure.h"
670b57cec5SDimitry Andric #include "llvm/CodeGen/ScheduleDAG.h"
680b57cec5SDimitry Andric #include "llvm/CodeGen/ScheduleDAGMutation.h"
697a6dacacSDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
700b57cec5SDimitry Andric #include "llvm/CodeGen/TargetOpcodes.h"
710fca6ea1SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
720b57cec5SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
730b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
740b57cec5SDimitry Andric #include "llvm/Config/llvm-config.h"
750b57cec5SDimitry Andric #include "llvm/IR/Attributes.h"
760b57cec5SDimitry Andric #include "llvm/IR/Function.h"
770b57cec5SDimitry Andric #include "llvm/MC/LaneBitmask.h"
780b57cec5SDimitry Andric #include "llvm/MC/MCInstrDesc.h"
790b57cec5SDimitry Andric #include "llvm/MC/MCInstrItineraries.h"
800b57cec5SDimitry Andric #include "llvm/MC/MCRegisterInfo.h"
810b57cec5SDimitry Andric #include "llvm/Pass.h"
820b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
830b57cec5SDimitry Andric #include "llvm/Support/Compiler.h"
840b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
850b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
860b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
870b57cec5SDimitry Andric #include <algorithm>
880b57cec5SDimitry Andric #include <cassert>
890b57cec5SDimitry Andric #include <climits>
900b57cec5SDimitry Andric #include <cstdint>
910b57cec5SDimitry Andric #include <deque>
920b57cec5SDimitry Andric #include <functional>
93bdd1243dSDimitry Andric #include <iomanip>
940b57cec5SDimitry Andric #include <iterator>
950b57cec5SDimitry Andric #include <map>
960b57cec5SDimitry Andric #include <memory>
97bdd1243dSDimitry Andric #include <sstream>
980b57cec5SDimitry Andric #include <tuple>
990b57cec5SDimitry Andric #include <utility>
1000b57cec5SDimitry Andric #include <vector>
1010b57cec5SDimitry Andric 
1020b57cec5SDimitry Andric using namespace llvm;
1030b57cec5SDimitry Andric 
1040b57cec5SDimitry Andric #define DEBUG_TYPE "pipeliner"
1050b57cec5SDimitry Andric 
1060b57cec5SDimitry Andric STATISTIC(NumTrytoPipeline, "Number of loops that we attempt to pipeline");
1070b57cec5SDimitry Andric STATISTIC(NumPipelined, "Number of loops software pipelined");
1080b57cec5SDimitry Andric STATISTIC(NumNodeOrderIssues, "Number of node order issues found");
1090b57cec5SDimitry Andric STATISTIC(NumFailBranch, "Pipeliner abort due to unknown branch");
1100b57cec5SDimitry Andric STATISTIC(NumFailLoop, "Pipeliner abort due to unsupported loop");
1110b57cec5SDimitry Andric STATISTIC(NumFailPreheader, "Pipeliner abort due to missing preheader");
1120b57cec5SDimitry Andric STATISTIC(NumFailLargeMaxMII, "Pipeliner abort due to MaxMII too large");
1130b57cec5SDimitry Andric STATISTIC(NumFailZeroMII, "Pipeliner abort due to zero MII");
1140b57cec5SDimitry Andric STATISTIC(NumFailNoSchedule, "Pipeliner abort due to no schedule found");
1150b57cec5SDimitry Andric STATISTIC(NumFailZeroStage, "Pipeliner abort due to zero stage");
1160b57cec5SDimitry Andric STATISTIC(NumFailLargeMaxStage, "Pipeliner abort due to too many stages");
1170b57cec5SDimitry Andric 
1180b57cec5SDimitry Andric /// A command line option to turn software pipelining on or off.
1190b57cec5SDimitry Andric static cl::opt<bool> EnableSWP("enable-pipeliner", cl::Hidden, cl::init(true),
1200b57cec5SDimitry Andric                                cl::desc("Enable Software Pipelining"));
1210b57cec5SDimitry Andric 
1220b57cec5SDimitry Andric /// A command line option to enable SWP at -Os.
1230b57cec5SDimitry Andric static cl::opt<bool> EnableSWPOptSize("enable-pipeliner-opt-size",
1240b57cec5SDimitry Andric                                       cl::desc("Enable SWP at Os."), cl::Hidden,
1250b57cec5SDimitry Andric                                       cl::init(false));
1260b57cec5SDimitry Andric 
1270b57cec5SDimitry Andric /// A command line argument to limit minimum initial interval for pipelining.
1280b57cec5SDimitry Andric static cl::opt<int> SwpMaxMii("pipeliner-max-mii",
1290b57cec5SDimitry Andric                               cl::desc("Size limit for the MII."),
1300b57cec5SDimitry Andric                               cl::Hidden, cl::init(27));
1310b57cec5SDimitry Andric 
132bdd1243dSDimitry Andric /// A command line argument to force pipeliner to use specified initial
133bdd1243dSDimitry Andric /// interval.
134bdd1243dSDimitry Andric static cl::opt<int> SwpForceII("pipeliner-force-ii",
135bdd1243dSDimitry Andric                                cl::desc("Force pipeliner to use specified II."),
136bdd1243dSDimitry Andric                                cl::Hidden, cl::init(-1));
137bdd1243dSDimitry Andric 
1380b57cec5SDimitry Andric /// A command line argument to limit the number of stages in the pipeline.
1390b57cec5SDimitry Andric static cl::opt<int>
1400b57cec5SDimitry Andric     SwpMaxStages("pipeliner-max-stages",
1410b57cec5SDimitry Andric                  cl::desc("Maximum stages allowed in the generated scheduled."),
1420b57cec5SDimitry Andric                  cl::Hidden, cl::init(3));
1430b57cec5SDimitry Andric 
1440b57cec5SDimitry Andric /// A command line option to disable the pruning of chain dependences due to
1450b57cec5SDimitry Andric /// an unrelated Phi.
1460b57cec5SDimitry Andric static cl::opt<bool>
1470b57cec5SDimitry Andric     SwpPruneDeps("pipeliner-prune-deps",
1480b57cec5SDimitry Andric                  cl::desc("Prune dependences between unrelated Phi nodes."),
1490b57cec5SDimitry Andric                  cl::Hidden, cl::init(true));
1500b57cec5SDimitry Andric 
1510b57cec5SDimitry Andric /// A command line option to disable the pruning of loop carried order
1520b57cec5SDimitry Andric /// dependences.
1530b57cec5SDimitry Andric static cl::opt<bool>
1540b57cec5SDimitry Andric     SwpPruneLoopCarried("pipeliner-prune-loop-carried",
1550b57cec5SDimitry Andric                         cl::desc("Prune loop carried order dependences."),
1560b57cec5SDimitry Andric                         cl::Hidden, cl::init(true));
1570b57cec5SDimitry Andric 
1580b57cec5SDimitry Andric #ifndef NDEBUG
1590b57cec5SDimitry Andric static cl::opt<int> SwpLoopLimit("pipeliner-max", cl::Hidden, cl::init(-1));
1600b57cec5SDimitry Andric #endif
1610b57cec5SDimitry Andric 
1620b57cec5SDimitry Andric static cl::opt<bool> SwpIgnoreRecMII("pipeliner-ignore-recmii",
16381ad6265SDimitry Andric                                      cl::ReallyHidden,
16481ad6265SDimitry Andric                                      cl::desc("Ignore RecMII"));
1650b57cec5SDimitry Andric 
1660b57cec5SDimitry Andric static cl::opt<bool> SwpShowResMask("pipeliner-show-mask", cl::Hidden,
1670b57cec5SDimitry Andric                                     cl::init(false));
1680b57cec5SDimitry Andric static cl::opt<bool> SwpDebugResource("pipeliner-dbg-res", cl::Hidden,
1690b57cec5SDimitry Andric                                       cl::init(false));
1700b57cec5SDimitry Andric 
1718bcb0991SDimitry Andric static cl::opt<bool> EmitTestAnnotations(
1728bcb0991SDimitry Andric     "pipeliner-annotate-for-testing", cl::Hidden, cl::init(false),
1738bcb0991SDimitry Andric     cl::desc("Instead of emitting the pipelined code, annotate instructions "
1748bcb0991SDimitry Andric              "with the generated schedule for feeding into the "
1758bcb0991SDimitry Andric              "-modulo-schedule-test pass"));
1768bcb0991SDimitry Andric 
1778bcb0991SDimitry Andric static cl::opt<bool> ExperimentalCodeGen(
1788bcb0991SDimitry Andric     "pipeliner-experimental-cg", cl::Hidden, cl::init(false),
1798bcb0991SDimitry Andric     cl::desc(
1808bcb0991SDimitry Andric         "Use the experimental peeling code generator for software pipelining"));
1818bcb0991SDimitry Andric 
1827a6dacacSDimitry Andric static cl::opt<int> SwpIISearchRange("pipeliner-ii-search-range",
1837a6dacacSDimitry Andric                                      cl::desc("Range to search for II"),
1847a6dacacSDimitry Andric                                      cl::Hidden, cl::init(10));
1857a6dacacSDimitry Andric 
1867a6dacacSDimitry Andric static cl::opt<bool>
1877a6dacacSDimitry Andric     LimitRegPressure("pipeliner-register-pressure", cl::Hidden, cl::init(false),
1887a6dacacSDimitry Andric                      cl::desc("Limit register pressure of scheduled loop"));
1897a6dacacSDimitry Andric 
1907a6dacacSDimitry Andric static cl::opt<int>
1917a6dacacSDimitry Andric     RegPressureMargin("pipeliner-register-pressure-margin", cl::Hidden,
1927a6dacacSDimitry Andric                       cl::init(5),
1937a6dacacSDimitry Andric                       cl::desc("Margin representing the unused percentage of "
1947a6dacacSDimitry Andric                                "the register pressure limit"));
1957a6dacacSDimitry Andric 
1960fca6ea1SDimitry Andric static cl::opt<bool>
1970fca6ea1SDimitry Andric     MVECodeGen("pipeliner-mve-cg", cl::Hidden, cl::init(false),
1980fca6ea1SDimitry Andric                cl::desc("Use the MVE code generator for software pipelining"));
1990fca6ea1SDimitry Andric 
2000b57cec5SDimitry Andric namespace llvm {
2010b57cec5SDimitry Andric 
2020b57cec5SDimitry Andric // A command line option to enable the CopyToPhi DAG mutation.
20381ad6265SDimitry Andric cl::opt<bool> SwpEnableCopyToPhi("pipeliner-enable-copytophi", cl::ReallyHidden,
20481ad6265SDimitry Andric                                  cl::init(true),
2050b57cec5SDimitry Andric                                  cl::desc("Enable CopyToPhi DAG Mutation"));
2060b57cec5SDimitry Andric 
207bdd1243dSDimitry Andric /// A command line argument to force pipeliner to use specified issue
208bdd1243dSDimitry Andric /// width.
209bdd1243dSDimitry Andric cl::opt<int> SwpForceIssueWidth(
210bdd1243dSDimitry Andric     "pipeliner-force-issue-width",
211bdd1243dSDimitry Andric     cl::desc("Force pipeliner to use specified issue width."), cl::Hidden,
212bdd1243dSDimitry Andric     cl::init(-1));
213bdd1243dSDimitry Andric 
2140fca6ea1SDimitry Andric /// A command line argument to set the window scheduling option.
2150fca6ea1SDimitry Andric cl::opt<WindowSchedulingFlag> WindowSchedulingOption(
2160fca6ea1SDimitry Andric     "window-sched", cl::Hidden, cl::init(WindowSchedulingFlag::WS_On),
2170fca6ea1SDimitry Andric     cl::desc("Set how to use window scheduling algorithm."),
2180fca6ea1SDimitry Andric     cl::values(clEnumValN(WindowSchedulingFlag::WS_Off, "off",
2190fca6ea1SDimitry Andric                           "Turn off window algorithm."),
2200fca6ea1SDimitry Andric                clEnumValN(WindowSchedulingFlag::WS_On, "on",
2210fca6ea1SDimitry Andric                           "Use window algorithm after SMS algorithm fails."),
2220fca6ea1SDimitry Andric                clEnumValN(WindowSchedulingFlag::WS_Force, "force",
2230fca6ea1SDimitry Andric                           "Use window algorithm instead of SMS algorithm.")));
2240fca6ea1SDimitry Andric 
2250b57cec5SDimitry Andric } // end namespace llvm
2260b57cec5SDimitry Andric 
2270b57cec5SDimitry Andric unsigned SwingSchedulerDAG::Circuits::MaxPaths = 5;
2280b57cec5SDimitry Andric char MachinePipeliner::ID = 0;
2290b57cec5SDimitry Andric #ifndef NDEBUG
2300b57cec5SDimitry Andric int MachinePipeliner::NumTries = 0;
2310b57cec5SDimitry Andric #endif
2320b57cec5SDimitry Andric char &llvm::MachinePipelinerID = MachinePipeliner::ID;
2330b57cec5SDimitry Andric 
2340b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(MachinePipeliner, DEBUG_TYPE,
2350b57cec5SDimitry Andric                       "Modulo Software Pipelining", false, false)
2360b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
2370fca6ea1SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineLoopInfoWrapperPass)
2380fca6ea1SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineDominatorTreeWrapperPass)
2390fca6ea1SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LiveIntervalsWrapperPass)
2400b57cec5SDimitry Andric INITIALIZE_PASS_END(MachinePipeliner, DEBUG_TYPE,
2410b57cec5SDimitry Andric                     "Modulo Software Pipelining", false, false)
2420b57cec5SDimitry Andric 
2430b57cec5SDimitry Andric /// The "main" function for implementing Swing Modulo Scheduling.
2440b57cec5SDimitry Andric bool MachinePipeliner::runOnMachineFunction(MachineFunction &mf) {
2450b57cec5SDimitry Andric   if (skipFunction(mf.getFunction()))
2460b57cec5SDimitry Andric     return false;
2470b57cec5SDimitry Andric 
2480b57cec5SDimitry Andric   if (!EnableSWP)
2490b57cec5SDimitry Andric     return false;
2500b57cec5SDimitry Andric 
251349cc55cSDimitry Andric   if (mf.getFunction().getAttributes().hasFnAttr(Attribute::OptimizeForSize) &&
2520b57cec5SDimitry Andric       !EnableSWPOptSize.getPosition())
2530b57cec5SDimitry Andric     return false;
2540b57cec5SDimitry Andric 
2550b57cec5SDimitry Andric   if (!mf.getSubtarget().enableMachinePipeliner())
2560b57cec5SDimitry Andric     return false;
2570b57cec5SDimitry Andric 
2580b57cec5SDimitry Andric   // Cannot pipeline loops without instruction itineraries if we are using
2590b57cec5SDimitry Andric   // DFA for the pipeliner.
2600b57cec5SDimitry Andric   if (mf.getSubtarget().useDFAforSMS() &&
2610b57cec5SDimitry Andric       (!mf.getSubtarget().getInstrItineraryData() ||
2620b57cec5SDimitry Andric        mf.getSubtarget().getInstrItineraryData()->isEmpty()))
2630b57cec5SDimitry Andric     return false;
2640b57cec5SDimitry Andric 
2650b57cec5SDimitry Andric   MF = &mf;
2660fca6ea1SDimitry Andric   MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
2670fca6ea1SDimitry Andric   MDT = &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
2685ffd83dbSDimitry Andric   ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
2690b57cec5SDimitry Andric   TII = MF->getSubtarget().getInstrInfo();
2700b57cec5SDimitry Andric   RegClassInfo.runOnMachineFunction(*MF);
2710b57cec5SDimitry Andric 
272fcaf7f86SDimitry Andric   for (const auto &L : *MLI)
2730b57cec5SDimitry Andric     scheduleLoop(*L);
2740b57cec5SDimitry Andric 
2750b57cec5SDimitry Andric   return false;
2760b57cec5SDimitry Andric }
2770b57cec5SDimitry Andric 
2780b57cec5SDimitry Andric /// Attempt to perform the SMS algorithm on the specified loop. This function is
2790b57cec5SDimitry Andric /// the main entry point for the algorithm.  The function identifies candidate
2800b57cec5SDimitry Andric /// loops, calculates the minimum initiation interval, and attempts to schedule
2810b57cec5SDimitry Andric /// the loop.
2820b57cec5SDimitry Andric bool MachinePipeliner::scheduleLoop(MachineLoop &L) {
2830b57cec5SDimitry Andric   bool Changed = false;
284fcaf7f86SDimitry Andric   for (const auto &InnerLoop : L)
2850b57cec5SDimitry Andric     Changed |= scheduleLoop(*InnerLoop);
2860b57cec5SDimitry Andric 
2870b57cec5SDimitry Andric #ifndef NDEBUG
2880b57cec5SDimitry Andric   // Stop trying after reaching the limit (if any).
2890b57cec5SDimitry Andric   int Limit = SwpLoopLimit;
2900b57cec5SDimitry Andric   if (Limit >= 0) {
2910b57cec5SDimitry Andric     if (NumTries >= SwpLoopLimit)
2920b57cec5SDimitry Andric       return Changed;
2930b57cec5SDimitry Andric     NumTries++;
2940b57cec5SDimitry Andric   }
2950b57cec5SDimitry Andric #endif
2960b57cec5SDimitry Andric 
2970b57cec5SDimitry Andric   setPragmaPipelineOptions(L);
2980b57cec5SDimitry Andric   if (!canPipelineLoop(L)) {
2990b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "\n!!! Can not pipeline loop.\n");
3005ffd83dbSDimitry Andric     ORE->emit([&]() {
3015ffd83dbSDimitry Andric       return MachineOptimizationRemarkMissed(DEBUG_TYPE, "canPipelineLoop",
3025ffd83dbSDimitry Andric                                              L.getStartLoc(), L.getHeader())
3035ffd83dbSDimitry Andric              << "Failed to pipeline loop";
3045ffd83dbSDimitry Andric     });
3055ffd83dbSDimitry Andric 
30681ad6265SDimitry Andric     LI.LoopPipelinerInfo.reset();
3070b57cec5SDimitry Andric     return Changed;
3080b57cec5SDimitry Andric   }
3090b57cec5SDimitry Andric 
3100b57cec5SDimitry Andric   ++NumTrytoPipeline;
3110fca6ea1SDimitry Andric   if (useSwingModuloScheduler())
3120b57cec5SDimitry Andric     Changed = swingModuloScheduler(L);
3130b57cec5SDimitry Andric 
3140fca6ea1SDimitry Andric   if (useWindowScheduler(Changed))
3150fca6ea1SDimitry Andric     Changed = runWindowScheduler(L);
3160fca6ea1SDimitry Andric 
31781ad6265SDimitry Andric   LI.LoopPipelinerInfo.reset();
3180b57cec5SDimitry Andric   return Changed;
3190b57cec5SDimitry Andric }
3200b57cec5SDimitry Andric 
3210b57cec5SDimitry Andric void MachinePipeliner::setPragmaPipelineOptions(MachineLoop &L) {
3225ffd83dbSDimitry Andric   // Reset the pragma for the next loop in iteration.
3235ffd83dbSDimitry Andric   disabledByPragma = false;
324e8d8bef9SDimitry Andric   II_setByPragma = 0;
3255ffd83dbSDimitry Andric 
3260b57cec5SDimitry Andric   MachineBasicBlock *LBLK = L.getTopBlock();
3270b57cec5SDimitry Andric 
3280b57cec5SDimitry Andric   if (LBLK == nullptr)
3290b57cec5SDimitry Andric     return;
3300b57cec5SDimitry Andric 
3310b57cec5SDimitry Andric   const BasicBlock *BBLK = LBLK->getBasicBlock();
3320b57cec5SDimitry Andric   if (BBLK == nullptr)
3330b57cec5SDimitry Andric     return;
3340b57cec5SDimitry Andric 
3350b57cec5SDimitry Andric   const Instruction *TI = BBLK->getTerminator();
3360b57cec5SDimitry Andric   if (TI == nullptr)
3370b57cec5SDimitry Andric     return;
3380b57cec5SDimitry Andric 
3390b57cec5SDimitry Andric   MDNode *LoopID = TI->getMetadata(LLVMContext::MD_loop);
3400b57cec5SDimitry Andric   if (LoopID == nullptr)
3410b57cec5SDimitry Andric     return;
3420b57cec5SDimitry Andric 
3430b57cec5SDimitry Andric   assert(LoopID->getNumOperands() > 0 && "requires atleast one operand");
3440b57cec5SDimitry Andric   assert(LoopID->getOperand(0) == LoopID && "invalid loop");
3450b57cec5SDimitry Andric 
3460fca6ea1SDimitry Andric   for (const MDOperand &MDO : llvm::drop_begin(LoopID->operands())) {
3470fca6ea1SDimitry Andric     MDNode *MD = dyn_cast<MDNode>(MDO);
3480b57cec5SDimitry Andric 
3490b57cec5SDimitry Andric     if (MD == nullptr)
3500b57cec5SDimitry Andric       continue;
3510b57cec5SDimitry Andric 
3520b57cec5SDimitry Andric     MDString *S = dyn_cast<MDString>(MD->getOperand(0));
3530b57cec5SDimitry Andric 
3540b57cec5SDimitry Andric     if (S == nullptr)
3550b57cec5SDimitry Andric       continue;
3560b57cec5SDimitry Andric 
3570b57cec5SDimitry Andric     if (S->getString() == "llvm.loop.pipeline.initiationinterval") {
3580b57cec5SDimitry Andric       assert(MD->getNumOperands() == 2 &&
3590b57cec5SDimitry Andric              "Pipeline initiation interval hint metadata should have two operands.");
3600b57cec5SDimitry Andric       II_setByPragma =
3610b57cec5SDimitry Andric           mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
3620b57cec5SDimitry Andric       assert(II_setByPragma >= 1 && "Pipeline initiation interval must be positive.");
3630b57cec5SDimitry Andric     } else if (S->getString() == "llvm.loop.pipeline.disable") {
3640b57cec5SDimitry Andric       disabledByPragma = true;
3650b57cec5SDimitry Andric     }
3660b57cec5SDimitry Andric   }
3670b57cec5SDimitry Andric }
3680b57cec5SDimitry Andric 
3690b57cec5SDimitry Andric /// Return true if the loop can be software pipelined.  The algorithm is
3700b57cec5SDimitry Andric /// restricted to loops with a single basic block.  Make sure that the
3710b57cec5SDimitry Andric /// branch in the loop can be analyzed.
3720b57cec5SDimitry Andric bool MachinePipeliner::canPipelineLoop(MachineLoop &L) {
3735ffd83dbSDimitry Andric   if (L.getNumBlocks() != 1) {
3745ffd83dbSDimitry Andric     ORE->emit([&]() {
3755ffd83dbSDimitry Andric       return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "canPipelineLoop",
3765ffd83dbSDimitry Andric                                                L.getStartLoc(), L.getHeader())
3775ffd83dbSDimitry Andric              << "Not a single basic block: "
3785ffd83dbSDimitry Andric              << ore::NV("NumBlocks", L.getNumBlocks());
3795ffd83dbSDimitry Andric     });
3800b57cec5SDimitry Andric     return false;
3815ffd83dbSDimitry Andric   }
3820b57cec5SDimitry Andric 
3835ffd83dbSDimitry Andric   if (disabledByPragma) {
3845ffd83dbSDimitry Andric     ORE->emit([&]() {
3855ffd83dbSDimitry Andric       return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "canPipelineLoop",
3865ffd83dbSDimitry Andric                                                L.getStartLoc(), L.getHeader())
3875ffd83dbSDimitry Andric              << "Disabled by Pragma.";
3885ffd83dbSDimitry Andric     });
3890b57cec5SDimitry Andric     return false;
3905ffd83dbSDimitry Andric   }
3910b57cec5SDimitry Andric 
3920b57cec5SDimitry Andric   // Check if the branch can't be understood because we can't do pipelining
3930b57cec5SDimitry Andric   // if that's the case.
3940b57cec5SDimitry Andric   LI.TBB = nullptr;
3950b57cec5SDimitry Andric   LI.FBB = nullptr;
3960b57cec5SDimitry Andric   LI.BrCond.clear();
3970b57cec5SDimitry Andric   if (TII->analyzeBranch(*L.getHeader(), LI.TBB, LI.FBB, LI.BrCond)) {
3985ffd83dbSDimitry Andric     LLVM_DEBUG(dbgs() << "Unable to analyzeBranch, can NOT pipeline Loop\n");
3990b57cec5SDimitry Andric     NumFailBranch++;
4005ffd83dbSDimitry Andric     ORE->emit([&]() {
4015ffd83dbSDimitry Andric       return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "canPipelineLoop",
4025ffd83dbSDimitry Andric                                                L.getStartLoc(), L.getHeader())
4035ffd83dbSDimitry Andric              << "The branch can't be understood";
4045ffd83dbSDimitry Andric     });
4050b57cec5SDimitry Andric     return false;
4060b57cec5SDimitry Andric   }
4070b57cec5SDimitry Andric 
4080b57cec5SDimitry Andric   LI.LoopInductionVar = nullptr;
4090b57cec5SDimitry Andric   LI.LoopCompare = nullptr;
41081ad6265SDimitry Andric   LI.LoopPipelinerInfo = TII->analyzeLoopForPipelining(L.getTopBlock());
41181ad6265SDimitry Andric   if (!LI.LoopPipelinerInfo) {
4125ffd83dbSDimitry Andric     LLVM_DEBUG(dbgs() << "Unable to analyzeLoop, can NOT pipeline Loop\n");
4130b57cec5SDimitry Andric     NumFailLoop++;
4145ffd83dbSDimitry Andric     ORE->emit([&]() {
4155ffd83dbSDimitry Andric       return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "canPipelineLoop",
4165ffd83dbSDimitry Andric                                                L.getStartLoc(), L.getHeader())
4175ffd83dbSDimitry Andric              << "The loop structure is not supported";
4185ffd83dbSDimitry Andric     });
4190b57cec5SDimitry Andric     return false;
4200b57cec5SDimitry Andric   }
4210b57cec5SDimitry Andric 
4220b57cec5SDimitry Andric   if (!L.getLoopPreheader()) {
4235ffd83dbSDimitry Andric     LLVM_DEBUG(dbgs() << "Preheader not found, can NOT pipeline Loop\n");
4240b57cec5SDimitry Andric     NumFailPreheader++;
4255ffd83dbSDimitry Andric     ORE->emit([&]() {
4265ffd83dbSDimitry Andric       return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "canPipelineLoop",
4275ffd83dbSDimitry Andric                                                L.getStartLoc(), L.getHeader())
4285ffd83dbSDimitry Andric              << "No loop preheader found";
4295ffd83dbSDimitry Andric     });
4300b57cec5SDimitry Andric     return false;
4310b57cec5SDimitry Andric   }
4320b57cec5SDimitry Andric 
4330b57cec5SDimitry Andric   // Remove any subregisters from inputs to phi nodes.
4340b57cec5SDimitry Andric   preprocessPhiNodes(*L.getHeader());
4350b57cec5SDimitry Andric   return true;
4360b57cec5SDimitry Andric }
4370b57cec5SDimitry Andric 
4380b57cec5SDimitry Andric void MachinePipeliner::preprocessPhiNodes(MachineBasicBlock &B) {
4390b57cec5SDimitry Andric   MachineRegisterInfo &MRI = MF->getRegInfo();
4400fca6ea1SDimitry Andric   SlotIndexes &Slots =
4410fca6ea1SDimitry Andric       *getAnalysis<LiveIntervalsWrapperPass>().getLIS().getSlotIndexes();
4420b57cec5SDimitry Andric 
443349cc55cSDimitry Andric   for (MachineInstr &PI : B.phis()) {
4440b57cec5SDimitry Andric     MachineOperand &DefOp = PI.getOperand(0);
4450b57cec5SDimitry Andric     assert(DefOp.getSubReg() == 0);
4460b57cec5SDimitry Andric     auto *RC = MRI.getRegClass(DefOp.getReg());
4470b57cec5SDimitry Andric 
4480b57cec5SDimitry Andric     for (unsigned i = 1, n = PI.getNumOperands(); i != n; i += 2) {
4490b57cec5SDimitry Andric       MachineOperand &RegOp = PI.getOperand(i);
4500b57cec5SDimitry Andric       if (RegOp.getSubReg() == 0)
4510b57cec5SDimitry Andric         continue;
4520b57cec5SDimitry Andric 
4530b57cec5SDimitry Andric       // If the operand uses a subregister, replace it with a new register
4540b57cec5SDimitry Andric       // without subregisters, and generate a copy to the new register.
4558bcb0991SDimitry Andric       Register NewReg = MRI.createVirtualRegister(RC);
4560b57cec5SDimitry Andric       MachineBasicBlock &PredB = *PI.getOperand(i+1).getMBB();
4570b57cec5SDimitry Andric       MachineBasicBlock::iterator At = PredB.getFirstTerminator();
4580b57cec5SDimitry Andric       const DebugLoc &DL = PredB.findDebugLoc(At);
4590b57cec5SDimitry Andric       auto Copy = BuildMI(PredB, At, DL, TII->get(TargetOpcode::COPY), NewReg)
4600b57cec5SDimitry Andric                     .addReg(RegOp.getReg(), getRegState(RegOp),
4610b57cec5SDimitry Andric                             RegOp.getSubReg());
4620b57cec5SDimitry Andric       Slots.insertMachineInstrInMaps(*Copy);
4630b57cec5SDimitry Andric       RegOp.setReg(NewReg);
4640b57cec5SDimitry Andric       RegOp.setSubReg(0);
4650b57cec5SDimitry Andric     }
4660b57cec5SDimitry Andric   }
4670b57cec5SDimitry Andric }
4680b57cec5SDimitry Andric 
4690b57cec5SDimitry Andric /// The SMS algorithm consists of the following main steps:
4700b57cec5SDimitry Andric /// 1. Computation and analysis of the dependence graph.
4710b57cec5SDimitry Andric /// 2. Ordering of the nodes (instructions).
4720b57cec5SDimitry Andric /// 3. Attempt to Schedule the loop.
4730b57cec5SDimitry Andric bool MachinePipeliner::swingModuloScheduler(MachineLoop &L) {
4740b57cec5SDimitry Andric   assert(L.getBlocks().size() == 1 && "SMS works on single blocks only.");
4750b57cec5SDimitry Andric 
4760fca6ea1SDimitry Andric   SwingSchedulerDAG SMS(
4770fca6ea1SDimitry Andric       *this, L, getAnalysis<LiveIntervalsWrapperPass>().getLIS(), RegClassInfo,
47881ad6265SDimitry Andric       II_setByPragma, LI.LoopPipelinerInfo.get());
4790b57cec5SDimitry Andric 
4800b57cec5SDimitry Andric   MachineBasicBlock *MBB = L.getHeader();
4810b57cec5SDimitry Andric   // The kernel should not include any terminator instructions.  These
4820b57cec5SDimitry Andric   // will be added back later.
4830b57cec5SDimitry Andric   SMS.startBlock(MBB);
4840b57cec5SDimitry Andric 
4850b57cec5SDimitry Andric   // Compute the number of 'real' instructions in the basic block by
4860b57cec5SDimitry Andric   // ignoring terminators.
4870b57cec5SDimitry Andric   unsigned size = MBB->size();
4880b57cec5SDimitry Andric   for (MachineBasicBlock::iterator I = MBB->getFirstTerminator(),
4890b57cec5SDimitry Andric                                    E = MBB->instr_end();
4900b57cec5SDimitry Andric        I != E; ++I, --size)
4910b57cec5SDimitry Andric     ;
4920b57cec5SDimitry Andric 
4930b57cec5SDimitry Andric   SMS.enterRegion(MBB, MBB->begin(), MBB->getFirstTerminator(), size);
4940b57cec5SDimitry Andric   SMS.schedule();
4950b57cec5SDimitry Andric   SMS.exitRegion();
4960b57cec5SDimitry Andric 
4970b57cec5SDimitry Andric   SMS.finishBlock();
4980b57cec5SDimitry Andric   return SMS.hasNewSchedule();
4990b57cec5SDimitry Andric }
5000b57cec5SDimitry Andric 
501e8d8bef9SDimitry Andric void MachinePipeliner::getAnalysisUsage(AnalysisUsage &AU) const {
502e8d8bef9SDimitry Andric   AU.addRequired<AAResultsWrapperPass>();
503e8d8bef9SDimitry Andric   AU.addPreserved<AAResultsWrapperPass>();
5040fca6ea1SDimitry Andric   AU.addRequired<MachineLoopInfoWrapperPass>();
5050fca6ea1SDimitry Andric   AU.addRequired<MachineDominatorTreeWrapperPass>();
5060fca6ea1SDimitry Andric   AU.addRequired<LiveIntervalsWrapperPass>();
507e8d8bef9SDimitry Andric   AU.addRequired<MachineOptimizationRemarkEmitterPass>();
5080fca6ea1SDimitry Andric   AU.addRequired<TargetPassConfig>();
509e8d8bef9SDimitry Andric   MachineFunctionPass::getAnalysisUsage(AU);
510e8d8bef9SDimitry Andric }
511e8d8bef9SDimitry Andric 
5120fca6ea1SDimitry Andric bool MachinePipeliner::runWindowScheduler(MachineLoop &L) {
5130fca6ea1SDimitry Andric   MachineSchedContext Context;
5140fca6ea1SDimitry Andric   Context.MF = MF;
5150fca6ea1SDimitry Andric   Context.MLI = MLI;
5160fca6ea1SDimitry Andric   Context.MDT = MDT;
5170fca6ea1SDimitry Andric   Context.PassConfig = &getAnalysis<TargetPassConfig>();
5180fca6ea1SDimitry Andric   Context.AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
5190fca6ea1SDimitry Andric   Context.LIS = &getAnalysis<LiveIntervalsWrapperPass>().getLIS();
5200fca6ea1SDimitry Andric   Context.RegClassInfo->runOnMachineFunction(*MF);
5210fca6ea1SDimitry Andric   WindowScheduler WS(&Context, L);
5220fca6ea1SDimitry Andric   return WS.run();
5230fca6ea1SDimitry Andric }
5240fca6ea1SDimitry Andric 
5250fca6ea1SDimitry Andric bool MachinePipeliner::useSwingModuloScheduler() {
5260fca6ea1SDimitry Andric   // SwingModuloScheduler does not work when WindowScheduler is forced.
5270fca6ea1SDimitry Andric   return WindowSchedulingOption != WindowSchedulingFlag::WS_Force;
5280fca6ea1SDimitry Andric }
5290fca6ea1SDimitry Andric 
5300fca6ea1SDimitry Andric bool MachinePipeliner::useWindowScheduler(bool Changed) {
531*6c4b055cSDimitry Andric   // WindowScheduler does not work for following cases:
532*6c4b055cSDimitry Andric   // 1. when it is off.
533*6c4b055cSDimitry Andric   // 2. when SwingModuloScheduler is successfully scheduled.
534*6c4b055cSDimitry Andric   // 3. when pragma II is enabled.
535*6c4b055cSDimitry Andric   if (II_setByPragma) {
536*6c4b055cSDimitry Andric     LLVM_DEBUG(dbgs() << "Window scheduling is disabled when "
537*6c4b055cSDimitry Andric                          "llvm.loop.pipeline.initiationinterval is set.\n");
538*6c4b055cSDimitry Andric     return false;
539*6c4b055cSDimitry Andric   }
540*6c4b055cSDimitry Andric 
5410fca6ea1SDimitry Andric   return WindowSchedulingOption == WindowSchedulingFlag::WS_Force ||
5420fca6ea1SDimitry Andric          (WindowSchedulingOption == WindowSchedulingFlag::WS_On && !Changed);
5430fca6ea1SDimitry Andric }
5440fca6ea1SDimitry Andric 
5450b57cec5SDimitry Andric void SwingSchedulerDAG::setMII(unsigned ResMII, unsigned RecMII) {
546bdd1243dSDimitry Andric   if (SwpForceII > 0)
547bdd1243dSDimitry Andric     MII = SwpForceII;
548bdd1243dSDimitry Andric   else if (II_setByPragma > 0)
5490b57cec5SDimitry Andric     MII = II_setByPragma;
5500b57cec5SDimitry Andric   else
5510b57cec5SDimitry Andric     MII = std::max(ResMII, RecMII);
5520b57cec5SDimitry Andric }
5530b57cec5SDimitry Andric 
5540b57cec5SDimitry Andric void SwingSchedulerDAG::setMAX_II() {
555bdd1243dSDimitry Andric   if (SwpForceII > 0)
556bdd1243dSDimitry Andric     MAX_II = SwpForceII;
557bdd1243dSDimitry Andric   else if (II_setByPragma > 0)
5580b57cec5SDimitry Andric     MAX_II = II_setByPragma;
5590b57cec5SDimitry Andric   else
5607a6dacacSDimitry Andric     MAX_II = MII + SwpIISearchRange;
5610b57cec5SDimitry Andric }
5620b57cec5SDimitry Andric 
5630b57cec5SDimitry Andric /// We override the schedule function in ScheduleDAGInstrs to implement the
5640b57cec5SDimitry Andric /// scheduling part of the Swing Modulo Scheduling algorithm.
5650b57cec5SDimitry Andric void SwingSchedulerDAG::schedule() {
5660b57cec5SDimitry Andric   AliasAnalysis *AA = &Pass.getAnalysis<AAResultsWrapperPass>().getAAResults();
5670b57cec5SDimitry Andric   buildSchedGraph(AA);
5680b57cec5SDimitry Andric   addLoopCarriedDependences(AA);
5690b57cec5SDimitry Andric   updatePhiDependences();
5700b57cec5SDimitry Andric   Topo.InitDAGTopologicalSorting();
5710b57cec5SDimitry Andric   changeDependences();
57206c3fb27SDimitry Andric   postProcessDAG();
5730b57cec5SDimitry Andric   LLVM_DEBUG(dump());
5740b57cec5SDimitry Andric 
5750b57cec5SDimitry Andric   NodeSetType NodeSets;
5760b57cec5SDimitry Andric   findCircuits(NodeSets);
5770b57cec5SDimitry Andric   NodeSetType Circuits = NodeSets;
5780b57cec5SDimitry Andric 
5790b57cec5SDimitry Andric   // Calculate the MII.
5800b57cec5SDimitry Andric   unsigned ResMII = calculateResMII();
5810b57cec5SDimitry Andric   unsigned RecMII = calculateRecMII(NodeSets);
5820b57cec5SDimitry Andric 
5830b57cec5SDimitry Andric   fuseRecs(NodeSets);
5840b57cec5SDimitry Andric 
5850b57cec5SDimitry Andric   // This flag is used for testing and can cause correctness problems.
5860b57cec5SDimitry Andric   if (SwpIgnoreRecMII)
5870b57cec5SDimitry Andric     RecMII = 0;
5880b57cec5SDimitry Andric 
5890b57cec5SDimitry Andric   setMII(ResMII, RecMII);
5900b57cec5SDimitry Andric   setMAX_II();
5910b57cec5SDimitry Andric 
5920b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "MII = " << MII << " MAX_II = " << MAX_II
5930b57cec5SDimitry Andric                     << " (rec=" << RecMII << ", res=" << ResMII << ")\n");
5940b57cec5SDimitry Andric 
5950b57cec5SDimitry Andric   // Can't schedule a loop without a valid MII.
5960b57cec5SDimitry Andric   if (MII == 0) {
5975ffd83dbSDimitry Andric     LLVM_DEBUG(dbgs() << "Invalid Minimal Initiation Interval: 0\n");
5980b57cec5SDimitry Andric     NumFailZeroMII++;
5995ffd83dbSDimitry Andric     Pass.ORE->emit([&]() {
6005ffd83dbSDimitry Andric       return MachineOptimizationRemarkAnalysis(
6015ffd83dbSDimitry Andric                  DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
6025ffd83dbSDimitry Andric              << "Invalid Minimal Initiation Interval: 0";
6035ffd83dbSDimitry Andric     });
6040b57cec5SDimitry Andric     return;
6050b57cec5SDimitry Andric   }
6060b57cec5SDimitry Andric 
6070b57cec5SDimitry Andric   // Don't pipeline large loops.
6080b57cec5SDimitry Andric   if (SwpMaxMii != -1 && (int)MII > SwpMaxMii) {
6090b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "MII > " << SwpMaxMii
61081ad6265SDimitry Andric                       << ", we don't pipeline large loops\n");
6110b57cec5SDimitry Andric     NumFailLargeMaxMII++;
6125ffd83dbSDimitry Andric     Pass.ORE->emit([&]() {
6135ffd83dbSDimitry Andric       return MachineOptimizationRemarkAnalysis(
6145ffd83dbSDimitry Andric                  DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
6155ffd83dbSDimitry Andric              << "Minimal Initiation Interval too large: "
6165ffd83dbSDimitry Andric              << ore::NV("MII", (int)MII) << " > "
6175ffd83dbSDimitry Andric              << ore::NV("SwpMaxMii", SwpMaxMii) << "."
6185ffd83dbSDimitry Andric              << "Refer to -pipeliner-max-mii.";
6195ffd83dbSDimitry Andric     });
6200b57cec5SDimitry Andric     return;
6210b57cec5SDimitry Andric   }
6220b57cec5SDimitry Andric 
6230b57cec5SDimitry Andric   computeNodeFunctions(NodeSets);
6240b57cec5SDimitry Andric 
6250b57cec5SDimitry Andric   registerPressureFilter(NodeSets);
6260b57cec5SDimitry Andric 
6270b57cec5SDimitry Andric   colocateNodeSets(NodeSets);
6280b57cec5SDimitry Andric 
6290b57cec5SDimitry Andric   checkNodeSets(NodeSets);
6300b57cec5SDimitry Andric 
6310b57cec5SDimitry Andric   LLVM_DEBUG({
6320b57cec5SDimitry Andric     for (auto &I : NodeSets) {
6330b57cec5SDimitry Andric       dbgs() << "  Rec NodeSet ";
6340b57cec5SDimitry Andric       I.dump();
6350b57cec5SDimitry Andric     }
6360b57cec5SDimitry Andric   });
6370b57cec5SDimitry Andric 
6380b57cec5SDimitry Andric   llvm::stable_sort(NodeSets, std::greater<NodeSet>());
6390b57cec5SDimitry Andric 
6400b57cec5SDimitry Andric   groupRemainingNodes(NodeSets);
6410b57cec5SDimitry Andric 
6420b57cec5SDimitry Andric   removeDuplicateNodes(NodeSets);
6430b57cec5SDimitry Andric 
6440b57cec5SDimitry Andric   LLVM_DEBUG({
6450b57cec5SDimitry Andric     for (auto &I : NodeSets) {
6460b57cec5SDimitry Andric       dbgs() << "  NodeSet ";
6470b57cec5SDimitry Andric       I.dump();
6480b57cec5SDimitry Andric     }
6490b57cec5SDimitry Andric   });
6500b57cec5SDimitry Andric 
6510b57cec5SDimitry Andric   computeNodeOrder(NodeSets);
6520b57cec5SDimitry Andric 
6530b57cec5SDimitry Andric   // check for node order issues
6540b57cec5SDimitry Andric   checkValidNodeOrder(Circuits);
6550b57cec5SDimitry Andric 
656bdd1243dSDimitry Andric   SMSchedule Schedule(Pass.MF, this);
6570b57cec5SDimitry Andric   Scheduled = schedulePipeline(Schedule);
6580b57cec5SDimitry Andric 
6590b57cec5SDimitry Andric   if (!Scheduled){
6600b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "No schedule found, return\n");
6610b57cec5SDimitry Andric     NumFailNoSchedule++;
6625ffd83dbSDimitry Andric     Pass.ORE->emit([&]() {
6635ffd83dbSDimitry Andric       return MachineOptimizationRemarkAnalysis(
6645ffd83dbSDimitry Andric                  DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
6655ffd83dbSDimitry Andric              << "Unable to find schedule";
6665ffd83dbSDimitry Andric     });
6670b57cec5SDimitry Andric     return;
6680b57cec5SDimitry Andric   }
6690b57cec5SDimitry Andric 
6700b57cec5SDimitry Andric   unsigned numStages = Schedule.getMaxStageCount();
6710b57cec5SDimitry Andric   // No need to generate pipeline if there are no overlapped iterations.
6720b57cec5SDimitry Andric   if (numStages == 0) {
6735ffd83dbSDimitry Andric     LLVM_DEBUG(dbgs() << "No overlapped iterations, skip.\n");
6740b57cec5SDimitry Andric     NumFailZeroStage++;
6755ffd83dbSDimitry Andric     Pass.ORE->emit([&]() {
6765ffd83dbSDimitry Andric       return MachineOptimizationRemarkAnalysis(
6775ffd83dbSDimitry Andric                  DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
6785ffd83dbSDimitry Andric              << "No need to pipeline - no overlapped iterations in schedule.";
6795ffd83dbSDimitry Andric     });
6800b57cec5SDimitry Andric     return;
6810b57cec5SDimitry Andric   }
6820b57cec5SDimitry Andric   // Check that the maximum stage count is less than user-defined limit.
6830b57cec5SDimitry Andric   if (SwpMaxStages > -1 && (int)numStages > SwpMaxStages) {
6840b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "numStages:" << numStages << ">" << SwpMaxStages
6850b57cec5SDimitry Andric                       << " : too many stages, abort\n");
6860b57cec5SDimitry Andric     NumFailLargeMaxStage++;
6875ffd83dbSDimitry Andric     Pass.ORE->emit([&]() {
6885ffd83dbSDimitry Andric       return MachineOptimizationRemarkAnalysis(
6895ffd83dbSDimitry Andric                  DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
6905ffd83dbSDimitry Andric              << "Too many stages in schedule: "
6915ffd83dbSDimitry Andric              << ore::NV("numStages", (int)numStages) << " > "
6925ffd83dbSDimitry Andric              << ore::NV("SwpMaxStages", SwpMaxStages)
6935ffd83dbSDimitry Andric              << ". Refer to -pipeliner-max-stages.";
6945ffd83dbSDimitry Andric     });
6950b57cec5SDimitry Andric     return;
6960b57cec5SDimitry Andric   }
6970b57cec5SDimitry Andric 
6985ffd83dbSDimitry Andric   Pass.ORE->emit([&]() {
6995ffd83dbSDimitry Andric     return MachineOptimizationRemark(DEBUG_TYPE, "schedule", Loop.getStartLoc(),
7005ffd83dbSDimitry Andric                                      Loop.getHeader())
7015ffd83dbSDimitry Andric            << "Pipelined succesfully!";
7025ffd83dbSDimitry Andric   });
7035ffd83dbSDimitry Andric 
7048bcb0991SDimitry Andric   // Generate the schedule as a ModuloSchedule.
7058bcb0991SDimitry Andric   DenseMap<MachineInstr *, int> Cycles, Stages;
7068bcb0991SDimitry Andric   std::vector<MachineInstr *> OrderedInsts;
7078bcb0991SDimitry Andric   for (int Cycle = Schedule.getFirstCycle(); Cycle <= Schedule.getFinalCycle();
7088bcb0991SDimitry Andric        ++Cycle) {
7098bcb0991SDimitry Andric     for (SUnit *SU : Schedule.getInstructions(Cycle)) {
7108bcb0991SDimitry Andric       OrderedInsts.push_back(SU->getInstr());
7118bcb0991SDimitry Andric       Cycles[SU->getInstr()] = Cycle;
7128bcb0991SDimitry Andric       Stages[SU->getInstr()] = Schedule.stageScheduled(SU);
7138bcb0991SDimitry Andric     }
7148bcb0991SDimitry Andric   }
7158bcb0991SDimitry Andric   DenseMap<MachineInstr *, std::pair<unsigned, int64_t>> NewInstrChanges;
7168bcb0991SDimitry Andric   for (auto &KV : NewMIs) {
7178bcb0991SDimitry Andric     Cycles[KV.first] = Cycles[KV.second];
7188bcb0991SDimitry Andric     Stages[KV.first] = Stages[KV.second];
7198bcb0991SDimitry Andric     NewInstrChanges[KV.first] = InstrChanges[getSUnit(KV.first)];
7208bcb0991SDimitry Andric   }
7218bcb0991SDimitry Andric 
7228bcb0991SDimitry Andric   ModuloSchedule MS(MF, &Loop, std::move(OrderedInsts), std::move(Cycles),
7238bcb0991SDimitry Andric                     std::move(Stages));
7248bcb0991SDimitry Andric   if (EmitTestAnnotations) {
7258bcb0991SDimitry Andric     assert(NewInstrChanges.empty() &&
7268bcb0991SDimitry Andric            "Cannot serialize a schedule with InstrChanges!");
7278bcb0991SDimitry Andric     ModuloScheduleTestAnnotater MSTI(MF, MS);
7288bcb0991SDimitry Andric     MSTI.annotate();
7298bcb0991SDimitry Andric     return;
7308bcb0991SDimitry Andric   }
7318bcb0991SDimitry Andric   // The experimental code generator can't work if there are InstChanges.
7328bcb0991SDimitry Andric   if (ExperimentalCodeGen && NewInstrChanges.empty()) {
7338bcb0991SDimitry Andric     PeelingModuloScheduleExpander MSE(MF, MS, &LIS);
7348bcb0991SDimitry Andric     MSE.expand();
7350fca6ea1SDimitry Andric   } else if (MVECodeGen && NewInstrChanges.empty() &&
7360fca6ea1SDimitry Andric              LoopPipelinerInfo->isMVEExpanderSupported() &&
7370fca6ea1SDimitry Andric              ModuloScheduleExpanderMVE::canApply(Loop)) {
7380fca6ea1SDimitry Andric     ModuloScheduleExpanderMVE MSE(MF, MS, LIS);
7390fca6ea1SDimitry Andric     MSE.expand();
7408bcb0991SDimitry Andric   } else {
7418bcb0991SDimitry Andric     ModuloScheduleExpander MSE(MF, MS, LIS, std::move(NewInstrChanges));
7428bcb0991SDimitry Andric     MSE.expand();
7438bcb0991SDimitry Andric     MSE.cleanup();
7448bcb0991SDimitry Andric   }
7450b57cec5SDimitry Andric   ++NumPipelined;
7460b57cec5SDimitry Andric }
7470b57cec5SDimitry Andric 
7480b57cec5SDimitry Andric /// Clean up after the software pipeliner runs.
7490b57cec5SDimitry Andric void SwingSchedulerDAG::finishBlock() {
7508bcb0991SDimitry Andric   for (auto &KV : NewMIs)
7510eae32dcSDimitry Andric     MF.deleteMachineInstr(KV.second);
7520b57cec5SDimitry Andric   NewMIs.clear();
7530b57cec5SDimitry Andric 
7540b57cec5SDimitry Andric   // Call the superclass.
7550b57cec5SDimitry Andric   ScheduleDAGInstrs::finishBlock();
7560b57cec5SDimitry Andric }
7570b57cec5SDimitry Andric 
7580b57cec5SDimitry Andric /// Return the register values for  the operands of a Phi instruction.
7590b57cec5SDimitry Andric /// This function assume the instruction is a Phi.
7600b57cec5SDimitry Andric static void getPhiRegs(MachineInstr &Phi, MachineBasicBlock *Loop,
7610b57cec5SDimitry Andric                        unsigned &InitVal, unsigned &LoopVal) {
7620b57cec5SDimitry Andric   assert(Phi.isPHI() && "Expecting a Phi.");
7630b57cec5SDimitry Andric 
7640b57cec5SDimitry Andric   InitVal = 0;
7650b57cec5SDimitry Andric   LoopVal = 0;
7660b57cec5SDimitry Andric   for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
7670b57cec5SDimitry Andric     if (Phi.getOperand(i + 1).getMBB() != Loop)
7680b57cec5SDimitry Andric       InitVal = Phi.getOperand(i).getReg();
7690b57cec5SDimitry Andric     else
7700b57cec5SDimitry Andric       LoopVal = Phi.getOperand(i).getReg();
7710b57cec5SDimitry Andric 
7720b57cec5SDimitry Andric   assert(InitVal != 0 && LoopVal != 0 && "Unexpected Phi structure.");
7730b57cec5SDimitry Andric }
7740b57cec5SDimitry Andric 
7750b57cec5SDimitry Andric /// Return the Phi register value that comes the loop block.
7767a6dacacSDimitry Andric static unsigned getLoopPhiReg(const MachineInstr &Phi,
7777a6dacacSDimitry Andric                               const MachineBasicBlock *LoopBB) {
7780b57cec5SDimitry Andric   for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
7790b57cec5SDimitry Andric     if (Phi.getOperand(i + 1).getMBB() == LoopBB)
7800b57cec5SDimitry Andric       return Phi.getOperand(i).getReg();
7810b57cec5SDimitry Andric   return 0;
7820b57cec5SDimitry Andric }
7830b57cec5SDimitry Andric 
7840b57cec5SDimitry Andric /// Return true if SUb can be reached from SUa following the chain edges.
7850b57cec5SDimitry Andric static bool isSuccOrder(SUnit *SUa, SUnit *SUb) {
7860b57cec5SDimitry Andric   SmallPtrSet<SUnit *, 8> Visited;
7870b57cec5SDimitry Andric   SmallVector<SUnit *, 8> Worklist;
7880b57cec5SDimitry Andric   Worklist.push_back(SUa);
7890b57cec5SDimitry Andric   while (!Worklist.empty()) {
7900b57cec5SDimitry Andric     const SUnit *SU = Worklist.pop_back_val();
791fcaf7f86SDimitry Andric     for (const auto &SI : SU->Succs) {
7920b57cec5SDimitry Andric       SUnit *SuccSU = SI.getSUnit();
7930b57cec5SDimitry Andric       if (SI.getKind() == SDep::Order) {
7940b57cec5SDimitry Andric         if (Visited.count(SuccSU))
7950b57cec5SDimitry Andric           continue;
7960b57cec5SDimitry Andric         if (SuccSU == SUb)
7970b57cec5SDimitry Andric           return true;
7980b57cec5SDimitry Andric         Worklist.push_back(SuccSU);
7990b57cec5SDimitry Andric         Visited.insert(SuccSU);
8000b57cec5SDimitry Andric       }
8010b57cec5SDimitry Andric     }
8020b57cec5SDimitry Andric   }
8030b57cec5SDimitry Andric   return false;
8040b57cec5SDimitry Andric }
8050b57cec5SDimitry Andric 
8060b57cec5SDimitry Andric /// Return true if the instruction causes a chain between memory
8070b57cec5SDimitry Andric /// references before and after it.
808fcaf7f86SDimitry Andric static bool isDependenceBarrier(MachineInstr &MI) {
8090b57cec5SDimitry Andric   return MI.isCall() || MI.mayRaiseFPException() ||
8100b57cec5SDimitry Andric          MI.hasUnmodeledSideEffects() ||
8110b57cec5SDimitry Andric          (MI.hasOrderedMemoryRef() &&
812fcaf7f86SDimitry Andric           (!MI.mayLoad() || !MI.isDereferenceableInvariantLoad()));
8130b57cec5SDimitry Andric }
8140b57cec5SDimitry Andric 
8150b57cec5SDimitry Andric /// Return the underlying objects for the memory references of an instruction.
8160b57cec5SDimitry Andric /// This function calls the code in ValueTracking, but first checks that the
8170b57cec5SDimitry Andric /// instruction has a memory operand.
8180b57cec5SDimitry Andric static void getUnderlyingObjects(const MachineInstr *MI,
819e8d8bef9SDimitry Andric                                  SmallVectorImpl<const Value *> &Objs) {
8200b57cec5SDimitry Andric   if (!MI->hasOneMemOperand())
8210b57cec5SDimitry Andric     return;
8220b57cec5SDimitry Andric   MachineMemOperand *MM = *MI->memoperands_begin();
8230b57cec5SDimitry Andric   if (!MM->getValue())
8240b57cec5SDimitry Andric     return;
825e8d8bef9SDimitry Andric   getUnderlyingObjects(MM->getValue(), Objs);
8260b57cec5SDimitry Andric   for (const Value *V : Objs) {
8270b57cec5SDimitry Andric     if (!isIdentifiedObject(V)) {
8280b57cec5SDimitry Andric       Objs.clear();
8290b57cec5SDimitry Andric       return;
8300b57cec5SDimitry Andric     }
8310b57cec5SDimitry Andric   }
8320b57cec5SDimitry Andric }
8330b57cec5SDimitry Andric 
8340b57cec5SDimitry Andric /// Add a chain edge between a load and store if the store can be an
8350b57cec5SDimitry Andric /// alias of the load on a subsequent iteration, i.e., a loop carried
8360b57cec5SDimitry Andric /// dependence. This code is very similar to the code in ScheduleDAGInstrs
8370b57cec5SDimitry Andric /// but that code doesn't create loop carried dependences.
8380b57cec5SDimitry Andric void SwingSchedulerDAG::addLoopCarriedDependences(AliasAnalysis *AA) {
8390b57cec5SDimitry Andric   MapVector<const Value *, SmallVector<SUnit *, 4>> PendingLoads;
8400b57cec5SDimitry Andric   Value *UnknownValue =
8410b57cec5SDimitry Andric     UndefValue::get(Type::getVoidTy(MF.getFunction().getContext()));
8420b57cec5SDimitry Andric   for (auto &SU : SUnits) {
8430b57cec5SDimitry Andric     MachineInstr &MI = *SU.getInstr();
844fcaf7f86SDimitry Andric     if (isDependenceBarrier(MI))
8450b57cec5SDimitry Andric       PendingLoads.clear();
8460b57cec5SDimitry Andric     else if (MI.mayLoad()) {
8470b57cec5SDimitry Andric       SmallVector<const Value *, 4> Objs;
848e8d8bef9SDimitry Andric       ::getUnderlyingObjects(&MI, Objs);
8490b57cec5SDimitry Andric       if (Objs.empty())
8500b57cec5SDimitry Andric         Objs.push_back(UnknownValue);
851fcaf7f86SDimitry Andric       for (const auto *V : Objs) {
8520b57cec5SDimitry Andric         SmallVector<SUnit *, 4> &SUs = PendingLoads[V];
8530b57cec5SDimitry Andric         SUs.push_back(&SU);
8540b57cec5SDimitry Andric       }
8550b57cec5SDimitry Andric     } else if (MI.mayStore()) {
8560b57cec5SDimitry Andric       SmallVector<const Value *, 4> Objs;
857e8d8bef9SDimitry Andric       ::getUnderlyingObjects(&MI, Objs);
8580b57cec5SDimitry Andric       if (Objs.empty())
8590b57cec5SDimitry Andric         Objs.push_back(UnknownValue);
860fcaf7f86SDimitry Andric       for (const auto *V : Objs) {
8610b57cec5SDimitry Andric         MapVector<const Value *, SmallVector<SUnit *, 4>>::iterator I =
8620b57cec5SDimitry Andric             PendingLoads.find(V);
8630b57cec5SDimitry Andric         if (I == PendingLoads.end())
8640b57cec5SDimitry Andric           continue;
865fcaf7f86SDimitry Andric         for (auto *Load : I->second) {
8660b57cec5SDimitry Andric           if (isSuccOrder(Load, &SU))
8670b57cec5SDimitry Andric             continue;
8680b57cec5SDimitry Andric           MachineInstr &LdMI = *Load->getInstr();
8690b57cec5SDimitry Andric           // First, perform the cheaper check that compares the base register.
8700b57cec5SDimitry Andric           // If they are the same and the load offset is less than the store
8710b57cec5SDimitry Andric           // offset, then mark the dependence as loop carried potentially.
8720b57cec5SDimitry Andric           const MachineOperand *BaseOp1, *BaseOp2;
8730b57cec5SDimitry Andric           int64_t Offset1, Offset2;
8745ffd83dbSDimitry Andric           bool Offset1IsScalable, Offset2IsScalable;
8755ffd83dbSDimitry Andric           if (TII->getMemOperandWithOffset(LdMI, BaseOp1, Offset1,
8765ffd83dbSDimitry Andric                                            Offset1IsScalable, TRI) &&
8775ffd83dbSDimitry Andric               TII->getMemOperandWithOffset(MI, BaseOp2, Offset2,
8785ffd83dbSDimitry Andric                                            Offset2IsScalable, TRI)) {
8790b57cec5SDimitry Andric             if (BaseOp1->isIdenticalTo(*BaseOp2) &&
8805ffd83dbSDimitry Andric                 Offset1IsScalable == Offset2IsScalable &&
8810b57cec5SDimitry Andric                 (int)Offset1 < (int)Offset2) {
8828bcb0991SDimitry Andric               assert(TII->areMemAccessesTriviallyDisjoint(LdMI, MI) &&
8830b57cec5SDimitry Andric                      "What happened to the chain edge?");
8840b57cec5SDimitry Andric               SDep Dep(Load, SDep::Barrier);
8850b57cec5SDimitry Andric               Dep.setLatency(1);
8860b57cec5SDimitry Andric               SU.addPred(Dep);
8870b57cec5SDimitry Andric               continue;
8880b57cec5SDimitry Andric             }
8890b57cec5SDimitry Andric           }
8900b57cec5SDimitry Andric           // Second, the more expensive check that uses alias analysis on the
8910b57cec5SDimitry Andric           // base registers. If they alias, and the load offset is less than
8920b57cec5SDimitry Andric           // the store offset, the mark the dependence as loop carried.
8930b57cec5SDimitry Andric           if (!AA) {
8940b57cec5SDimitry Andric             SDep Dep(Load, SDep::Barrier);
8950b57cec5SDimitry Andric             Dep.setLatency(1);
8960b57cec5SDimitry Andric             SU.addPred(Dep);
8970b57cec5SDimitry Andric             continue;
8980b57cec5SDimitry Andric           }
8990b57cec5SDimitry Andric           MachineMemOperand *MMO1 = *LdMI.memoperands_begin();
9000b57cec5SDimitry Andric           MachineMemOperand *MMO2 = *MI.memoperands_begin();
9010b57cec5SDimitry Andric           if (!MMO1->getValue() || !MMO2->getValue()) {
9020b57cec5SDimitry Andric             SDep Dep(Load, SDep::Barrier);
9030b57cec5SDimitry Andric             Dep.setLatency(1);
9040b57cec5SDimitry Andric             SU.addPred(Dep);
9050b57cec5SDimitry Andric             continue;
9060b57cec5SDimitry Andric           }
9070b57cec5SDimitry Andric           if (MMO1->getValue() == MMO2->getValue() &&
9080b57cec5SDimitry Andric               MMO1->getOffset() <= MMO2->getOffset()) {
9090b57cec5SDimitry Andric             SDep Dep(Load, SDep::Barrier);
9100b57cec5SDimitry Andric             Dep.setLatency(1);
9110b57cec5SDimitry Andric             SU.addPred(Dep);
9120b57cec5SDimitry Andric             continue;
9130b57cec5SDimitry Andric           }
914fe6060f1SDimitry Andric           if (!AA->isNoAlias(
915e8d8bef9SDimitry Andric                   MemoryLocation::getAfter(MMO1->getValue(), MMO1->getAAInfo()),
916fe6060f1SDimitry Andric                   MemoryLocation::getAfter(MMO2->getValue(),
917fe6060f1SDimitry Andric                                            MMO2->getAAInfo()))) {
9180b57cec5SDimitry Andric             SDep Dep(Load, SDep::Barrier);
9190b57cec5SDimitry Andric             Dep.setLatency(1);
9200b57cec5SDimitry Andric             SU.addPred(Dep);
9210b57cec5SDimitry Andric           }
9220b57cec5SDimitry Andric         }
9230b57cec5SDimitry Andric       }
9240b57cec5SDimitry Andric     }
9250b57cec5SDimitry Andric   }
9260b57cec5SDimitry Andric }
9270b57cec5SDimitry Andric 
9280b57cec5SDimitry Andric /// Update the phi dependences to the DAG because ScheduleDAGInstrs no longer
9290b57cec5SDimitry Andric /// processes dependences for PHIs. This function adds true dependences
9300b57cec5SDimitry Andric /// from a PHI to a use, and a loop carried dependence from the use to the
9310b57cec5SDimitry Andric /// PHI. The loop carried dependence is represented as an anti dependence
9320b57cec5SDimitry Andric /// edge. This function also removes chain dependences between unrelated
9330b57cec5SDimitry Andric /// PHIs.
9340b57cec5SDimitry Andric void SwingSchedulerDAG::updatePhiDependences() {
9350b57cec5SDimitry Andric   SmallVector<SDep, 4> RemoveDeps;
9360b57cec5SDimitry Andric   const TargetSubtargetInfo &ST = MF.getSubtarget<TargetSubtargetInfo>();
9370b57cec5SDimitry Andric 
9380b57cec5SDimitry Andric   // Iterate over each DAG node.
9390b57cec5SDimitry Andric   for (SUnit &I : SUnits) {
9400b57cec5SDimitry Andric     RemoveDeps.clear();
9410b57cec5SDimitry Andric     // Set to true if the instruction has an operand defined by a Phi.
9420b57cec5SDimitry Andric     unsigned HasPhiUse = 0;
9430b57cec5SDimitry Andric     unsigned HasPhiDef = 0;
9440b57cec5SDimitry Andric     MachineInstr *MI = I.getInstr();
9450b57cec5SDimitry Andric     // Iterate over each operand, and we process the definitions.
94606c3fb27SDimitry Andric     for (const MachineOperand &MO : MI->operands()) {
94706c3fb27SDimitry Andric       if (!MO.isReg())
9480b57cec5SDimitry Andric         continue;
94906c3fb27SDimitry Andric       Register Reg = MO.getReg();
95006c3fb27SDimitry Andric       if (MO.isDef()) {
9510b57cec5SDimitry Andric         // If the register is used by a Phi, then create an anti dependence.
9520b57cec5SDimitry Andric         for (MachineRegisterInfo::use_instr_iterator
9530b57cec5SDimitry Andric                  UI = MRI.use_instr_begin(Reg),
9540b57cec5SDimitry Andric                  UE = MRI.use_instr_end();
9550b57cec5SDimitry Andric              UI != UE; ++UI) {
9560b57cec5SDimitry Andric           MachineInstr *UseMI = &*UI;
9570b57cec5SDimitry Andric           SUnit *SU = getSUnit(UseMI);
9580b57cec5SDimitry Andric           if (SU != nullptr && UseMI->isPHI()) {
9590b57cec5SDimitry Andric             if (!MI->isPHI()) {
9600b57cec5SDimitry Andric               SDep Dep(SU, SDep::Anti, Reg);
9610b57cec5SDimitry Andric               Dep.setLatency(1);
9620b57cec5SDimitry Andric               I.addPred(Dep);
9630b57cec5SDimitry Andric             } else {
9640b57cec5SDimitry Andric               HasPhiDef = Reg;
9650b57cec5SDimitry Andric               // Add a chain edge to a dependent Phi that isn't an existing
9660b57cec5SDimitry Andric               // predecessor.
9670b57cec5SDimitry Andric               if (SU->NodeNum < I.NodeNum && !I.isPred(SU))
9680b57cec5SDimitry Andric                 I.addPred(SDep(SU, SDep::Barrier));
9690b57cec5SDimitry Andric             }
9700b57cec5SDimitry Andric           }
9710b57cec5SDimitry Andric         }
97206c3fb27SDimitry Andric       } else if (MO.isUse()) {
9730b57cec5SDimitry Andric         // If the register is defined by a Phi, then create a true dependence.
9740b57cec5SDimitry Andric         MachineInstr *DefMI = MRI.getUniqueVRegDef(Reg);
9750b57cec5SDimitry Andric         if (DefMI == nullptr)
9760b57cec5SDimitry Andric           continue;
9770b57cec5SDimitry Andric         SUnit *SU = getSUnit(DefMI);
9780b57cec5SDimitry Andric         if (SU != nullptr && DefMI->isPHI()) {
9790b57cec5SDimitry Andric           if (!MI->isPHI()) {
9800b57cec5SDimitry Andric             SDep Dep(SU, SDep::Data, Reg);
9810b57cec5SDimitry Andric             Dep.setLatency(0);
9820fca6ea1SDimitry Andric             ST.adjustSchedDependency(SU, 0, &I, MO.getOperandNo(), Dep,
9830fca6ea1SDimitry Andric                                      &SchedModel);
9840b57cec5SDimitry Andric             I.addPred(Dep);
9850b57cec5SDimitry Andric           } else {
9860b57cec5SDimitry Andric             HasPhiUse = Reg;
9870b57cec5SDimitry Andric             // Add a chain edge to a dependent Phi that isn't an existing
9880b57cec5SDimitry Andric             // predecessor.
9890b57cec5SDimitry Andric             if (SU->NodeNum < I.NodeNum && !I.isPred(SU))
9900b57cec5SDimitry Andric               I.addPred(SDep(SU, SDep::Barrier));
9910b57cec5SDimitry Andric           }
9920b57cec5SDimitry Andric         }
9930b57cec5SDimitry Andric       }
9940b57cec5SDimitry Andric     }
9950b57cec5SDimitry Andric     // Remove order dependences from an unrelated Phi.
9960b57cec5SDimitry Andric     if (!SwpPruneDeps)
9970b57cec5SDimitry Andric       continue;
9980b57cec5SDimitry Andric     for (auto &PI : I.Preds) {
9990b57cec5SDimitry Andric       MachineInstr *PMI = PI.getSUnit()->getInstr();
10000b57cec5SDimitry Andric       if (PMI->isPHI() && PI.getKind() == SDep::Order) {
10010b57cec5SDimitry Andric         if (I.getInstr()->isPHI()) {
10020b57cec5SDimitry Andric           if (PMI->getOperand(0).getReg() == HasPhiUse)
10030b57cec5SDimitry Andric             continue;
10040b57cec5SDimitry Andric           if (getLoopPhiReg(*PMI, PMI->getParent()) == HasPhiDef)
10050b57cec5SDimitry Andric             continue;
10060b57cec5SDimitry Andric         }
10070b57cec5SDimitry Andric         RemoveDeps.push_back(PI);
10080b57cec5SDimitry Andric       }
10090b57cec5SDimitry Andric     }
10100fca6ea1SDimitry Andric     for (const SDep &D : RemoveDeps)
10110fca6ea1SDimitry Andric       I.removePred(D);
10120b57cec5SDimitry Andric   }
10130b57cec5SDimitry Andric }
10140b57cec5SDimitry Andric 
10150b57cec5SDimitry Andric /// Iterate over each DAG node and see if we can change any dependences
10160b57cec5SDimitry Andric /// in order to reduce the recurrence MII.
10170b57cec5SDimitry Andric void SwingSchedulerDAG::changeDependences() {
10180b57cec5SDimitry Andric   // See if an instruction can use a value from the previous iteration.
10190b57cec5SDimitry Andric   // If so, we update the base and offset of the instruction and change
10200b57cec5SDimitry Andric   // the dependences.
10210b57cec5SDimitry Andric   for (SUnit &I : SUnits) {
10220b57cec5SDimitry Andric     unsigned BasePos = 0, OffsetPos = 0, NewBase = 0;
10230b57cec5SDimitry Andric     int64_t NewOffset = 0;
10240b57cec5SDimitry Andric     if (!canUseLastOffsetValue(I.getInstr(), BasePos, OffsetPos, NewBase,
10250b57cec5SDimitry Andric                                NewOffset))
10260b57cec5SDimitry Andric       continue;
10270b57cec5SDimitry Andric 
10280b57cec5SDimitry Andric     // Get the MI and SUnit for the instruction that defines the original base.
10298bcb0991SDimitry Andric     Register OrigBase = I.getInstr()->getOperand(BasePos).getReg();
10300b57cec5SDimitry Andric     MachineInstr *DefMI = MRI.getUniqueVRegDef(OrigBase);
10310b57cec5SDimitry Andric     if (!DefMI)
10320b57cec5SDimitry Andric       continue;
10330b57cec5SDimitry Andric     SUnit *DefSU = getSUnit(DefMI);
10340b57cec5SDimitry Andric     if (!DefSU)
10350b57cec5SDimitry Andric       continue;
10360b57cec5SDimitry Andric     // Get the MI and SUnit for the instruction that defins the new base.
10370b57cec5SDimitry Andric     MachineInstr *LastMI = MRI.getUniqueVRegDef(NewBase);
10380b57cec5SDimitry Andric     if (!LastMI)
10390b57cec5SDimitry Andric       continue;
10400b57cec5SDimitry Andric     SUnit *LastSU = getSUnit(LastMI);
10410b57cec5SDimitry Andric     if (!LastSU)
10420b57cec5SDimitry Andric       continue;
10430b57cec5SDimitry Andric 
10440b57cec5SDimitry Andric     if (Topo.IsReachable(&I, LastSU))
10450b57cec5SDimitry Andric       continue;
10460b57cec5SDimitry Andric 
10470b57cec5SDimitry Andric     // Remove the dependence. The value now depends on a prior iteration.
10480b57cec5SDimitry Andric     SmallVector<SDep, 4> Deps;
1049fe6060f1SDimitry Andric     for (const SDep &P : I.Preds)
1050fe6060f1SDimitry Andric       if (P.getSUnit() == DefSU)
1051fe6060f1SDimitry Andric         Deps.push_back(P);
10520fca6ea1SDimitry Andric     for (const SDep &D : Deps) {
10530fca6ea1SDimitry Andric       Topo.RemovePred(&I, D.getSUnit());
10540fca6ea1SDimitry Andric       I.removePred(D);
10550b57cec5SDimitry Andric     }
10560b57cec5SDimitry Andric     // Remove the chain dependence between the instructions.
10570b57cec5SDimitry Andric     Deps.clear();
10580b57cec5SDimitry Andric     for (auto &P : LastSU->Preds)
10590b57cec5SDimitry Andric       if (P.getSUnit() == &I && P.getKind() == SDep::Order)
10600b57cec5SDimitry Andric         Deps.push_back(P);
10610fca6ea1SDimitry Andric     for (const SDep &D : Deps) {
10620fca6ea1SDimitry Andric       Topo.RemovePred(LastSU, D.getSUnit());
10630fca6ea1SDimitry Andric       LastSU->removePred(D);
10640b57cec5SDimitry Andric     }
10650b57cec5SDimitry Andric 
10660b57cec5SDimitry Andric     // Add a dependence between the new instruction and the instruction
10670b57cec5SDimitry Andric     // that defines the new base.
10680b57cec5SDimitry Andric     SDep Dep(&I, SDep::Anti, NewBase);
10690b57cec5SDimitry Andric     Topo.AddPred(LastSU, &I);
10700b57cec5SDimitry Andric     LastSU->addPred(Dep);
10710b57cec5SDimitry Andric 
10720b57cec5SDimitry Andric     // Remember the base and offset information so that we can update the
10730b57cec5SDimitry Andric     // instruction during code generation.
10740b57cec5SDimitry Andric     InstrChanges[&I] = std::make_pair(NewBase, NewOffset);
10750b57cec5SDimitry Andric   }
10760b57cec5SDimitry Andric }
10770b57cec5SDimitry Andric 
10787a6dacacSDimitry Andric /// Create an instruction stream that represents a single iteration and stage of
10797a6dacacSDimitry Andric /// each instruction. This function differs from SMSchedule::finalizeSchedule in
10807a6dacacSDimitry Andric /// that this doesn't have any side-effect to SwingSchedulerDAG. That is, this
10817a6dacacSDimitry Andric /// function is an approximation of SMSchedule::finalizeSchedule with all
10827a6dacacSDimitry Andric /// non-const operations removed.
10837a6dacacSDimitry Andric static void computeScheduledInsts(const SwingSchedulerDAG *SSD,
10847a6dacacSDimitry Andric                                   SMSchedule &Schedule,
10857a6dacacSDimitry Andric                                   std::vector<MachineInstr *> &OrderedInsts,
10867a6dacacSDimitry Andric                                   DenseMap<MachineInstr *, unsigned> &Stages) {
10877a6dacacSDimitry Andric   DenseMap<int, std::deque<SUnit *>> Instrs;
10887a6dacacSDimitry Andric 
10897a6dacacSDimitry Andric   // Move all instructions to the first stage from the later stages.
10907a6dacacSDimitry Andric   for (int Cycle = Schedule.getFirstCycle(); Cycle <= Schedule.getFinalCycle();
10917a6dacacSDimitry Andric        ++Cycle) {
10927a6dacacSDimitry Andric     for (int Stage = 0, LastStage = Schedule.getMaxStageCount();
10937a6dacacSDimitry Andric          Stage <= LastStage; ++Stage) {
10947a6dacacSDimitry Andric       for (SUnit *SU : llvm::reverse(Schedule.getInstructions(
10957a6dacacSDimitry Andric                Cycle + Stage * Schedule.getInitiationInterval()))) {
10967a6dacacSDimitry Andric         Instrs[Cycle].push_front(SU);
10977a6dacacSDimitry Andric       }
10987a6dacacSDimitry Andric     }
10997a6dacacSDimitry Andric   }
11007a6dacacSDimitry Andric 
11017a6dacacSDimitry Andric   for (int Cycle = Schedule.getFirstCycle(); Cycle <= Schedule.getFinalCycle();
11027a6dacacSDimitry Andric        ++Cycle) {
11037a6dacacSDimitry Andric     std::deque<SUnit *> &CycleInstrs = Instrs[Cycle];
11047a6dacacSDimitry Andric     CycleInstrs = Schedule.reorderInstructions(SSD, CycleInstrs);
11057a6dacacSDimitry Andric     for (SUnit *SU : CycleInstrs) {
11067a6dacacSDimitry Andric       MachineInstr *MI = SU->getInstr();
11077a6dacacSDimitry Andric       OrderedInsts.push_back(MI);
11087a6dacacSDimitry Andric       Stages[MI] = Schedule.stageScheduled(SU);
11097a6dacacSDimitry Andric     }
11107a6dacacSDimitry Andric   }
11117a6dacacSDimitry Andric }
11127a6dacacSDimitry Andric 
11130b57cec5SDimitry Andric namespace {
11140b57cec5SDimitry Andric 
11150b57cec5SDimitry Andric // FuncUnitSorter - Comparison operator used to sort instructions by
11160b57cec5SDimitry Andric // the number of functional unit choices.
11170b57cec5SDimitry Andric struct FuncUnitSorter {
11180b57cec5SDimitry Andric   const InstrItineraryData *InstrItins;
11190b57cec5SDimitry Andric   const MCSubtargetInfo *STI;
11205ffd83dbSDimitry Andric   DenseMap<InstrStage::FuncUnits, unsigned> Resources;
11210b57cec5SDimitry Andric 
11220b57cec5SDimitry Andric   FuncUnitSorter(const TargetSubtargetInfo &TSI)
11230b57cec5SDimitry Andric       : InstrItins(TSI.getInstrItineraryData()), STI(&TSI) {}
11240b57cec5SDimitry Andric 
11250b57cec5SDimitry Andric   // Compute the number of functional unit alternatives needed
11260b57cec5SDimitry Andric   // at each stage, and take the minimum value. We prioritize the
11270b57cec5SDimitry Andric   // instructions by the least number of choices first.
11285ffd83dbSDimitry Andric   unsigned minFuncUnits(const MachineInstr *Inst,
11295ffd83dbSDimitry Andric                         InstrStage::FuncUnits &F) const {
11300b57cec5SDimitry Andric     unsigned SchedClass = Inst->getDesc().getSchedClass();
11310b57cec5SDimitry Andric     unsigned min = UINT_MAX;
11320b57cec5SDimitry Andric     if (InstrItins && !InstrItins->isEmpty()) {
11330b57cec5SDimitry Andric       for (const InstrStage &IS :
11340b57cec5SDimitry Andric            make_range(InstrItins->beginStage(SchedClass),
11350b57cec5SDimitry Andric                       InstrItins->endStage(SchedClass))) {
11365ffd83dbSDimitry Andric         InstrStage::FuncUnits funcUnits = IS.getUnits();
1137bdd1243dSDimitry Andric         unsigned numAlternatives = llvm::popcount(funcUnits);
11380b57cec5SDimitry Andric         if (numAlternatives < min) {
11390b57cec5SDimitry Andric           min = numAlternatives;
11400b57cec5SDimitry Andric           F = funcUnits;
11410b57cec5SDimitry Andric         }
11420b57cec5SDimitry Andric       }
11430b57cec5SDimitry Andric       return min;
11440b57cec5SDimitry Andric     }
11450b57cec5SDimitry Andric     if (STI && STI->getSchedModel().hasInstrSchedModel()) {
11460b57cec5SDimitry Andric       const MCSchedClassDesc *SCDesc =
11470b57cec5SDimitry Andric           STI->getSchedModel().getSchedClassDesc(SchedClass);
11480b57cec5SDimitry Andric       if (!SCDesc->isValid())
11490b57cec5SDimitry Andric         // No valid Schedule Class Desc for schedClass, should be
11500b57cec5SDimitry Andric         // Pseudo/PostRAPseudo
11510b57cec5SDimitry Andric         return min;
11520b57cec5SDimitry Andric 
11530b57cec5SDimitry Andric       for (const MCWriteProcResEntry &PRE :
11540b57cec5SDimitry Andric            make_range(STI->getWriteProcResBegin(SCDesc),
11550b57cec5SDimitry Andric                       STI->getWriteProcResEnd(SCDesc))) {
11565f757f3fSDimitry Andric         if (!PRE.ReleaseAtCycle)
11570b57cec5SDimitry Andric           continue;
11580b57cec5SDimitry Andric         const MCProcResourceDesc *ProcResource =
11590b57cec5SDimitry Andric             STI->getSchedModel().getProcResource(PRE.ProcResourceIdx);
11600b57cec5SDimitry Andric         unsigned NumUnits = ProcResource->NumUnits;
11610b57cec5SDimitry Andric         if (NumUnits < min) {
11620b57cec5SDimitry Andric           min = NumUnits;
11630b57cec5SDimitry Andric           F = PRE.ProcResourceIdx;
11640b57cec5SDimitry Andric         }
11650b57cec5SDimitry Andric       }
11660b57cec5SDimitry Andric       return min;
11670b57cec5SDimitry Andric     }
11680b57cec5SDimitry Andric     llvm_unreachable("Should have non-empty InstrItins or hasInstrSchedModel!");
11690b57cec5SDimitry Andric   }
11700b57cec5SDimitry Andric 
11710b57cec5SDimitry Andric   // Compute the critical resources needed by the instruction. This
11720b57cec5SDimitry Andric   // function records the functional units needed by instructions that
11730b57cec5SDimitry Andric   // must use only one functional unit. We use this as a tie breaker
11740b57cec5SDimitry Andric   // for computing the resource MII. The instrutions that require
11750b57cec5SDimitry Andric   // the same, highly used, functional unit have high priority.
11760b57cec5SDimitry Andric   void calcCriticalResources(MachineInstr &MI) {
11770b57cec5SDimitry Andric     unsigned SchedClass = MI.getDesc().getSchedClass();
11780b57cec5SDimitry Andric     if (InstrItins && !InstrItins->isEmpty()) {
11790b57cec5SDimitry Andric       for (const InstrStage &IS :
11800b57cec5SDimitry Andric            make_range(InstrItins->beginStage(SchedClass),
11810b57cec5SDimitry Andric                       InstrItins->endStage(SchedClass))) {
11825ffd83dbSDimitry Andric         InstrStage::FuncUnits FuncUnits = IS.getUnits();
1183bdd1243dSDimitry Andric         if (llvm::popcount(FuncUnits) == 1)
11840b57cec5SDimitry Andric           Resources[FuncUnits]++;
11850b57cec5SDimitry Andric       }
11860b57cec5SDimitry Andric       return;
11870b57cec5SDimitry Andric     }
11880b57cec5SDimitry Andric     if (STI && STI->getSchedModel().hasInstrSchedModel()) {
11890b57cec5SDimitry Andric       const MCSchedClassDesc *SCDesc =
11900b57cec5SDimitry Andric           STI->getSchedModel().getSchedClassDesc(SchedClass);
11910b57cec5SDimitry Andric       if (!SCDesc->isValid())
11920b57cec5SDimitry Andric         // No valid Schedule Class Desc for schedClass, should be
11930b57cec5SDimitry Andric         // Pseudo/PostRAPseudo
11940b57cec5SDimitry Andric         return;
11950b57cec5SDimitry Andric 
11960b57cec5SDimitry Andric       for (const MCWriteProcResEntry &PRE :
11970b57cec5SDimitry Andric            make_range(STI->getWriteProcResBegin(SCDesc),
11980b57cec5SDimitry Andric                       STI->getWriteProcResEnd(SCDesc))) {
11995f757f3fSDimitry Andric         if (!PRE.ReleaseAtCycle)
12000b57cec5SDimitry Andric           continue;
12010b57cec5SDimitry Andric         Resources[PRE.ProcResourceIdx]++;
12020b57cec5SDimitry Andric       }
12030b57cec5SDimitry Andric       return;
12040b57cec5SDimitry Andric     }
12050b57cec5SDimitry Andric     llvm_unreachable("Should have non-empty InstrItins or hasInstrSchedModel!");
12060b57cec5SDimitry Andric   }
12070b57cec5SDimitry Andric 
12080b57cec5SDimitry Andric   /// Return true if IS1 has less priority than IS2.
12090b57cec5SDimitry Andric   bool operator()(const MachineInstr *IS1, const MachineInstr *IS2) const {
12105ffd83dbSDimitry Andric     InstrStage::FuncUnits F1 = 0, F2 = 0;
12110b57cec5SDimitry Andric     unsigned MFUs1 = minFuncUnits(IS1, F1);
12120b57cec5SDimitry Andric     unsigned MFUs2 = minFuncUnits(IS2, F2);
12138bcb0991SDimitry Andric     if (MFUs1 == MFUs2)
12140b57cec5SDimitry Andric       return Resources.lookup(F1) < Resources.lookup(F2);
12150b57cec5SDimitry Andric     return MFUs1 > MFUs2;
12160b57cec5SDimitry Andric   }
12170b57cec5SDimitry Andric };
12180b57cec5SDimitry Andric 
12197a6dacacSDimitry Andric /// Calculate the maximum register pressure of the scheduled instructions stream
12207a6dacacSDimitry Andric class HighRegisterPressureDetector {
12217a6dacacSDimitry Andric   MachineBasicBlock *OrigMBB;
12227a6dacacSDimitry Andric   const MachineFunction &MF;
12237a6dacacSDimitry Andric   const MachineRegisterInfo &MRI;
12247a6dacacSDimitry Andric   const TargetRegisterInfo *TRI;
12257a6dacacSDimitry Andric 
12267a6dacacSDimitry Andric   const unsigned PSetNum;
12277a6dacacSDimitry Andric 
12287a6dacacSDimitry Andric   // Indexed by PSet ID
12297a6dacacSDimitry Andric   // InitSetPressure takes into account the register pressure of live-in
12307a6dacacSDimitry Andric   // registers. It's not depend on how the loop is scheduled, so it's enough to
12317a6dacacSDimitry Andric   // calculate them once at the beginning.
12327a6dacacSDimitry Andric   std::vector<unsigned> InitSetPressure;
12337a6dacacSDimitry Andric 
12347a6dacacSDimitry Andric   // Indexed by PSet ID
12357a6dacacSDimitry Andric   // Upper limit for each register pressure set
12367a6dacacSDimitry Andric   std::vector<unsigned> PressureSetLimit;
12377a6dacacSDimitry Andric 
12387a6dacacSDimitry Andric   DenseMap<MachineInstr *, RegisterOperands> ROMap;
12397a6dacacSDimitry Andric 
12407a6dacacSDimitry Andric   using Instr2LastUsesTy = DenseMap<MachineInstr *, SmallDenseSet<Register, 4>>;
12417a6dacacSDimitry Andric 
12427a6dacacSDimitry Andric public:
12437a6dacacSDimitry Andric   using OrderedInstsTy = std::vector<MachineInstr *>;
12447a6dacacSDimitry Andric   using Instr2StageTy = DenseMap<MachineInstr *, unsigned>;
12457a6dacacSDimitry Andric 
12467a6dacacSDimitry Andric private:
12477a6dacacSDimitry Andric   static void dumpRegisterPressures(const std::vector<unsigned> &Pressures) {
12487a6dacacSDimitry Andric     if (Pressures.size() == 0) {
12497a6dacacSDimitry Andric       dbgs() << "[]";
12507a6dacacSDimitry Andric     } else {
12517a6dacacSDimitry Andric       char Prefix = '[';
12527a6dacacSDimitry Andric       for (unsigned P : Pressures) {
12537a6dacacSDimitry Andric         dbgs() << Prefix << P;
12547a6dacacSDimitry Andric         Prefix = ' ';
12557a6dacacSDimitry Andric       }
12567a6dacacSDimitry Andric       dbgs() << ']';
12577a6dacacSDimitry Andric     }
12587a6dacacSDimitry Andric   }
12597a6dacacSDimitry Andric 
12607a6dacacSDimitry Andric   void dumpPSet(Register Reg) const {
12617a6dacacSDimitry Andric     dbgs() << "Reg=" << printReg(Reg, TRI, 0, &MRI) << " PSet=";
12627a6dacacSDimitry Andric     for (auto PSetIter = MRI.getPressureSets(Reg); PSetIter.isValid();
12637a6dacacSDimitry Andric          ++PSetIter) {
12647a6dacacSDimitry Andric       dbgs() << *PSetIter << ' ';
12657a6dacacSDimitry Andric     }
12667a6dacacSDimitry Andric     dbgs() << '\n';
12677a6dacacSDimitry Andric   }
12687a6dacacSDimitry Andric 
12697a6dacacSDimitry Andric   void increaseRegisterPressure(std::vector<unsigned> &Pressure,
12707a6dacacSDimitry Andric                                 Register Reg) const {
12717a6dacacSDimitry Andric     auto PSetIter = MRI.getPressureSets(Reg);
12727a6dacacSDimitry Andric     unsigned Weight = PSetIter.getWeight();
12737a6dacacSDimitry Andric     for (; PSetIter.isValid(); ++PSetIter)
12747a6dacacSDimitry Andric       Pressure[*PSetIter] += Weight;
12757a6dacacSDimitry Andric   }
12767a6dacacSDimitry Andric 
12777a6dacacSDimitry Andric   void decreaseRegisterPressure(std::vector<unsigned> &Pressure,
12787a6dacacSDimitry Andric                                 Register Reg) const {
12797a6dacacSDimitry Andric     auto PSetIter = MRI.getPressureSets(Reg);
12807a6dacacSDimitry Andric     unsigned Weight = PSetIter.getWeight();
12817a6dacacSDimitry Andric     for (; PSetIter.isValid(); ++PSetIter) {
12827a6dacacSDimitry Andric       auto &P = Pressure[*PSetIter];
12837a6dacacSDimitry Andric       assert(P >= Weight &&
12847a6dacacSDimitry Andric              "register pressure must be greater than or equal weight");
12857a6dacacSDimitry Andric       P -= Weight;
12867a6dacacSDimitry Andric     }
12877a6dacacSDimitry Andric   }
12887a6dacacSDimitry Andric 
12897a6dacacSDimitry Andric   // Return true if Reg is fixed one, for example, stack pointer
12907a6dacacSDimitry Andric   bool isFixedRegister(Register Reg) const {
12917a6dacacSDimitry Andric     return Reg.isPhysical() && TRI->isFixedRegister(MF, Reg.asMCReg());
12927a6dacacSDimitry Andric   }
12937a6dacacSDimitry Andric 
12947a6dacacSDimitry Andric   bool isDefinedInThisLoop(Register Reg) const {
12957a6dacacSDimitry Andric     return Reg.isVirtual() && MRI.getVRegDef(Reg)->getParent() == OrigMBB;
12967a6dacacSDimitry Andric   }
12977a6dacacSDimitry Andric 
12987a6dacacSDimitry Andric   // Search for live-in variables. They are factored into the register pressure
12997a6dacacSDimitry Andric   // from the begining. Live-in variables used by every iteration should be
13007a6dacacSDimitry Andric   // considered as alive throughout the loop. For example, the variable `c` in
13017a6dacacSDimitry Andric   // following code. \code
13027a6dacacSDimitry Andric   //   int c = ...;
13037a6dacacSDimitry Andric   //   for (int i = 0; i < n; i++)
13047a6dacacSDimitry Andric   //     a[i] += b[i] + c;
13057a6dacacSDimitry Andric   // \endcode
13067a6dacacSDimitry Andric   void computeLiveIn() {
13077a6dacacSDimitry Andric     DenseSet<Register> Used;
13087a6dacacSDimitry Andric     for (auto &MI : *OrigMBB) {
13097a6dacacSDimitry Andric       if (MI.isDebugInstr())
13107a6dacacSDimitry Andric         continue;
13110fca6ea1SDimitry Andric       for (auto &Use : ROMap[&MI].Uses) {
13127a6dacacSDimitry Andric         auto Reg = Use.RegUnit;
13137a6dacacSDimitry Andric         // Ignore the variable that appears only on one side of phi instruction
13147a6dacacSDimitry Andric         // because it's used only at the first iteration.
13157a6dacacSDimitry Andric         if (MI.isPHI() && Reg != getLoopPhiReg(MI, OrigMBB))
13167a6dacacSDimitry Andric           continue;
13177a6dacacSDimitry Andric         if (isFixedRegister(Reg))
13187a6dacacSDimitry Andric           continue;
13197a6dacacSDimitry Andric         if (isDefinedInThisLoop(Reg))
13207a6dacacSDimitry Andric           continue;
13217a6dacacSDimitry Andric         Used.insert(Reg);
13227a6dacacSDimitry Andric       }
13237a6dacacSDimitry Andric     }
13247a6dacacSDimitry Andric 
13257a6dacacSDimitry Andric     for (auto LiveIn : Used)
13267a6dacacSDimitry Andric       increaseRegisterPressure(InitSetPressure, LiveIn);
13277a6dacacSDimitry Andric   }
13287a6dacacSDimitry Andric 
13297a6dacacSDimitry Andric   // Calculate the upper limit of each pressure set
13307a6dacacSDimitry Andric   void computePressureSetLimit(const RegisterClassInfo &RCI) {
13317a6dacacSDimitry Andric     for (unsigned PSet = 0; PSet < PSetNum; PSet++)
13320fca6ea1SDimitry Andric       PressureSetLimit[PSet] = TRI->getRegPressureSetLimit(MF, PSet);
13337a6dacacSDimitry Andric 
13347a6dacacSDimitry Andric     // We assume fixed registers, such as stack pointer, are already in use.
13357a6dacacSDimitry Andric     // Therefore subtracting the weight of the fixed registers from the limit of
13367a6dacacSDimitry Andric     // each pressure set in advance.
13377a6dacacSDimitry Andric     SmallDenseSet<Register, 8> FixedRegs;
13387a6dacacSDimitry Andric     for (const TargetRegisterClass *TRC : TRI->regclasses()) {
13397a6dacacSDimitry Andric       for (const MCPhysReg Reg : *TRC)
13407a6dacacSDimitry Andric         if (isFixedRegister(Reg))
13417a6dacacSDimitry Andric           FixedRegs.insert(Reg);
13427a6dacacSDimitry Andric     }
13437a6dacacSDimitry Andric 
13447a6dacacSDimitry Andric     LLVM_DEBUG({
13457a6dacacSDimitry Andric       for (auto Reg : FixedRegs) {
13467a6dacacSDimitry Andric         dbgs() << printReg(Reg, TRI, 0, &MRI) << ": [";
13477a6dacacSDimitry Andric         const int *Sets = TRI->getRegUnitPressureSets(Reg);
13487a6dacacSDimitry Andric         for (; *Sets != -1; Sets++) {
13497a6dacacSDimitry Andric           dbgs() << TRI->getRegPressureSetName(*Sets) << ", ";
13507a6dacacSDimitry Andric         }
13517a6dacacSDimitry Andric         dbgs() << "]\n";
13527a6dacacSDimitry Andric       }
13537a6dacacSDimitry Andric     });
13547a6dacacSDimitry Andric 
13557a6dacacSDimitry Andric     for (auto Reg : FixedRegs) {
13567a6dacacSDimitry Andric       LLVM_DEBUG(dbgs() << "fixed register: " << printReg(Reg, TRI, 0, &MRI)
13577a6dacacSDimitry Andric                         << "\n");
13587a6dacacSDimitry Andric       auto PSetIter = MRI.getPressureSets(Reg);
13597a6dacacSDimitry Andric       unsigned Weight = PSetIter.getWeight();
13607a6dacacSDimitry Andric       for (; PSetIter.isValid(); ++PSetIter) {
13617a6dacacSDimitry Andric         unsigned &Limit = PressureSetLimit[*PSetIter];
13627a6dacacSDimitry Andric         assert(Limit >= Weight &&
13637a6dacacSDimitry Andric                "register pressure limit must be greater than or equal weight");
13647a6dacacSDimitry Andric         Limit -= Weight;
13657a6dacacSDimitry Andric         LLVM_DEBUG(dbgs() << "PSet=" << *PSetIter << " Limit=" << Limit
13667a6dacacSDimitry Andric                           << " (decreased by " << Weight << ")\n");
13677a6dacacSDimitry Andric       }
13687a6dacacSDimitry Andric     }
13697a6dacacSDimitry Andric   }
13707a6dacacSDimitry Andric 
13717a6dacacSDimitry Andric   // There are two patterns of last-use.
13727a6dacacSDimitry Andric   //   - by an instruction of the current iteration
13737a6dacacSDimitry Andric   //   - by a phi instruction of the next iteration (loop carried value)
13747a6dacacSDimitry Andric   //
13757a6dacacSDimitry Andric   // Furthermore, following two groups of instructions are executed
13767a6dacacSDimitry Andric   // simultaneously
13777a6dacacSDimitry Andric   //   - next iteration's phi instructions in i-th stage
13787a6dacacSDimitry Andric   //   - current iteration's instructions in i+1-th stage
13797a6dacacSDimitry Andric   //
13807a6dacacSDimitry Andric   // This function calculates the last-use of each register while taking into
13817a6dacacSDimitry Andric   // account the above two patterns.
13827a6dacacSDimitry Andric   Instr2LastUsesTy computeLastUses(const OrderedInstsTy &OrderedInsts,
13837a6dacacSDimitry Andric                                    Instr2StageTy &Stages) const {
13847a6dacacSDimitry Andric     // We treat virtual registers that are defined and used in this loop.
13857a6dacacSDimitry Andric     // Following virtual register will be ignored
13867a6dacacSDimitry Andric     //   - live-in one
13877a6dacacSDimitry Andric     //   - defined but not used in the loop (potentially live-out)
13887a6dacacSDimitry Andric     DenseSet<Register> TargetRegs;
13897a6dacacSDimitry Andric     const auto UpdateTargetRegs = [this, &TargetRegs](Register Reg) {
13907a6dacacSDimitry Andric       if (isDefinedInThisLoop(Reg))
13917a6dacacSDimitry Andric         TargetRegs.insert(Reg);
13927a6dacacSDimitry Andric     };
13937a6dacacSDimitry Andric     for (MachineInstr *MI : OrderedInsts) {
13947a6dacacSDimitry Andric       if (MI->isPHI()) {
13957a6dacacSDimitry Andric         Register Reg = getLoopPhiReg(*MI, OrigMBB);
13967a6dacacSDimitry Andric         UpdateTargetRegs(Reg);
13977a6dacacSDimitry Andric       } else {
13980fca6ea1SDimitry Andric         for (auto &Use : ROMap.find(MI)->getSecond().Uses)
13997a6dacacSDimitry Andric           UpdateTargetRegs(Use.RegUnit);
14007a6dacacSDimitry Andric       }
14017a6dacacSDimitry Andric     }
14027a6dacacSDimitry Andric 
14037a6dacacSDimitry Andric     const auto InstrScore = [&Stages](MachineInstr *MI) {
14047a6dacacSDimitry Andric       return Stages[MI] + MI->isPHI();
14057a6dacacSDimitry Andric     };
14067a6dacacSDimitry Andric 
14077a6dacacSDimitry Andric     DenseMap<Register, MachineInstr *> LastUseMI;
14087a6dacacSDimitry Andric     for (MachineInstr *MI : llvm::reverse(OrderedInsts)) {
14090fca6ea1SDimitry Andric       for (auto &Use : ROMap.find(MI)->getSecond().Uses) {
14107a6dacacSDimitry Andric         auto Reg = Use.RegUnit;
14117a6dacacSDimitry Andric         if (!TargetRegs.contains(Reg))
14127a6dacacSDimitry Andric           continue;
14137a6dacacSDimitry Andric         auto Ite = LastUseMI.find(Reg);
14147a6dacacSDimitry Andric         if (Ite == LastUseMI.end()) {
14157a6dacacSDimitry Andric           LastUseMI[Reg] = MI;
14167a6dacacSDimitry Andric         } else {
14177a6dacacSDimitry Andric           MachineInstr *Orig = Ite->second;
14187a6dacacSDimitry Andric           MachineInstr *New = MI;
14197a6dacacSDimitry Andric           if (InstrScore(Orig) < InstrScore(New))
14207a6dacacSDimitry Andric             LastUseMI[Reg] = New;
14217a6dacacSDimitry Andric         }
14227a6dacacSDimitry Andric       }
14237a6dacacSDimitry Andric     }
14247a6dacacSDimitry Andric 
14257a6dacacSDimitry Andric     Instr2LastUsesTy LastUses;
14267a6dacacSDimitry Andric     for (auto &Entry : LastUseMI)
14277a6dacacSDimitry Andric       LastUses[Entry.second].insert(Entry.first);
14287a6dacacSDimitry Andric     return LastUses;
14297a6dacacSDimitry Andric   }
14307a6dacacSDimitry Andric 
14317a6dacacSDimitry Andric   // Compute the maximum register pressure of the kernel. We'll simulate #Stage
14327a6dacacSDimitry Andric   // iterations and check the register pressure at the point where all stages
14337a6dacacSDimitry Andric   // overlapping.
14347a6dacacSDimitry Andric   //
14357a6dacacSDimitry Andric   // An example of unrolled loop where #Stage is 4..
14367a6dacacSDimitry Andric   // Iter   i+0 i+1 i+2 i+3
14377a6dacacSDimitry Andric   // ------------------------
14387a6dacacSDimitry Andric   // Stage   0
14397a6dacacSDimitry Andric   // Stage   1   0
14407a6dacacSDimitry Andric   // Stage   2   1   0
14417a6dacacSDimitry Andric   // Stage   3   2   1   0  <- All stages overlap
14427a6dacacSDimitry Andric   //
14437a6dacacSDimitry Andric   std::vector<unsigned>
14447a6dacacSDimitry Andric   computeMaxSetPressure(const OrderedInstsTy &OrderedInsts,
14457a6dacacSDimitry Andric                         Instr2StageTy &Stages,
14467a6dacacSDimitry Andric                         const unsigned StageCount) const {
14477a6dacacSDimitry Andric     using RegSetTy = SmallDenseSet<Register, 16>;
14487a6dacacSDimitry Andric 
14497a6dacacSDimitry Andric     // Indexed by #Iter. To treat "local" variables of each stage separately, we
14507a6dacacSDimitry Andric     // manage the liveness of the registers independently by iterations.
14517a6dacacSDimitry Andric     SmallVector<RegSetTy> LiveRegSets(StageCount);
14527a6dacacSDimitry Andric 
14537a6dacacSDimitry Andric     auto CurSetPressure = InitSetPressure;
14547a6dacacSDimitry Andric     auto MaxSetPressure = InitSetPressure;
14557a6dacacSDimitry Andric     auto LastUses = computeLastUses(OrderedInsts, Stages);
14567a6dacacSDimitry Andric 
14577a6dacacSDimitry Andric     LLVM_DEBUG({
14587a6dacacSDimitry Andric       dbgs() << "Ordered instructions:\n";
14597a6dacacSDimitry Andric       for (MachineInstr *MI : OrderedInsts) {
14607a6dacacSDimitry Andric         dbgs() << "Stage " << Stages[MI] << ": ";
14617a6dacacSDimitry Andric         MI->dump();
14627a6dacacSDimitry Andric       }
14637a6dacacSDimitry Andric     });
14647a6dacacSDimitry Andric 
14657a6dacacSDimitry Andric     const auto InsertReg = [this, &CurSetPressure](RegSetTy &RegSet,
14667a6dacacSDimitry Andric                                                    Register Reg) {
14677a6dacacSDimitry Andric       if (!Reg.isValid() || isFixedRegister(Reg))
14687a6dacacSDimitry Andric         return;
14697a6dacacSDimitry Andric 
14707a6dacacSDimitry Andric       bool Inserted = RegSet.insert(Reg).second;
14717a6dacacSDimitry Andric       if (!Inserted)
14727a6dacacSDimitry Andric         return;
14737a6dacacSDimitry Andric 
14747a6dacacSDimitry Andric       LLVM_DEBUG(dbgs() << "insert " << printReg(Reg, TRI, 0, &MRI) << "\n");
14757a6dacacSDimitry Andric       increaseRegisterPressure(CurSetPressure, Reg);
14767a6dacacSDimitry Andric       LLVM_DEBUG(dumpPSet(Reg));
14777a6dacacSDimitry Andric     };
14787a6dacacSDimitry Andric 
14797a6dacacSDimitry Andric     const auto EraseReg = [this, &CurSetPressure](RegSetTy &RegSet,
14807a6dacacSDimitry Andric                                                   Register Reg) {
14817a6dacacSDimitry Andric       if (!Reg.isValid() || isFixedRegister(Reg))
14827a6dacacSDimitry Andric         return;
14837a6dacacSDimitry Andric 
14847a6dacacSDimitry Andric       // live-in register
14857a6dacacSDimitry Andric       if (!RegSet.contains(Reg))
14867a6dacacSDimitry Andric         return;
14877a6dacacSDimitry Andric 
14887a6dacacSDimitry Andric       LLVM_DEBUG(dbgs() << "erase " << printReg(Reg, TRI, 0, &MRI) << "\n");
14897a6dacacSDimitry Andric       RegSet.erase(Reg);
14907a6dacacSDimitry Andric       decreaseRegisterPressure(CurSetPressure, Reg);
14917a6dacacSDimitry Andric       LLVM_DEBUG(dumpPSet(Reg));
14927a6dacacSDimitry Andric     };
14937a6dacacSDimitry Andric 
14947a6dacacSDimitry Andric     for (unsigned I = 0; I < StageCount; I++) {
14957a6dacacSDimitry Andric       for (MachineInstr *MI : OrderedInsts) {
14967a6dacacSDimitry Andric         const auto Stage = Stages[MI];
14977a6dacacSDimitry Andric         if (I < Stage)
14987a6dacacSDimitry Andric           continue;
14997a6dacacSDimitry Andric 
15007a6dacacSDimitry Andric         const unsigned Iter = I - Stage;
15017a6dacacSDimitry Andric 
15020fca6ea1SDimitry Andric         for (auto &Def : ROMap.find(MI)->getSecond().Defs)
15037a6dacacSDimitry Andric           InsertReg(LiveRegSets[Iter], Def.RegUnit);
15047a6dacacSDimitry Andric 
15057a6dacacSDimitry Andric         for (auto LastUse : LastUses[MI]) {
15067a6dacacSDimitry Andric           if (MI->isPHI()) {
15077a6dacacSDimitry Andric             if (Iter != 0)
15087a6dacacSDimitry Andric               EraseReg(LiveRegSets[Iter - 1], LastUse);
15097a6dacacSDimitry Andric           } else {
15107a6dacacSDimitry Andric             EraseReg(LiveRegSets[Iter], LastUse);
15117a6dacacSDimitry Andric           }
15127a6dacacSDimitry Andric         }
15137a6dacacSDimitry Andric 
15147a6dacacSDimitry Andric         for (unsigned PSet = 0; PSet < PSetNum; PSet++)
15157a6dacacSDimitry Andric           MaxSetPressure[PSet] =
15167a6dacacSDimitry Andric               std::max(MaxSetPressure[PSet], CurSetPressure[PSet]);
15177a6dacacSDimitry Andric 
15187a6dacacSDimitry Andric         LLVM_DEBUG({
15197a6dacacSDimitry Andric           dbgs() << "CurSetPressure=";
15207a6dacacSDimitry Andric           dumpRegisterPressures(CurSetPressure);
15217a6dacacSDimitry Andric           dbgs() << " iter=" << Iter << " stage=" << Stage << ":";
15227a6dacacSDimitry Andric           MI->dump();
15237a6dacacSDimitry Andric         });
15247a6dacacSDimitry Andric       }
15257a6dacacSDimitry Andric     }
15267a6dacacSDimitry Andric 
15277a6dacacSDimitry Andric     return MaxSetPressure;
15287a6dacacSDimitry Andric   }
15297a6dacacSDimitry Andric 
15307a6dacacSDimitry Andric public:
15317a6dacacSDimitry Andric   HighRegisterPressureDetector(MachineBasicBlock *OrigMBB,
15327a6dacacSDimitry Andric                                const MachineFunction &MF)
15337a6dacacSDimitry Andric       : OrigMBB(OrigMBB), MF(MF), MRI(MF.getRegInfo()),
15347a6dacacSDimitry Andric         TRI(MF.getSubtarget().getRegisterInfo()),
15357a6dacacSDimitry Andric         PSetNum(TRI->getNumRegPressureSets()), InitSetPressure(PSetNum, 0),
15367a6dacacSDimitry Andric         PressureSetLimit(PSetNum, 0) {}
15377a6dacacSDimitry Andric 
15387a6dacacSDimitry Andric   // Used to calculate register pressure, which is independent of loop
15397a6dacacSDimitry Andric   // scheduling.
15407a6dacacSDimitry Andric   void init(const RegisterClassInfo &RCI) {
15417a6dacacSDimitry Andric     for (MachineInstr &MI : *OrigMBB) {
15427a6dacacSDimitry Andric       if (MI.isDebugInstr())
15437a6dacacSDimitry Andric         continue;
15447a6dacacSDimitry Andric       ROMap[&MI].collect(MI, *TRI, MRI, false, true);
15457a6dacacSDimitry Andric     }
15467a6dacacSDimitry Andric 
15477a6dacacSDimitry Andric     computeLiveIn();
15487a6dacacSDimitry Andric     computePressureSetLimit(RCI);
15497a6dacacSDimitry Andric   }
15507a6dacacSDimitry Andric 
15517a6dacacSDimitry Andric   // Calculate the maximum register pressures of the loop and check if they
15527a6dacacSDimitry Andric   // exceed the limit
15537a6dacacSDimitry Andric   bool detect(const SwingSchedulerDAG *SSD, SMSchedule &Schedule,
15547a6dacacSDimitry Andric               const unsigned MaxStage) const {
15557a6dacacSDimitry Andric     assert(0 <= RegPressureMargin && RegPressureMargin <= 100 &&
15567a6dacacSDimitry Andric            "the percentage of the margin must be between 0 to 100");
15577a6dacacSDimitry Andric 
15587a6dacacSDimitry Andric     OrderedInstsTy OrderedInsts;
15597a6dacacSDimitry Andric     Instr2StageTy Stages;
15607a6dacacSDimitry Andric     computeScheduledInsts(SSD, Schedule, OrderedInsts, Stages);
15617a6dacacSDimitry Andric     const auto MaxSetPressure =
15627a6dacacSDimitry Andric         computeMaxSetPressure(OrderedInsts, Stages, MaxStage + 1);
15637a6dacacSDimitry Andric 
15647a6dacacSDimitry Andric     LLVM_DEBUG({
15657a6dacacSDimitry Andric       dbgs() << "Dump MaxSetPressure:\n";
15667a6dacacSDimitry Andric       for (unsigned I = 0; I < MaxSetPressure.size(); I++) {
15677a6dacacSDimitry Andric         dbgs() << format("MaxSetPressure[%d]=%d\n", I, MaxSetPressure[I]);
15687a6dacacSDimitry Andric       }
15697a6dacacSDimitry Andric       dbgs() << '\n';
15707a6dacacSDimitry Andric     });
15717a6dacacSDimitry Andric 
15727a6dacacSDimitry Andric     for (unsigned PSet = 0; PSet < PSetNum; PSet++) {
15737a6dacacSDimitry Andric       unsigned Limit = PressureSetLimit[PSet];
15747a6dacacSDimitry Andric       unsigned Margin = Limit * RegPressureMargin / 100;
15757a6dacacSDimitry Andric       LLVM_DEBUG(dbgs() << "PSet=" << PSet << " Limit=" << Limit
15767a6dacacSDimitry Andric                         << " Margin=" << Margin << "\n");
15777a6dacacSDimitry Andric       if (Limit < MaxSetPressure[PSet] + Margin) {
15787a6dacacSDimitry Andric         LLVM_DEBUG(
15797a6dacacSDimitry Andric             dbgs()
15807a6dacacSDimitry Andric             << "Rejected the schedule because of too high register pressure\n");
15817a6dacacSDimitry Andric         return true;
15827a6dacacSDimitry Andric       }
15837a6dacacSDimitry Andric     }
15847a6dacacSDimitry Andric     return false;
15857a6dacacSDimitry Andric   }
15867a6dacacSDimitry Andric };
15877a6dacacSDimitry Andric 
15880b57cec5SDimitry Andric } // end anonymous namespace
15890b57cec5SDimitry Andric 
15900b57cec5SDimitry Andric /// Calculate the resource constrained minimum initiation interval for the
15910b57cec5SDimitry Andric /// specified loop. We use the DFA to model the resources needed for
15920b57cec5SDimitry Andric /// each instruction, and we ignore dependences. A different DFA is created
15930b57cec5SDimitry Andric /// for each cycle that is required. When adding a new instruction, we attempt
15940b57cec5SDimitry Andric /// to add it to each existing DFA, until a legal space is found. If the
15950b57cec5SDimitry Andric /// instruction cannot be reserved in an existing DFA, we create a new one.
15960b57cec5SDimitry Andric unsigned SwingSchedulerDAG::calculateResMII() {
15970b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "calculateResMII:\n");
1598bdd1243dSDimitry Andric   ResourceManager RM(&MF.getSubtarget(), this);
1599bdd1243dSDimitry Andric   return RM.calculateResMII();
16000b57cec5SDimitry Andric }
16010b57cec5SDimitry Andric 
16020b57cec5SDimitry Andric /// Calculate the recurrence-constrainted minimum initiation interval.
16030b57cec5SDimitry Andric /// Iterate over each circuit.  Compute the delay(c) and distance(c)
16040b57cec5SDimitry Andric /// for each circuit. The II needs to satisfy the inequality
16050b57cec5SDimitry Andric /// delay(c) - II*distance(c) <= 0. For each circuit, choose the smallest
16060b57cec5SDimitry Andric /// II that satisfies the inequality, and the RecMII is the maximum
16070b57cec5SDimitry Andric /// of those values.
16080b57cec5SDimitry Andric unsigned SwingSchedulerDAG::calculateRecMII(NodeSetType &NodeSets) {
16090b57cec5SDimitry Andric   unsigned RecMII = 0;
16100b57cec5SDimitry Andric 
16110b57cec5SDimitry Andric   for (NodeSet &Nodes : NodeSets) {
16120b57cec5SDimitry Andric     if (Nodes.empty())
16130b57cec5SDimitry Andric       continue;
16140b57cec5SDimitry Andric 
16150b57cec5SDimitry Andric     unsigned Delay = Nodes.getLatency();
16160b57cec5SDimitry Andric     unsigned Distance = 1;
16170b57cec5SDimitry Andric 
16180b57cec5SDimitry Andric     // ii = ceil(delay / distance)
16190b57cec5SDimitry Andric     unsigned CurMII = (Delay + Distance - 1) / Distance;
16200b57cec5SDimitry Andric     Nodes.setRecMII(CurMII);
16210b57cec5SDimitry Andric     if (CurMII > RecMII)
16220b57cec5SDimitry Andric       RecMII = CurMII;
16230b57cec5SDimitry Andric   }
16240b57cec5SDimitry Andric 
16250b57cec5SDimitry Andric   return RecMII;
16260b57cec5SDimitry Andric }
16270b57cec5SDimitry Andric 
16280b57cec5SDimitry Andric /// Swap all the anti dependences in the DAG. That means it is no longer a DAG,
16290b57cec5SDimitry Andric /// but we do this to find the circuits, and then change them back.
16300b57cec5SDimitry Andric static void swapAntiDependences(std::vector<SUnit> &SUnits) {
16310b57cec5SDimitry Andric   SmallVector<std::pair<SUnit *, SDep>, 8> DepsAdded;
16320eae32dcSDimitry Andric   for (SUnit &SU : SUnits) {
16330eae32dcSDimitry Andric     for (SDep &Pred : SU.Preds)
16340eae32dcSDimitry Andric       if (Pred.getKind() == SDep::Anti)
16350eae32dcSDimitry Andric         DepsAdded.push_back(std::make_pair(&SU, Pred));
16360b57cec5SDimitry Andric   }
1637fe6060f1SDimitry Andric   for (std::pair<SUnit *, SDep> &P : DepsAdded) {
16380b57cec5SDimitry Andric     // Remove this anti dependency and add one in the reverse direction.
1639fe6060f1SDimitry Andric     SUnit *SU = P.first;
1640fe6060f1SDimitry Andric     SDep &D = P.second;
16410b57cec5SDimitry Andric     SUnit *TargetSU = D.getSUnit();
16420b57cec5SDimitry Andric     unsigned Reg = D.getReg();
16430b57cec5SDimitry Andric     unsigned Lat = D.getLatency();
16440b57cec5SDimitry Andric     SU->removePred(D);
16450b57cec5SDimitry Andric     SDep Dep(SU, SDep::Anti, Reg);
16460b57cec5SDimitry Andric     Dep.setLatency(Lat);
16470b57cec5SDimitry Andric     TargetSU->addPred(Dep);
16480b57cec5SDimitry Andric   }
16490b57cec5SDimitry Andric }
16500b57cec5SDimitry Andric 
16510b57cec5SDimitry Andric /// Create the adjacency structure of the nodes in the graph.
16520b57cec5SDimitry Andric void SwingSchedulerDAG::Circuits::createAdjacencyStructure(
16530b57cec5SDimitry Andric     SwingSchedulerDAG *DAG) {
16540b57cec5SDimitry Andric   BitVector Added(SUnits.size());
16550b57cec5SDimitry Andric   DenseMap<int, int> OutputDeps;
16560b57cec5SDimitry Andric   for (int i = 0, e = SUnits.size(); i != e; ++i) {
16570b57cec5SDimitry Andric     Added.reset();
16580b57cec5SDimitry Andric     // Add any successor to the adjacency matrix and exclude duplicates.
16590b57cec5SDimitry Andric     for (auto &SI : SUnits[i].Succs) {
16600b57cec5SDimitry Andric       // Only create a back-edge on the first and last nodes of a dependence
16610b57cec5SDimitry Andric       // chain. This records any chains and adds them later.
16620b57cec5SDimitry Andric       if (SI.getKind() == SDep::Output) {
16630b57cec5SDimitry Andric         int N = SI.getSUnit()->NodeNum;
16640b57cec5SDimitry Andric         int BackEdge = i;
16650b57cec5SDimitry Andric         auto Dep = OutputDeps.find(BackEdge);
16660b57cec5SDimitry Andric         if (Dep != OutputDeps.end()) {
16670b57cec5SDimitry Andric           BackEdge = Dep->second;
16680b57cec5SDimitry Andric           OutputDeps.erase(Dep);
16690b57cec5SDimitry Andric         }
16700b57cec5SDimitry Andric         OutputDeps[N] = BackEdge;
16710b57cec5SDimitry Andric       }
16720b57cec5SDimitry Andric       // Do not process a boundary node, an artificial node.
16730b57cec5SDimitry Andric       // A back-edge is processed only if it goes to a Phi.
16740b57cec5SDimitry Andric       if (SI.getSUnit()->isBoundaryNode() || SI.isArtificial() ||
16750b57cec5SDimitry Andric           (SI.getKind() == SDep::Anti && !SI.getSUnit()->getInstr()->isPHI()))
16760b57cec5SDimitry Andric         continue;
16770b57cec5SDimitry Andric       int N = SI.getSUnit()->NodeNum;
16780b57cec5SDimitry Andric       if (!Added.test(N)) {
16790b57cec5SDimitry Andric         AdjK[i].push_back(N);
16800b57cec5SDimitry Andric         Added.set(N);
16810b57cec5SDimitry Andric       }
16820b57cec5SDimitry Andric     }
16830b57cec5SDimitry Andric     // A chain edge between a store and a load is treated as a back-edge in the
16840b57cec5SDimitry Andric     // adjacency matrix.
16850b57cec5SDimitry Andric     for (auto &PI : SUnits[i].Preds) {
16860b57cec5SDimitry Andric       if (!SUnits[i].getInstr()->mayStore() ||
16870b57cec5SDimitry Andric           !DAG->isLoopCarriedDep(&SUnits[i], PI, false))
16880b57cec5SDimitry Andric         continue;
16890b57cec5SDimitry Andric       if (PI.getKind() == SDep::Order && PI.getSUnit()->getInstr()->mayLoad()) {
16900b57cec5SDimitry Andric         int N = PI.getSUnit()->NodeNum;
16910b57cec5SDimitry Andric         if (!Added.test(N)) {
16920b57cec5SDimitry Andric           AdjK[i].push_back(N);
16930b57cec5SDimitry Andric           Added.set(N);
16940b57cec5SDimitry Andric         }
16950b57cec5SDimitry Andric       }
16960b57cec5SDimitry Andric     }
16970b57cec5SDimitry Andric   }
16980b57cec5SDimitry Andric   // Add back-edges in the adjacency matrix for the output dependences.
16990b57cec5SDimitry Andric   for (auto &OD : OutputDeps)
17000b57cec5SDimitry Andric     if (!Added.test(OD.second)) {
17010b57cec5SDimitry Andric       AdjK[OD.first].push_back(OD.second);
17020b57cec5SDimitry Andric       Added.set(OD.second);
17030b57cec5SDimitry Andric     }
17040b57cec5SDimitry Andric }
17050b57cec5SDimitry Andric 
17060b57cec5SDimitry Andric /// Identify an elementary circuit in the dependence graph starting at the
17070b57cec5SDimitry Andric /// specified node.
17080b57cec5SDimitry Andric bool SwingSchedulerDAG::Circuits::circuit(int V, int S, NodeSetType &NodeSets,
17090b57cec5SDimitry Andric                                           bool HasBackedge) {
17100b57cec5SDimitry Andric   SUnit *SV = &SUnits[V];
17110b57cec5SDimitry Andric   bool F = false;
17120b57cec5SDimitry Andric   Stack.insert(SV);
17130b57cec5SDimitry Andric   Blocked.set(V);
17140b57cec5SDimitry Andric 
17150b57cec5SDimitry Andric   for (auto W : AdjK[V]) {
17160b57cec5SDimitry Andric     if (NumPaths > MaxPaths)
17170b57cec5SDimitry Andric       break;
17180b57cec5SDimitry Andric     if (W < S)
17190b57cec5SDimitry Andric       continue;
17200b57cec5SDimitry Andric     if (W == S) {
17210b57cec5SDimitry Andric       if (!HasBackedge)
17220b57cec5SDimitry Andric         NodeSets.push_back(NodeSet(Stack.begin(), Stack.end()));
17230b57cec5SDimitry Andric       F = true;
17240b57cec5SDimitry Andric       ++NumPaths;
17250b57cec5SDimitry Andric       break;
17260b57cec5SDimitry Andric     } else if (!Blocked.test(W)) {
17270b57cec5SDimitry Andric       if (circuit(W, S, NodeSets,
17280b57cec5SDimitry Andric                   Node2Idx->at(W) < Node2Idx->at(V) ? true : HasBackedge))
17290b57cec5SDimitry Andric         F = true;
17300b57cec5SDimitry Andric     }
17310b57cec5SDimitry Andric   }
17320b57cec5SDimitry Andric 
17330b57cec5SDimitry Andric   if (F)
17340b57cec5SDimitry Andric     unblock(V);
17350b57cec5SDimitry Andric   else {
17360b57cec5SDimitry Andric     for (auto W : AdjK[V]) {
17370b57cec5SDimitry Andric       if (W < S)
17380b57cec5SDimitry Andric         continue;
17390b57cec5SDimitry Andric       B[W].insert(SV);
17400b57cec5SDimitry Andric     }
17410b57cec5SDimitry Andric   }
17420b57cec5SDimitry Andric   Stack.pop_back();
17430b57cec5SDimitry Andric   return F;
17440b57cec5SDimitry Andric }
17450b57cec5SDimitry Andric 
17460b57cec5SDimitry Andric /// Unblock a node in the circuit finding algorithm.
17470b57cec5SDimitry Andric void SwingSchedulerDAG::Circuits::unblock(int U) {
17480b57cec5SDimitry Andric   Blocked.reset(U);
17490b57cec5SDimitry Andric   SmallPtrSet<SUnit *, 4> &BU = B[U];
17500b57cec5SDimitry Andric   while (!BU.empty()) {
17510b57cec5SDimitry Andric     SmallPtrSet<SUnit *, 4>::iterator SI = BU.begin();
17520b57cec5SDimitry Andric     assert(SI != BU.end() && "Invalid B set.");
17530b57cec5SDimitry Andric     SUnit *W = *SI;
17540b57cec5SDimitry Andric     BU.erase(W);
17550b57cec5SDimitry Andric     if (Blocked.test(W->NodeNum))
17560b57cec5SDimitry Andric       unblock(W->NodeNum);
17570b57cec5SDimitry Andric   }
17580b57cec5SDimitry Andric }
17590b57cec5SDimitry Andric 
17600b57cec5SDimitry Andric /// Identify all the elementary circuits in the dependence graph using
17610b57cec5SDimitry Andric /// Johnson's circuit algorithm.
17620b57cec5SDimitry Andric void SwingSchedulerDAG::findCircuits(NodeSetType &NodeSets) {
17630b57cec5SDimitry Andric   // Swap all the anti dependences in the DAG. That means it is no longer a DAG,
17640b57cec5SDimitry Andric   // but we do this to find the circuits, and then change them back.
17650b57cec5SDimitry Andric   swapAntiDependences(SUnits);
17660b57cec5SDimitry Andric 
17670b57cec5SDimitry Andric   Circuits Cir(SUnits, Topo);
17680b57cec5SDimitry Andric   // Create the adjacency structure.
17690b57cec5SDimitry Andric   Cir.createAdjacencyStructure(this);
17700b57cec5SDimitry Andric   for (int i = 0, e = SUnits.size(); i != e; ++i) {
17710b57cec5SDimitry Andric     Cir.reset();
17720b57cec5SDimitry Andric     Cir.circuit(i, i, NodeSets);
17730b57cec5SDimitry Andric   }
17740b57cec5SDimitry Andric 
17750b57cec5SDimitry Andric   // Change the dependences back so that we've created a DAG again.
17760b57cec5SDimitry Andric   swapAntiDependences(SUnits);
17770b57cec5SDimitry Andric }
17780b57cec5SDimitry Andric 
17790b57cec5SDimitry Andric // Create artificial dependencies between the source of COPY/REG_SEQUENCE that
17800b57cec5SDimitry Andric // is loop-carried to the USE in next iteration. This will help pipeliner avoid
17810b57cec5SDimitry Andric // additional copies that are needed across iterations. An artificial dependence
17820b57cec5SDimitry Andric // edge is added from USE to SOURCE of COPY/REG_SEQUENCE.
17830b57cec5SDimitry Andric 
17840b57cec5SDimitry Andric // PHI-------Anti-Dep-----> COPY/REG_SEQUENCE (loop-carried)
17850b57cec5SDimitry Andric // SRCOfCopY------True-Dep---> COPY/REG_SEQUENCE
17860b57cec5SDimitry Andric // PHI-------True-Dep------> USEOfPhi
17870b57cec5SDimitry Andric 
17880b57cec5SDimitry Andric // The mutation creates
17890b57cec5SDimitry Andric // USEOfPHI -------Artificial-Dep---> SRCOfCopy
17900b57cec5SDimitry Andric 
17910b57cec5SDimitry Andric // This overall will ensure, the USEOfPHI is scheduled before SRCOfCopy
17920b57cec5SDimitry Andric // (since USE is a predecessor), implies, the COPY/ REG_SEQUENCE is scheduled
17930b57cec5SDimitry Andric // late  to avoid additional copies across iterations. The possible scheduling
17940b57cec5SDimitry Andric // order would be
17950b57cec5SDimitry Andric // USEOfPHI --- SRCOfCopy---  COPY/REG_SEQUENCE.
17960b57cec5SDimitry Andric 
17970b57cec5SDimitry Andric void SwingSchedulerDAG::CopyToPhiMutation::apply(ScheduleDAGInstrs *DAG) {
17980b57cec5SDimitry Andric   for (SUnit &SU : DAG->SUnits) {
17990b57cec5SDimitry Andric     // Find the COPY/REG_SEQUENCE instruction.
18000b57cec5SDimitry Andric     if (!SU.getInstr()->isCopy() && !SU.getInstr()->isRegSequence())
18010b57cec5SDimitry Andric       continue;
18020b57cec5SDimitry Andric 
18030b57cec5SDimitry Andric     // Record the loop carried PHIs.
18040b57cec5SDimitry Andric     SmallVector<SUnit *, 4> PHISUs;
18050b57cec5SDimitry Andric     // Record the SrcSUs that feed the COPY/REG_SEQUENCE instructions.
18060b57cec5SDimitry Andric     SmallVector<SUnit *, 4> SrcSUs;
18070b57cec5SDimitry Andric 
18080b57cec5SDimitry Andric     for (auto &Dep : SU.Preds) {
18090b57cec5SDimitry Andric       SUnit *TmpSU = Dep.getSUnit();
18100b57cec5SDimitry Andric       MachineInstr *TmpMI = TmpSU->getInstr();
18110b57cec5SDimitry Andric       SDep::Kind DepKind = Dep.getKind();
18120b57cec5SDimitry Andric       // Save the loop carried PHI.
18130b57cec5SDimitry Andric       if (DepKind == SDep::Anti && TmpMI->isPHI())
18140b57cec5SDimitry Andric         PHISUs.push_back(TmpSU);
18150b57cec5SDimitry Andric       // Save the source of COPY/REG_SEQUENCE.
18160b57cec5SDimitry Andric       // If the source has no pre-decessors, we will end up creating cycles.
18170b57cec5SDimitry Andric       else if (DepKind == SDep::Data && !TmpMI->isPHI() && TmpSU->NumPreds > 0)
18180b57cec5SDimitry Andric         SrcSUs.push_back(TmpSU);
18190b57cec5SDimitry Andric     }
18200b57cec5SDimitry Andric 
18210b57cec5SDimitry Andric     if (PHISUs.size() == 0 || SrcSUs.size() == 0)
18220b57cec5SDimitry Andric       continue;
18230b57cec5SDimitry Andric 
18240b57cec5SDimitry Andric     // Find the USEs of PHI. If the use is a PHI or REG_SEQUENCE, push back this
18250b57cec5SDimitry Andric     // SUnit to the container.
18260b57cec5SDimitry Andric     SmallVector<SUnit *, 8> UseSUs;
1827480093f4SDimitry Andric     // Do not use iterator based loop here as we are updating the container.
1828480093f4SDimitry Andric     for (size_t Index = 0; Index < PHISUs.size(); ++Index) {
1829480093f4SDimitry Andric       for (auto &Dep : PHISUs[Index]->Succs) {
18300b57cec5SDimitry Andric         if (Dep.getKind() != SDep::Data)
18310b57cec5SDimitry Andric           continue;
18320b57cec5SDimitry Andric 
18330b57cec5SDimitry Andric         SUnit *TmpSU = Dep.getSUnit();
18340b57cec5SDimitry Andric         MachineInstr *TmpMI = TmpSU->getInstr();
18350b57cec5SDimitry Andric         if (TmpMI->isPHI() || TmpMI->isRegSequence()) {
18360b57cec5SDimitry Andric           PHISUs.push_back(TmpSU);
18370b57cec5SDimitry Andric           continue;
18380b57cec5SDimitry Andric         }
18390b57cec5SDimitry Andric         UseSUs.push_back(TmpSU);
18400b57cec5SDimitry Andric       }
18410b57cec5SDimitry Andric     }
18420b57cec5SDimitry Andric 
18430b57cec5SDimitry Andric     if (UseSUs.size() == 0)
18440b57cec5SDimitry Andric       continue;
18450b57cec5SDimitry Andric 
18460b57cec5SDimitry Andric     SwingSchedulerDAG *SDAG = cast<SwingSchedulerDAG>(DAG);
18470b57cec5SDimitry Andric     // Add the artificial dependencies if it does not form a cycle.
1848fcaf7f86SDimitry Andric     for (auto *I : UseSUs) {
1849fcaf7f86SDimitry Andric       for (auto *Src : SrcSUs) {
18500b57cec5SDimitry Andric         if (!SDAG->Topo.IsReachable(I, Src) && Src != I) {
18510b57cec5SDimitry Andric           Src->addPred(SDep(I, SDep::Artificial));
18520b57cec5SDimitry Andric           SDAG->Topo.AddPred(Src, I);
18530b57cec5SDimitry Andric         }
18540b57cec5SDimitry Andric       }
18550b57cec5SDimitry Andric     }
18560b57cec5SDimitry Andric   }
18570b57cec5SDimitry Andric }
18580b57cec5SDimitry Andric 
18590b57cec5SDimitry Andric /// Return true for DAG nodes that we ignore when computing the cost functions.
18600b57cec5SDimitry Andric /// We ignore the back-edge recurrence in order to avoid unbounded recursion
18610b57cec5SDimitry Andric /// in the calculation of the ASAP, ALAP, etc functions.
18620b57cec5SDimitry Andric static bool ignoreDependence(const SDep &D, bool isPred) {
186381ad6265SDimitry Andric   if (D.isArtificial() || D.getSUnit()->isBoundaryNode())
18640b57cec5SDimitry Andric     return true;
18650b57cec5SDimitry Andric   return D.getKind() == SDep::Anti && isPred;
18660b57cec5SDimitry Andric }
18670b57cec5SDimitry Andric 
18680b57cec5SDimitry Andric /// Compute several functions need to order the nodes for scheduling.
18690b57cec5SDimitry Andric ///  ASAP - Earliest time to schedule a node.
18700b57cec5SDimitry Andric ///  ALAP - Latest time to schedule a node.
18710b57cec5SDimitry Andric ///  MOV - Mobility function, difference between ALAP and ASAP.
18720b57cec5SDimitry Andric ///  D - Depth of each node.
18730b57cec5SDimitry Andric ///  H - Height of each node.
18740b57cec5SDimitry Andric void SwingSchedulerDAG::computeNodeFunctions(NodeSetType &NodeSets) {
18750b57cec5SDimitry Andric   ScheduleInfo.resize(SUnits.size());
18760b57cec5SDimitry Andric 
18770b57cec5SDimitry Andric   LLVM_DEBUG({
1878fe6060f1SDimitry Andric     for (int I : Topo) {
1879fe6060f1SDimitry Andric       const SUnit &SU = SUnits[I];
18800b57cec5SDimitry Andric       dumpNode(SU);
18810b57cec5SDimitry Andric     }
18820b57cec5SDimitry Andric   });
18830b57cec5SDimitry Andric 
18840b57cec5SDimitry Andric   int maxASAP = 0;
18850b57cec5SDimitry Andric   // Compute ASAP and ZeroLatencyDepth.
1886fe6060f1SDimitry Andric   for (int I : Topo) {
18870b57cec5SDimitry Andric     int asap = 0;
18880b57cec5SDimitry Andric     int zeroLatencyDepth = 0;
1889fe6060f1SDimitry Andric     SUnit *SU = &SUnits[I];
18904824e7fdSDimitry Andric     for (const SDep &P : SU->Preds) {
18914824e7fdSDimitry Andric       SUnit *pred = P.getSUnit();
18924824e7fdSDimitry Andric       if (P.getLatency() == 0)
18930b57cec5SDimitry Andric         zeroLatencyDepth =
18940b57cec5SDimitry Andric             std::max(zeroLatencyDepth, getZeroLatencyDepth(pred) + 1);
18954824e7fdSDimitry Andric       if (ignoreDependence(P, true))
18960b57cec5SDimitry Andric         continue;
18974824e7fdSDimitry Andric       asap = std::max(asap, (int)(getASAP(pred) + P.getLatency() -
18984824e7fdSDimitry Andric                                   getDistance(pred, SU, P) * MII));
18990b57cec5SDimitry Andric     }
19000b57cec5SDimitry Andric     maxASAP = std::max(maxASAP, asap);
1901fe6060f1SDimitry Andric     ScheduleInfo[I].ASAP = asap;
1902fe6060f1SDimitry Andric     ScheduleInfo[I].ZeroLatencyDepth = zeroLatencyDepth;
19030b57cec5SDimitry Andric   }
19040b57cec5SDimitry Andric 
19050b57cec5SDimitry Andric   // Compute ALAP, ZeroLatencyHeight, and MOV.
19060eae32dcSDimitry Andric   for (int I : llvm::reverse(Topo)) {
19070b57cec5SDimitry Andric     int alap = maxASAP;
19080b57cec5SDimitry Andric     int zeroLatencyHeight = 0;
19090eae32dcSDimitry Andric     SUnit *SU = &SUnits[I];
19100eae32dcSDimitry Andric     for (const SDep &S : SU->Succs) {
19110eae32dcSDimitry Andric       SUnit *succ = S.getSUnit();
191281ad6265SDimitry Andric       if (succ->isBoundaryNode())
191381ad6265SDimitry Andric         continue;
19140eae32dcSDimitry Andric       if (S.getLatency() == 0)
19150b57cec5SDimitry Andric         zeroLatencyHeight =
19160b57cec5SDimitry Andric             std::max(zeroLatencyHeight, getZeroLatencyHeight(succ) + 1);
19170eae32dcSDimitry Andric       if (ignoreDependence(S, true))
19180b57cec5SDimitry Andric         continue;
19190eae32dcSDimitry Andric       alap = std::min(alap, (int)(getALAP(succ) - S.getLatency() +
19200eae32dcSDimitry Andric                                   getDistance(SU, succ, S) * MII));
19210b57cec5SDimitry Andric     }
19220b57cec5SDimitry Andric 
19230eae32dcSDimitry Andric     ScheduleInfo[I].ALAP = alap;
19240eae32dcSDimitry Andric     ScheduleInfo[I].ZeroLatencyHeight = zeroLatencyHeight;
19250b57cec5SDimitry Andric   }
19260b57cec5SDimitry Andric 
19270b57cec5SDimitry Andric   // After computing the node functions, compute the summary for each node set.
19280b57cec5SDimitry Andric   for (NodeSet &I : NodeSets)
19290b57cec5SDimitry Andric     I.computeNodeSetInfo(this);
19300b57cec5SDimitry Andric 
19310b57cec5SDimitry Andric   LLVM_DEBUG({
19320b57cec5SDimitry Andric     for (unsigned i = 0; i < SUnits.size(); i++) {
19330b57cec5SDimitry Andric       dbgs() << "\tNode " << i << ":\n";
19340b57cec5SDimitry Andric       dbgs() << "\t   ASAP = " << getASAP(&SUnits[i]) << "\n";
19350b57cec5SDimitry Andric       dbgs() << "\t   ALAP = " << getALAP(&SUnits[i]) << "\n";
19360b57cec5SDimitry Andric       dbgs() << "\t   MOV  = " << getMOV(&SUnits[i]) << "\n";
19370b57cec5SDimitry Andric       dbgs() << "\t   D    = " << getDepth(&SUnits[i]) << "\n";
19380b57cec5SDimitry Andric       dbgs() << "\t   H    = " << getHeight(&SUnits[i]) << "\n";
19390b57cec5SDimitry Andric       dbgs() << "\t   ZLD  = " << getZeroLatencyDepth(&SUnits[i]) << "\n";
19400b57cec5SDimitry Andric       dbgs() << "\t   ZLH  = " << getZeroLatencyHeight(&SUnits[i]) << "\n";
19410b57cec5SDimitry Andric     }
19420b57cec5SDimitry Andric   });
19430b57cec5SDimitry Andric }
19440b57cec5SDimitry Andric 
19450b57cec5SDimitry Andric /// Compute the Pred_L(O) set, as defined in the paper. The set is defined
19460b57cec5SDimitry Andric /// as the predecessors of the elements of NodeOrder that are not also in
19470b57cec5SDimitry Andric /// NodeOrder.
19480b57cec5SDimitry Andric static bool pred_L(SetVector<SUnit *> &NodeOrder,
19490b57cec5SDimitry Andric                    SmallSetVector<SUnit *, 8> &Preds,
19500b57cec5SDimitry Andric                    const NodeSet *S = nullptr) {
19510b57cec5SDimitry Andric   Preds.clear();
19524824e7fdSDimitry Andric   for (const SUnit *SU : NodeOrder) {
19534824e7fdSDimitry Andric     for (const SDep &Pred : SU->Preds) {
1954fe6060f1SDimitry Andric       if (S && S->count(Pred.getSUnit()) == 0)
19550b57cec5SDimitry Andric         continue;
1956fe6060f1SDimitry Andric       if (ignoreDependence(Pred, true))
19570b57cec5SDimitry Andric         continue;
1958fe6060f1SDimitry Andric       if (NodeOrder.count(Pred.getSUnit()) == 0)
1959fe6060f1SDimitry Andric         Preds.insert(Pred.getSUnit());
19600b57cec5SDimitry Andric     }
19610b57cec5SDimitry Andric     // Back-edges are predecessors with an anti-dependence.
19624824e7fdSDimitry Andric     for (const SDep &Succ : SU->Succs) {
1963fe6060f1SDimitry Andric       if (Succ.getKind() != SDep::Anti)
19640b57cec5SDimitry Andric         continue;
1965fe6060f1SDimitry Andric       if (S && S->count(Succ.getSUnit()) == 0)
19660b57cec5SDimitry Andric         continue;
1967fe6060f1SDimitry Andric       if (NodeOrder.count(Succ.getSUnit()) == 0)
1968fe6060f1SDimitry Andric         Preds.insert(Succ.getSUnit());
19690b57cec5SDimitry Andric     }
19700b57cec5SDimitry Andric   }
19710b57cec5SDimitry Andric   return !Preds.empty();
19720b57cec5SDimitry Andric }
19730b57cec5SDimitry Andric 
19740b57cec5SDimitry Andric /// Compute the Succ_L(O) set, as defined in the paper. The set is defined
19750b57cec5SDimitry Andric /// as the successors of the elements of NodeOrder that are not also in
19760b57cec5SDimitry Andric /// NodeOrder.
19770b57cec5SDimitry Andric static bool succ_L(SetVector<SUnit *> &NodeOrder,
19780b57cec5SDimitry Andric                    SmallSetVector<SUnit *, 8> &Succs,
19790b57cec5SDimitry Andric                    const NodeSet *S = nullptr) {
19800b57cec5SDimitry Andric   Succs.clear();
19810eae32dcSDimitry Andric   for (const SUnit *SU : NodeOrder) {
19820eae32dcSDimitry Andric     for (const SDep &Succ : SU->Succs) {
1983fe6060f1SDimitry Andric       if (S && S->count(Succ.getSUnit()) == 0)
19840b57cec5SDimitry Andric         continue;
1985fe6060f1SDimitry Andric       if (ignoreDependence(Succ, false))
19860b57cec5SDimitry Andric         continue;
1987fe6060f1SDimitry Andric       if (NodeOrder.count(Succ.getSUnit()) == 0)
1988fe6060f1SDimitry Andric         Succs.insert(Succ.getSUnit());
19890b57cec5SDimitry Andric     }
19900eae32dcSDimitry Andric     for (const SDep &Pred : SU->Preds) {
1991fe6060f1SDimitry Andric       if (Pred.getKind() != SDep::Anti)
19920b57cec5SDimitry Andric         continue;
1993fe6060f1SDimitry Andric       if (S && S->count(Pred.getSUnit()) == 0)
19940b57cec5SDimitry Andric         continue;
1995fe6060f1SDimitry Andric       if (NodeOrder.count(Pred.getSUnit()) == 0)
1996fe6060f1SDimitry Andric         Succs.insert(Pred.getSUnit());
19970b57cec5SDimitry Andric     }
19980b57cec5SDimitry Andric   }
19990b57cec5SDimitry Andric   return !Succs.empty();
20000b57cec5SDimitry Andric }
20010b57cec5SDimitry Andric 
20020b57cec5SDimitry Andric /// Return true if there is a path from the specified node to any of the nodes
20030b57cec5SDimitry Andric /// in DestNodes. Keep track and return the nodes in any path.
20040b57cec5SDimitry Andric static bool computePath(SUnit *Cur, SetVector<SUnit *> &Path,
20050b57cec5SDimitry Andric                         SetVector<SUnit *> &DestNodes,
20060b57cec5SDimitry Andric                         SetVector<SUnit *> &Exclude,
20070b57cec5SDimitry Andric                         SmallPtrSet<SUnit *, 8> &Visited) {
20080b57cec5SDimitry Andric   if (Cur->isBoundaryNode())
20090b57cec5SDimitry Andric     return false;
2010e8d8bef9SDimitry Andric   if (Exclude.contains(Cur))
20110b57cec5SDimitry Andric     return false;
2012e8d8bef9SDimitry Andric   if (DestNodes.contains(Cur))
20130b57cec5SDimitry Andric     return true;
20140b57cec5SDimitry Andric   if (!Visited.insert(Cur).second)
2015e8d8bef9SDimitry Andric     return Path.contains(Cur);
20160b57cec5SDimitry Andric   bool FoundPath = false;
20170b57cec5SDimitry Andric   for (auto &SI : Cur->Succs)
201881ad6265SDimitry Andric     if (!ignoreDependence(SI, false))
201981ad6265SDimitry Andric       FoundPath |=
202081ad6265SDimitry Andric           computePath(SI.getSUnit(), Path, DestNodes, Exclude, Visited);
20210b57cec5SDimitry Andric   for (auto &PI : Cur->Preds)
20220b57cec5SDimitry Andric     if (PI.getKind() == SDep::Anti)
20230b57cec5SDimitry Andric       FoundPath |=
20240b57cec5SDimitry Andric           computePath(PI.getSUnit(), Path, DestNodes, Exclude, Visited);
20250b57cec5SDimitry Andric   if (FoundPath)
20260b57cec5SDimitry Andric     Path.insert(Cur);
20270b57cec5SDimitry Andric   return FoundPath;
20280b57cec5SDimitry Andric }
20290b57cec5SDimitry Andric 
20300b57cec5SDimitry Andric /// Compute the live-out registers for the instructions in a node-set.
20310b57cec5SDimitry Andric /// The live-out registers are those that are defined in the node-set,
20320b57cec5SDimitry Andric /// but not used. Except for use operands of Phis.
20330b57cec5SDimitry Andric static void computeLiveOuts(MachineFunction &MF, RegPressureTracker &RPTracker,
20340b57cec5SDimitry Andric                             NodeSet &NS) {
20350b57cec5SDimitry Andric   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
20360b57cec5SDimitry Andric   MachineRegisterInfo &MRI = MF.getRegInfo();
20370b57cec5SDimitry Andric   SmallVector<RegisterMaskPair, 8> LiveOutRegs;
20380b57cec5SDimitry Andric   SmallSet<unsigned, 4> Uses;
20390b57cec5SDimitry Andric   for (SUnit *SU : NS) {
20400b57cec5SDimitry Andric     const MachineInstr *MI = SU->getInstr();
20410b57cec5SDimitry Andric     if (MI->isPHI())
20420b57cec5SDimitry Andric       continue;
204306c3fb27SDimitry Andric     for (const MachineOperand &MO : MI->all_uses()) {
20448bcb0991SDimitry Andric       Register Reg = MO.getReg();
2045bdd1243dSDimitry Andric       if (Reg.isVirtual())
20460b57cec5SDimitry Andric         Uses.insert(Reg);
20470b57cec5SDimitry Andric       else if (MRI.isAllocatable(Reg))
204806c3fb27SDimitry Andric         for (MCRegUnit Unit : TRI->regunits(Reg.asMCReg()))
204906c3fb27SDimitry Andric           Uses.insert(Unit);
20500b57cec5SDimitry Andric     }
20510b57cec5SDimitry Andric   }
20520b57cec5SDimitry Andric   for (SUnit *SU : NS)
205306c3fb27SDimitry Andric     for (const MachineOperand &MO : SU->getInstr()->all_defs())
205406c3fb27SDimitry Andric       if (!MO.isDead()) {
20558bcb0991SDimitry Andric         Register Reg = MO.getReg();
2056bdd1243dSDimitry Andric         if (Reg.isVirtual()) {
20570b57cec5SDimitry Andric           if (!Uses.count(Reg))
20580b57cec5SDimitry Andric             LiveOutRegs.push_back(RegisterMaskPair(Reg,
20590b57cec5SDimitry Andric                                                    LaneBitmask::getNone()));
20600b57cec5SDimitry Andric         } else if (MRI.isAllocatable(Reg)) {
206106c3fb27SDimitry Andric           for (MCRegUnit Unit : TRI->regunits(Reg.asMCReg()))
206206c3fb27SDimitry Andric             if (!Uses.count(Unit))
206306c3fb27SDimitry Andric               LiveOutRegs.push_back(
206406c3fb27SDimitry Andric                   RegisterMaskPair(Unit, LaneBitmask::getNone()));
20650b57cec5SDimitry Andric         }
20660b57cec5SDimitry Andric       }
20670b57cec5SDimitry Andric   RPTracker.addLiveRegs(LiveOutRegs);
20680b57cec5SDimitry Andric }
20690b57cec5SDimitry Andric 
20700b57cec5SDimitry Andric /// A heuristic to filter nodes in recurrent node-sets if the register
20710b57cec5SDimitry Andric /// pressure of a set is too high.
20720b57cec5SDimitry Andric void SwingSchedulerDAG::registerPressureFilter(NodeSetType &NodeSets) {
20730b57cec5SDimitry Andric   for (auto &NS : NodeSets) {
20740b57cec5SDimitry Andric     // Skip small node-sets since they won't cause register pressure problems.
20750b57cec5SDimitry Andric     if (NS.size() <= 2)
20760b57cec5SDimitry Andric       continue;
20770b57cec5SDimitry Andric     IntervalPressure RecRegPressure;
20780b57cec5SDimitry Andric     RegPressureTracker RecRPTracker(RecRegPressure);
20790b57cec5SDimitry Andric     RecRPTracker.init(&MF, &RegClassInfo, &LIS, BB, BB->end(), false, true);
20800b57cec5SDimitry Andric     computeLiveOuts(MF, RecRPTracker, NS);
20810b57cec5SDimitry Andric     RecRPTracker.closeBottom();
20820b57cec5SDimitry Andric 
20830b57cec5SDimitry Andric     std::vector<SUnit *> SUnits(NS.begin(), NS.end());
20840b57cec5SDimitry Andric     llvm::sort(SUnits, [](const SUnit *A, const SUnit *B) {
20850b57cec5SDimitry Andric       return A->NodeNum > B->NodeNum;
20860b57cec5SDimitry Andric     });
20870b57cec5SDimitry Andric 
20880b57cec5SDimitry Andric     for (auto &SU : SUnits) {
20890b57cec5SDimitry Andric       // Since we're computing the register pressure for a subset of the
20900b57cec5SDimitry Andric       // instructions in a block, we need to set the tracker for each
20910b57cec5SDimitry Andric       // instruction in the node-set. The tracker is set to the instruction
20920b57cec5SDimitry Andric       // just after the one we're interested in.
20930b57cec5SDimitry Andric       MachineBasicBlock::const_iterator CurInstI = SU->getInstr();
20940b57cec5SDimitry Andric       RecRPTracker.setPos(std::next(CurInstI));
20950b57cec5SDimitry Andric 
20960b57cec5SDimitry Andric       RegPressureDelta RPDelta;
20970b57cec5SDimitry Andric       ArrayRef<PressureChange> CriticalPSets;
20980b57cec5SDimitry Andric       RecRPTracker.getMaxUpwardPressureDelta(SU->getInstr(), nullptr, RPDelta,
20990b57cec5SDimitry Andric                                              CriticalPSets,
21000b57cec5SDimitry Andric                                              RecRegPressure.MaxSetPressure);
21010b57cec5SDimitry Andric       if (RPDelta.Excess.isValid()) {
21020b57cec5SDimitry Andric         LLVM_DEBUG(
21030b57cec5SDimitry Andric             dbgs() << "Excess register pressure: SU(" << SU->NodeNum << ") "
21040b57cec5SDimitry Andric                    << TRI->getRegPressureSetName(RPDelta.Excess.getPSet())
210581ad6265SDimitry Andric                    << ":" << RPDelta.Excess.getUnitInc() << "\n");
21060b57cec5SDimitry Andric         NS.setExceedPressure(SU);
21070b57cec5SDimitry Andric         break;
21080b57cec5SDimitry Andric       }
21090b57cec5SDimitry Andric       RecRPTracker.recede();
21100b57cec5SDimitry Andric     }
21110b57cec5SDimitry Andric   }
21120b57cec5SDimitry Andric }
21130b57cec5SDimitry Andric 
21140b57cec5SDimitry Andric /// A heuristic to colocate node sets that have the same set of
21150b57cec5SDimitry Andric /// successors.
21160b57cec5SDimitry Andric void SwingSchedulerDAG::colocateNodeSets(NodeSetType &NodeSets) {
21170b57cec5SDimitry Andric   unsigned Colocate = 0;
21180b57cec5SDimitry Andric   for (int i = 0, e = NodeSets.size(); i < e; ++i) {
21190b57cec5SDimitry Andric     NodeSet &N1 = NodeSets[i];
21200b57cec5SDimitry Andric     SmallSetVector<SUnit *, 8> S1;
21210b57cec5SDimitry Andric     if (N1.empty() || !succ_L(N1, S1))
21220b57cec5SDimitry Andric       continue;
21230b57cec5SDimitry Andric     for (int j = i + 1; j < e; ++j) {
21240b57cec5SDimitry Andric       NodeSet &N2 = NodeSets[j];
21250b57cec5SDimitry Andric       if (N1.compareRecMII(N2) != 0)
21260b57cec5SDimitry Andric         continue;
21270b57cec5SDimitry Andric       SmallSetVector<SUnit *, 8> S2;
21280b57cec5SDimitry Andric       if (N2.empty() || !succ_L(N2, S2))
21290b57cec5SDimitry Andric         continue;
2130fe6060f1SDimitry Andric       if (llvm::set_is_subset(S1, S2) && S1.size() == S2.size()) {
21310b57cec5SDimitry Andric         N1.setColocate(++Colocate);
21320b57cec5SDimitry Andric         N2.setColocate(Colocate);
21330b57cec5SDimitry Andric         break;
21340b57cec5SDimitry Andric       }
21350b57cec5SDimitry Andric     }
21360b57cec5SDimitry Andric   }
21370b57cec5SDimitry Andric }
21380b57cec5SDimitry Andric 
21390b57cec5SDimitry Andric /// Check if the existing node-sets are profitable. If not, then ignore the
21400b57cec5SDimitry Andric /// recurrent node-sets, and attempt to schedule all nodes together. This is
21410b57cec5SDimitry Andric /// a heuristic. If the MII is large and all the recurrent node-sets are small,
21420b57cec5SDimitry Andric /// then it's best to try to schedule all instructions together instead of
21430b57cec5SDimitry Andric /// starting with the recurrent node-sets.
21440b57cec5SDimitry Andric void SwingSchedulerDAG::checkNodeSets(NodeSetType &NodeSets) {
21450b57cec5SDimitry Andric   // Look for loops with a large MII.
21460b57cec5SDimitry Andric   if (MII < 17)
21470b57cec5SDimitry Andric     return;
21480b57cec5SDimitry Andric   // Check if the node-set contains only a simple add recurrence.
21490b57cec5SDimitry Andric   for (auto &NS : NodeSets) {
21500b57cec5SDimitry Andric     if (NS.getRecMII() > 2)
21510b57cec5SDimitry Andric       return;
21520b57cec5SDimitry Andric     if (NS.getMaxDepth() > MII)
21530b57cec5SDimitry Andric       return;
21540b57cec5SDimitry Andric   }
21550b57cec5SDimitry Andric   NodeSets.clear();
21560b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Clear recurrence node-sets\n");
21570b57cec5SDimitry Andric }
21580b57cec5SDimitry Andric 
21590b57cec5SDimitry Andric /// Add the nodes that do not belong to a recurrence set into groups
216081ad6265SDimitry Andric /// based upon connected components.
21610b57cec5SDimitry Andric void SwingSchedulerDAG::groupRemainingNodes(NodeSetType &NodeSets) {
21620b57cec5SDimitry Andric   SetVector<SUnit *> NodesAdded;
21630b57cec5SDimitry Andric   SmallPtrSet<SUnit *, 8> Visited;
21640b57cec5SDimitry Andric   // Add the nodes that are on a path between the previous node sets and
21650b57cec5SDimitry Andric   // the current node set.
21660b57cec5SDimitry Andric   for (NodeSet &I : NodeSets) {
21670b57cec5SDimitry Andric     SmallSetVector<SUnit *, 8> N;
21680b57cec5SDimitry Andric     // Add the nodes from the current node set to the previous node set.
21690b57cec5SDimitry Andric     if (succ_L(I, N)) {
21700b57cec5SDimitry Andric       SetVector<SUnit *> Path;
21710b57cec5SDimitry Andric       for (SUnit *NI : N) {
21720b57cec5SDimitry Andric         Visited.clear();
21730b57cec5SDimitry Andric         computePath(NI, Path, NodesAdded, I, Visited);
21740b57cec5SDimitry Andric       }
21750b57cec5SDimitry Andric       if (!Path.empty())
21760b57cec5SDimitry Andric         I.insert(Path.begin(), Path.end());
21770b57cec5SDimitry Andric     }
21780b57cec5SDimitry Andric     // Add the nodes from the previous node set to the current node set.
21790b57cec5SDimitry Andric     N.clear();
21800b57cec5SDimitry Andric     if (succ_L(NodesAdded, N)) {
21810b57cec5SDimitry Andric       SetVector<SUnit *> Path;
21820b57cec5SDimitry Andric       for (SUnit *NI : N) {
21830b57cec5SDimitry Andric         Visited.clear();
21840b57cec5SDimitry Andric         computePath(NI, Path, I, NodesAdded, Visited);
21850b57cec5SDimitry Andric       }
21860b57cec5SDimitry Andric       if (!Path.empty())
21870b57cec5SDimitry Andric         I.insert(Path.begin(), Path.end());
21880b57cec5SDimitry Andric     }
21890b57cec5SDimitry Andric     NodesAdded.insert(I.begin(), I.end());
21900b57cec5SDimitry Andric   }
21910b57cec5SDimitry Andric 
21920b57cec5SDimitry Andric   // Create a new node set with the connected nodes of any successor of a node
21930b57cec5SDimitry Andric   // in a recurrent set.
21940b57cec5SDimitry Andric   NodeSet NewSet;
21950b57cec5SDimitry Andric   SmallSetVector<SUnit *, 8> N;
21960b57cec5SDimitry Andric   if (succ_L(NodesAdded, N))
21970b57cec5SDimitry Andric     for (SUnit *I : N)
21980b57cec5SDimitry Andric       addConnectedNodes(I, NewSet, NodesAdded);
21990b57cec5SDimitry Andric   if (!NewSet.empty())
22000b57cec5SDimitry Andric     NodeSets.push_back(NewSet);
22010b57cec5SDimitry Andric 
22020b57cec5SDimitry Andric   // Create a new node set with the connected nodes of any predecessor of a node
22030b57cec5SDimitry Andric   // in a recurrent set.
22040b57cec5SDimitry Andric   NewSet.clear();
22050b57cec5SDimitry Andric   if (pred_L(NodesAdded, N))
22060b57cec5SDimitry Andric     for (SUnit *I : N)
22070b57cec5SDimitry Andric       addConnectedNodes(I, NewSet, NodesAdded);
22080b57cec5SDimitry Andric   if (!NewSet.empty())
22090b57cec5SDimitry Andric     NodeSets.push_back(NewSet);
22100b57cec5SDimitry Andric 
22110b57cec5SDimitry Andric   // Create new nodes sets with the connected nodes any remaining node that
22120b57cec5SDimitry Andric   // has no predecessor.
2213fe6060f1SDimitry Andric   for (SUnit &SU : SUnits) {
2214fe6060f1SDimitry Andric     if (NodesAdded.count(&SU) == 0) {
22150b57cec5SDimitry Andric       NewSet.clear();
2216fe6060f1SDimitry Andric       addConnectedNodes(&SU, NewSet, NodesAdded);
22170b57cec5SDimitry Andric       if (!NewSet.empty())
22180b57cec5SDimitry Andric         NodeSets.push_back(NewSet);
22190b57cec5SDimitry Andric     }
22200b57cec5SDimitry Andric   }
22210b57cec5SDimitry Andric }
22220b57cec5SDimitry Andric 
22230b57cec5SDimitry Andric /// Add the node to the set, and add all of its connected nodes to the set.
22240b57cec5SDimitry Andric void SwingSchedulerDAG::addConnectedNodes(SUnit *SU, NodeSet &NewSet,
22250b57cec5SDimitry Andric                                           SetVector<SUnit *> &NodesAdded) {
22260b57cec5SDimitry Andric   NewSet.insert(SU);
22270b57cec5SDimitry Andric   NodesAdded.insert(SU);
22280b57cec5SDimitry Andric   for (auto &SI : SU->Succs) {
22290b57cec5SDimitry Andric     SUnit *Successor = SI.getSUnit();
223081ad6265SDimitry Andric     if (!SI.isArtificial() && !Successor->isBoundaryNode() &&
223181ad6265SDimitry Andric         NodesAdded.count(Successor) == 0)
22320b57cec5SDimitry Andric       addConnectedNodes(Successor, NewSet, NodesAdded);
22330b57cec5SDimitry Andric   }
22340b57cec5SDimitry Andric   for (auto &PI : SU->Preds) {
22350b57cec5SDimitry Andric     SUnit *Predecessor = PI.getSUnit();
22360b57cec5SDimitry Andric     if (!PI.isArtificial() && NodesAdded.count(Predecessor) == 0)
22370b57cec5SDimitry Andric       addConnectedNodes(Predecessor, NewSet, NodesAdded);
22380b57cec5SDimitry Andric   }
22390b57cec5SDimitry Andric }
22400b57cec5SDimitry Andric 
22410b57cec5SDimitry Andric /// Return true if Set1 contains elements in Set2. The elements in common
22420b57cec5SDimitry Andric /// are returned in a different container.
22430b57cec5SDimitry Andric static bool isIntersect(SmallSetVector<SUnit *, 8> &Set1, const NodeSet &Set2,
22440b57cec5SDimitry Andric                         SmallSetVector<SUnit *, 8> &Result) {
22450b57cec5SDimitry Andric   Result.clear();
224681ad6265SDimitry Andric   for (SUnit *SU : Set1) {
22470b57cec5SDimitry Andric     if (Set2.count(SU) != 0)
22480b57cec5SDimitry Andric       Result.insert(SU);
22490b57cec5SDimitry Andric   }
22500b57cec5SDimitry Andric   return !Result.empty();
22510b57cec5SDimitry Andric }
22520b57cec5SDimitry Andric 
22530b57cec5SDimitry Andric /// Merge the recurrence node sets that have the same initial node.
22540b57cec5SDimitry Andric void SwingSchedulerDAG::fuseRecs(NodeSetType &NodeSets) {
22550b57cec5SDimitry Andric   for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
22560b57cec5SDimitry Andric        ++I) {
22570b57cec5SDimitry Andric     NodeSet &NI = *I;
22580b57cec5SDimitry Andric     for (NodeSetType::iterator J = I + 1; J != E;) {
22590b57cec5SDimitry Andric       NodeSet &NJ = *J;
22600b57cec5SDimitry Andric       if (NI.getNode(0)->NodeNum == NJ.getNode(0)->NodeNum) {
22610b57cec5SDimitry Andric         if (NJ.compareRecMII(NI) > 0)
22620b57cec5SDimitry Andric           NI.setRecMII(NJ.getRecMII());
2263fe6060f1SDimitry Andric         for (SUnit *SU : *J)
2264fe6060f1SDimitry Andric           I->insert(SU);
22650b57cec5SDimitry Andric         NodeSets.erase(J);
22660b57cec5SDimitry Andric         E = NodeSets.end();
22670b57cec5SDimitry Andric       } else {
22680b57cec5SDimitry Andric         ++J;
22690b57cec5SDimitry Andric       }
22700b57cec5SDimitry Andric     }
22710b57cec5SDimitry Andric   }
22720b57cec5SDimitry Andric }
22730b57cec5SDimitry Andric 
22740b57cec5SDimitry Andric /// Remove nodes that have been scheduled in previous NodeSets.
22750b57cec5SDimitry Andric void SwingSchedulerDAG::removeDuplicateNodes(NodeSetType &NodeSets) {
22760b57cec5SDimitry Andric   for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
22770b57cec5SDimitry Andric        ++I)
22780b57cec5SDimitry Andric     for (NodeSetType::iterator J = I + 1; J != E;) {
22790b57cec5SDimitry Andric       J->remove_if([&](SUnit *SUJ) { return I->count(SUJ); });
22800b57cec5SDimitry Andric 
22810b57cec5SDimitry Andric       if (J->empty()) {
22820b57cec5SDimitry Andric         NodeSets.erase(J);
22830b57cec5SDimitry Andric         E = NodeSets.end();
22840b57cec5SDimitry Andric       } else {
22850b57cec5SDimitry Andric         ++J;
22860b57cec5SDimitry Andric       }
22870b57cec5SDimitry Andric     }
22880b57cec5SDimitry Andric }
22890b57cec5SDimitry Andric 
22900b57cec5SDimitry Andric /// Compute an ordered list of the dependence graph nodes, which
22910b57cec5SDimitry Andric /// indicates the order that the nodes will be scheduled.  This is a
22920b57cec5SDimitry Andric /// two-level algorithm. First, a partial order is created, which
22930b57cec5SDimitry Andric /// consists of a list of sets ordered from highest to lowest priority.
22940b57cec5SDimitry Andric void SwingSchedulerDAG::computeNodeOrder(NodeSetType &NodeSets) {
22950b57cec5SDimitry Andric   SmallSetVector<SUnit *, 8> R;
22960b57cec5SDimitry Andric   NodeOrder.clear();
22970b57cec5SDimitry Andric 
22980b57cec5SDimitry Andric   for (auto &Nodes : NodeSets) {
22990b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "NodeSet size " << Nodes.size() << "\n");
23000b57cec5SDimitry Andric     OrderKind Order;
23010b57cec5SDimitry Andric     SmallSetVector<SUnit *, 8> N;
2302fe6060f1SDimitry Andric     if (pred_L(NodeOrder, N) && llvm::set_is_subset(N, Nodes)) {
23030b57cec5SDimitry Andric       R.insert(N.begin(), N.end());
23040b57cec5SDimitry Andric       Order = BottomUp;
23050b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "  Bottom up (preds) ");
2306fe6060f1SDimitry Andric     } else if (succ_L(NodeOrder, N) && llvm::set_is_subset(N, Nodes)) {
23070b57cec5SDimitry Andric       R.insert(N.begin(), N.end());
23080b57cec5SDimitry Andric       Order = TopDown;
23090b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "  Top down (succs) ");
23100b57cec5SDimitry Andric     } else if (isIntersect(N, Nodes, R)) {
23110b57cec5SDimitry Andric       // If some of the successors are in the existing node-set, then use the
23120b57cec5SDimitry Andric       // top-down ordering.
23130b57cec5SDimitry Andric       Order = TopDown;
23140b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "  Top down (intersect) ");
23150b57cec5SDimitry Andric     } else if (NodeSets.size() == 1) {
2316fcaf7f86SDimitry Andric       for (const auto &N : Nodes)
23170b57cec5SDimitry Andric         if (N->Succs.size() == 0)
23180b57cec5SDimitry Andric           R.insert(N);
23190b57cec5SDimitry Andric       Order = BottomUp;
23200b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "  Bottom up (all) ");
23210b57cec5SDimitry Andric     } else {
23220b57cec5SDimitry Andric       // Find the node with the highest ASAP.
23230b57cec5SDimitry Andric       SUnit *maxASAP = nullptr;
23240b57cec5SDimitry Andric       for (SUnit *SU : Nodes) {
23250b57cec5SDimitry Andric         if (maxASAP == nullptr || getASAP(SU) > getASAP(maxASAP) ||
23260b57cec5SDimitry Andric             (getASAP(SU) == getASAP(maxASAP) && SU->NodeNum > maxASAP->NodeNum))
23270b57cec5SDimitry Andric           maxASAP = SU;
23280b57cec5SDimitry Andric       }
23290b57cec5SDimitry Andric       R.insert(maxASAP);
23300b57cec5SDimitry Andric       Order = BottomUp;
23310b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "  Bottom up (default) ");
23320b57cec5SDimitry Andric     }
23330b57cec5SDimitry Andric 
23340b57cec5SDimitry Andric     while (!R.empty()) {
23350b57cec5SDimitry Andric       if (Order == TopDown) {
23360b57cec5SDimitry Andric         // Choose the node with the maximum height.  If more than one, choose
23370b57cec5SDimitry Andric         // the node wiTH the maximum ZeroLatencyHeight. If still more than one,
23380b57cec5SDimitry Andric         // choose the node with the lowest MOV.
23390b57cec5SDimitry Andric         while (!R.empty()) {
23400b57cec5SDimitry Andric           SUnit *maxHeight = nullptr;
23410b57cec5SDimitry Andric           for (SUnit *I : R) {
23420b57cec5SDimitry Andric             if (maxHeight == nullptr || getHeight(I) > getHeight(maxHeight))
23430b57cec5SDimitry Andric               maxHeight = I;
23440b57cec5SDimitry Andric             else if (getHeight(I) == getHeight(maxHeight) &&
23450b57cec5SDimitry Andric                      getZeroLatencyHeight(I) > getZeroLatencyHeight(maxHeight))
23460b57cec5SDimitry Andric               maxHeight = I;
23470b57cec5SDimitry Andric             else if (getHeight(I) == getHeight(maxHeight) &&
23480b57cec5SDimitry Andric                      getZeroLatencyHeight(I) ==
23490b57cec5SDimitry Andric                          getZeroLatencyHeight(maxHeight) &&
23500b57cec5SDimitry Andric                      getMOV(I) < getMOV(maxHeight))
23510b57cec5SDimitry Andric               maxHeight = I;
23520b57cec5SDimitry Andric           }
23530b57cec5SDimitry Andric           NodeOrder.insert(maxHeight);
23540b57cec5SDimitry Andric           LLVM_DEBUG(dbgs() << maxHeight->NodeNum << " ");
23550b57cec5SDimitry Andric           R.remove(maxHeight);
23560b57cec5SDimitry Andric           for (const auto &I : maxHeight->Succs) {
23570b57cec5SDimitry Andric             if (Nodes.count(I.getSUnit()) == 0)
23580b57cec5SDimitry Andric               continue;
2359e8d8bef9SDimitry Andric             if (NodeOrder.contains(I.getSUnit()))
23600b57cec5SDimitry Andric               continue;
23610b57cec5SDimitry Andric             if (ignoreDependence(I, false))
23620b57cec5SDimitry Andric               continue;
23630b57cec5SDimitry Andric             R.insert(I.getSUnit());
23640b57cec5SDimitry Andric           }
23650b57cec5SDimitry Andric           // Back-edges are predecessors with an anti-dependence.
23660b57cec5SDimitry Andric           for (const auto &I : maxHeight->Preds) {
23670b57cec5SDimitry Andric             if (I.getKind() != SDep::Anti)
23680b57cec5SDimitry Andric               continue;
23690b57cec5SDimitry Andric             if (Nodes.count(I.getSUnit()) == 0)
23700b57cec5SDimitry Andric               continue;
2371e8d8bef9SDimitry Andric             if (NodeOrder.contains(I.getSUnit()))
23720b57cec5SDimitry Andric               continue;
23730b57cec5SDimitry Andric             R.insert(I.getSUnit());
23740b57cec5SDimitry Andric           }
23750b57cec5SDimitry Andric         }
23760b57cec5SDimitry Andric         Order = BottomUp;
23770b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "\n   Switching order to bottom up ");
23780b57cec5SDimitry Andric         SmallSetVector<SUnit *, 8> N;
23790b57cec5SDimitry Andric         if (pred_L(NodeOrder, N, &Nodes))
23800b57cec5SDimitry Andric           R.insert(N.begin(), N.end());
23810b57cec5SDimitry Andric       } else {
23820b57cec5SDimitry Andric         // Choose the node with the maximum depth.  If more than one, choose
23830b57cec5SDimitry Andric         // the node with the maximum ZeroLatencyDepth. If still more than one,
23840b57cec5SDimitry Andric         // choose the node with the lowest MOV.
23850b57cec5SDimitry Andric         while (!R.empty()) {
23860b57cec5SDimitry Andric           SUnit *maxDepth = nullptr;
23870b57cec5SDimitry Andric           for (SUnit *I : R) {
23880b57cec5SDimitry Andric             if (maxDepth == nullptr || getDepth(I) > getDepth(maxDepth))
23890b57cec5SDimitry Andric               maxDepth = I;
23900b57cec5SDimitry Andric             else if (getDepth(I) == getDepth(maxDepth) &&
23910b57cec5SDimitry Andric                      getZeroLatencyDepth(I) > getZeroLatencyDepth(maxDepth))
23920b57cec5SDimitry Andric               maxDepth = I;
23930b57cec5SDimitry Andric             else if (getDepth(I) == getDepth(maxDepth) &&
23940b57cec5SDimitry Andric                      getZeroLatencyDepth(I) == getZeroLatencyDepth(maxDepth) &&
23950b57cec5SDimitry Andric                      getMOV(I) < getMOV(maxDepth))
23960b57cec5SDimitry Andric               maxDepth = I;
23970b57cec5SDimitry Andric           }
23980b57cec5SDimitry Andric           NodeOrder.insert(maxDepth);
23990b57cec5SDimitry Andric           LLVM_DEBUG(dbgs() << maxDepth->NodeNum << " ");
24000b57cec5SDimitry Andric           R.remove(maxDepth);
24010b57cec5SDimitry Andric           if (Nodes.isExceedSU(maxDepth)) {
24020b57cec5SDimitry Andric             Order = TopDown;
24030b57cec5SDimitry Andric             R.clear();
24040b57cec5SDimitry Andric             R.insert(Nodes.getNode(0));
24050b57cec5SDimitry Andric             break;
24060b57cec5SDimitry Andric           }
24070b57cec5SDimitry Andric           for (const auto &I : maxDepth->Preds) {
24080b57cec5SDimitry Andric             if (Nodes.count(I.getSUnit()) == 0)
24090b57cec5SDimitry Andric               continue;
2410e8d8bef9SDimitry Andric             if (NodeOrder.contains(I.getSUnit()))
24110b57cec5SDimitry Andric               continue;
24120b57cec5SDimitry Andric             R.insert(I.getSUnit());
24130b57cec5SDimitry Andric           }
24140b57cec5SDimitry Andric           // Back-edges are predecessors with an anti-dependence.
24150b57cec5SDimitry Andric           for (const auto &I : maxDepth->Succs) {
24160b57cec5SDimitry Andric             if (I.getKind() != SDep::Anti)
24170b57cec5SDimitry Andric               continue;
24180b57cec5SDimitry Andric             if (Nodes.count(I.getSUnit()) == 0)
24190b57cec5SDimitry Andric               continue;
2420e8d8bef9SDimitry Andric             if (NodeOrder.contains(I.getSUnit()))
24210b57cec5SDimitry Andric               continue;
24220b57cec5SDimitry Andric             R.insert(I.getSUnit());
24230b57cec5SDimitry Andric           }
24240b57cec5SDimitry Andric         }
24250b57cec5SDimitry Andric         Order = TopDown;
24260b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "\n   Switching order to top down ");
24270b57cec5SDimitry Andric         SmallSetVector<SUnit *, 8> N;
24280b57cec5SDimitry Andric         if (succ_L(NodeOrder, N, &Nodes))
24290b57cec5SDimitry Andric           R.insert(N.begin(), N.end());
24300b57cec5SDimitry Andric       }
24310b57cec5SDimitry Andric     }
24320b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "\nDone with Nodeset\n");
24330b57cec5SDimitry Andric   }
24340b57cec5SDimitry Andric 
24350b57cec5SDimitry Andric   LLVM_DEBUG({
24360b57cec5SDimitry Andric     dbgs() << "Node order: ";
24370b57cec5SDimitry Andric     for (SUnit *I : NodeOrder)
24380b57cec5SDimitry Andric       dbgs() << " " << I->NodeNum << " ";
24390b57cec5SDimitry Andric     dbgs() << "\n";
24400b57cec5SDimitry Andric   });
24410b57cec5SDimitry Andric }
24420b57cec5SDimitry Andric 
24430b57cec5SDimitry Andric /// Process the nodes in the computed order and create the pipelined schedule
24440b57cec5SDimitry Andric /// of the instructions, if possible. Return true if a schedule is found.
24450b57cec5SDimitry Andric bool SwingSchedulerDAG::schedulePipeline(SMSchedule &Schedule) {
24460b57cec5SDimitry Andric 
24470b57cec5SDimitry Andric   if (NodeOrder.empty()){
24480b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "NodeOrder is empty! abort scheduling\n" );
24490b57cec5SDimitry Andric     return false;
24500b57cec5SDimitry Andric   }
24510b57cec5SDimitry Andric 
24520b57cec5SDimitry Andric   bool scheduleFound = false;
24537a6dacacSDimitry Andric   std::unique_ptr<HighRegisterPressureDetector> HRPDetector;
24547a6dacacSDimitry Andric   if (LimitRegPressure) {
24557a6dacacSDimitry Andric     HRPDetector =
24567a6dacacSDimitry Andric         std::make_unique<HighRegisterPressureDetector>(Loop.getHeader(), MF);
24577a6dacacSDimitry Andric     HRPDetector->init(RegClassInfo);
24587a6dacacSDimitry Andric   }
24590b57cec5SDimitry Andric   // Keep increasing II until a valid schedule is found.
2460fe6060f1SDimitry Andric   for (unsigned II = MII; II <= MAX_II && !scheduleFound; ++II) {
24610b57cec5SDimitry Andric     Schedule.reset();
24620b57cec5SDimitry Andric     Schedule.setInitiationInterval(II);
24630b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Try to schedule with " << II << "\n");
24640b57cec5SDimitry Andric 
24650b57cec5SDimitry Andric     SetVector<SUnit *>::iterator NI = NodeOrder.begin();
24660b57cec5SDimitry Andric     SetVector<SUnit *>::iterator NE = NodeOrder.end();
24670b57cec5SDimitry Andric     do {
24680b57cec5SDimitry Andric       SUnit *SU = *NI;
24690b57cec5SDimitry Andric 
24700b57cec5SDimitry Andric       // Compute the schedule time for the instruction, which is based
24710b57cec5SDimitry Andric       // upon the scheduled time for any predecessors/successors.
24720b57cec5SDimitry Andric       int EarlyStart = INT_MIN;
24730b57cec5SDimitry Andric       int LateStart = INT_MAX;
24740fca6ea1SDimitry Andric       Schedule.computeStart(SU, &EarlyStart, &LateStart, II, this);
24750b57cec5SDimitry Andric       LLVM_DEBUG({
24760b57cec5SDimitry Andric         dbgs() << "\n";
24770b57cec5SDimitry Andric         dbgs() << "Inst (" << SU->NodeNum << ") ";
24780b57cec5SDimitry Andric         SU->getInstr()->dump();
24790b57cec5SDimitry Andric         dbgs() << "\n";
24800b57cec5SDimitry Andric       });
24810fca6ea1SDimitry Andric       LLVM_DEBUG(
24820fca6ea1SDimitry Andric           dbgs() << format("\tes: %8x ls: %8x\n", EarlyStart, LateStart));
24830b57cec5SDimitry Andric 
24840fca6ea1SDimitry Andric       if (EarlyStart > LateStart)
24850b57cec5SDimitry Andric         scheduleFound = false;
24860fca6ea1SDimitry Andric       else if (EarlyStart != INT_MIN && LateStart == INT_MAX)
24870fca6ea1SDimitry Andric         scheduleFound =
24880fca6ea1SDimitry Andric             Schedule.insert(SU, EarlyStart, EarlyStart + (int)II - 1, II);
24890fca6ea1SDimitry Andric       else if (EarlyStart == INT_MIN && LateStart != INT_MAX)
24900fca6ea1SDimitry Andric         scheduleFound =
24910fca6ea1SDimitry Andric             Schedule.insert(SU, LateStart, LateStart - (int)II + 1, II);
24920fca6ea1SDimitry Andric       else if (EarlyStart != INT_MIN && LateStart != INT_MAX) {
24930fca6ea1SDimitry Andric         LateStart = std::min(LateStart, EarlyStart + (int)II - 1);
24940fca6ea1SDimitry Andric         // When scheduling a Phi it is better to start at the late cycle and
24950fca6ea1SDimitry Andric         // go backwards. The default order may insert the Phi too far away
24960fca6ea1SDimitry Andric         // from its first dependence.
24970fca6ea1SDimitry Andric         // Also, do backward search when all scheduled predecessors are
24980fca6ea1SDimitry Andric         // loop-carried output/order dependencies. Empirically, there are also
24990fca6ea1SDimitry Andric         // cases where scheduling becomes possible with backward search.
25000fca6ea1SDimitry Andric         if (SU->getInstr()->isPHI() ||
25010fca6ea1SDimitry Andric             Schedule.onlyHasLoopCarriedOutputOrOrderPreds(SU, this))
25020fca6ea1SDimitry Andric           scheduleFound = Schedule.insert(SU, LateStart, EarlyStart, II);
25030b57cec5SDimitry Andric         else
25040fca6ea1SDimitry Andric           scheduleFound = Schedule.insert(SU, EarlyStart, LateStart, II);
25050b57cec5SDimitry Andric       } else {
25060b57cec5SDimitry Andric         int FirstCycle = Schedule.getFirstCycle();
25070b57cec5SDimitry Andric         scheduleFound = Schedule.insert(SU, FirstCycle + getASAP(SU),
25080b57cec5SDimitry Andric                                         FirstCycle + getASAP(SU) + II - 1, II);
25090b57cec5SDimitry Andric       }
25100fca6ea1SDimitry Andric 
25110b57cec5SDimitry Andric       // Even if we find a schedule, make sure the schedule doesn't exceed the
25120b57cec5SDimitry Andric       // allowable number of stages. We keep trying if this happens.
25130b57cec5SDimitry Andric       if (scheduleFound)
25140b57cec5SDimitry Andric         if (SwpMaxStages > -1 &&
25150b57cec5SDimitry Andric             Schedule.getMaxStageCount() > (unsigned)SwpMaxStages)
25160b57cec5SDimitry Andric           scheduleFound = false;
25170b57cec5SDimitry Andric 
25180b57cec5SDimitry Andric       LLVM_DEBUG({
25190b57cec5SDimitry Andric         if (!scheduleFound)
25200b57cec5SDimitry Andric           dbgs() << "\tCan't schedule\n";
25210b57cec5SDimitry Andric       });
25220b57cec5SDimitry Andric     } while (++NI != NE && scheduleFound);
25230b57cec5SDimitry Andric 
252481ad6265SDimitry Andric     // If a schedule is found, ensure non-pipelined instructions are in stage 0
252581ad6265SDimitry Andric     if (scheduleFound)
252681ad6265SDimitry Andric       scheduleFound =
252781ad6265SDimitry Andric           Schedule.normalizeNonPipelinedInstructions(this, LoopPipelinerInfo);
252881ad6265SDimitry Andric 
25290b57cec5SDimitry Andric     // If a schedule is found, check if it is a valid schedule too.
25300b57cec5SDimitry Andric     if (scheduleFound)
25310b57cec5SDimitry Andric       scheduleFound = Schedule.isValidSchedule(this);
25327a6dacacSDimitry Andric 
25337a6dacacSDimitry Andric     // If a schedule was found and the option is enabled, check if the schedule
25347a6dacacSDimitry Andric     // might generate additional register spills/fills.
25357a6dacacSDimitry Andric     if (scheduleFound && LimitRegPressure)
25367a6dacacSDimitry Andric       scheduleFound =
25377a6dacacSDimitry Andric           !HRPDetector->detect(this, Schedule, Schedule.getMaxStageCount());
25380b57cec5SDimitry Andric   }
25390b57cec5SDimitry Andric 
2540fe6060f1SDimitry Andric   LLVM_DEBUG(dbgs() << "Schedule Found? " << scheduleFound
2541fe6060f1SDimitry Andric                     << " (II=" << Schedule.getInitiationInterval()
25420b57cec5SDimitry Andric                     << ")\n");
25430b57cec5SDimitry Andric 
25445ffd83dbSDimitry Andric   if (scheduleFound) {
2545bdd1243dSDimitry Andric     scheduleFound = LoopPipelinerInfo->shouldUseSchedule(*this, Schedule);
2546bdd1243dSDimitry Andric     if (!scheduleFound)
2547bdd1243dSDimitry Andric       LLVM_DEBUG(dbgs() << "Target rejected schedule\n");
2548bdd1243dSDimitry Andric   }
2549bdd1243dSDimitry Andric 
2550bdd1243dSDimitry Andric   if (scheduleFound) {
25510b57cec5SDimitry Andric     Schedule.finalizeSchedule(this);
25525ffd83dbSDimitry Andric     Pass.ORE->emit([&]() {
25535ffd83dbSDimitry Andric       return MachineOptimizationRemarkAnalysis(
25545ffd83dbSDimitry Andric                  DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
2555fe6060f1SDimitry Andric              << "Schedule found with Initiation Interval: "
2556fe6060f1SDimitry Andric              << ore::NV("II", Schedule.getInitiationInterval())
25575ffd83dbSDimitry Andric              << ", MaxStageCount: "
25585ffd83dbSDimitry Andric              << ore::NV("MaxStageCount", Schedule.getMaxStageCount());
25595ffd83dbSDimitry Andric     });
25605ffd83dbSDimitry Andric   } else
25610b57cec5SDimitry Andric     Schedule.reset();
25620b57cec5SDimitry Andric 
25630b57cec5SDimitry Andric   return scheduleFound && Schedule.getMaxStageCount() > 0;
25640b57cec5SDimitry Andric }
25650b57cec5SDimitry Andric 
25660b57cec5SDimitry Andric /// Return true if we can compute the amount the instruction changes
25670b57cec5SDimitry Andric /// during each iteration. Set Delta to the amount of the change.
25680b57cec5SDimitry Andric bool SwingSchedulerDAG::computeDelta(MachineInstr &MI, unsigned &Delta) {
25690b57cec5SDimitry Andric   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
25700b57cec5SDimitry Andric   const MachineOperand *BaseOp;
25710b57cec5SDimitry Andric   int64_t Offset;
25725ffd83dbSDimitry Andric   bool OffsetIsScalable;
25735ffd83dbSDimitry Andric   if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, OffsetIsScalable, TRI))
25745ffd83dbSDimitry Andric     return false;
25755ffd83dbSDimitry Andric 
25765ffd83dbSDimitry Andric   // FIXME: This algorithm assumes instructions have fixed-size offsets.
25775ffd83dbSDimitry Andric   if (OffsetIsScalable)
25780b57cec5SDimitry Andric     return false;
25790b57cec5SDimitry Andric 
25800b57cec5SDimitry Andric   if (!BaseOp->isReg())
25810b57cec5SDimitry Andric     return false;
25820b57cec5SDimitry Andric 
25838bcb0991SDimitry Andric   Register BaseReg = BaseOp->getReg();
25840b57cec5SDimitry Andric 
25850b57cec5SDimitry Andric   MachineRegisterInfo &MRI = MF.getRegInfo();
25860b57cec5SDimitry Andric   // Check if there is a Phi. If so, get the definition in the loop.
25870b57cec5SDimitry Andric   MachineInstr *BaseDef = MRI.getVRegDef(BaseReg);
25880b57cec5SDimitry Andric   if (BaseDef && BaseDef->isPHI()) {
25890b57cec5SDimitry Andric     BaseReg = getLoopPhiReg(*BaseDef, MI.getParent());
25900b57cec5SDimitry Andric     BaseDef = MRI.getVRegDef(BaseReg);
25910b57cec5SDimitry Andric   }
25920b57cec5SDimitry Andric   if (!BaseDef)
25930b57cec5SDimitry Andric     return false;
25940b57cec5SDimitry Andric 
25950b57cec5SDimitry Andric   int D = 0;
25960b57cec5SDimitry Andric   if (!TII->getIncrementValue(*BaseDef, D) && D >= 0)
25970b57cec5SDimitry Andric     return false;
25980b57cec5SDimitry Andric 
25990b57cec5SDimitry Andric   Delta = D;
26000b57cec5SDimitry Andric   return true;
26010b57cec5SDimitry Andric }
26020b57cec5SDimitry Andric 
26030b57cec5SDimitry Andric /// Check if we can change the instruction to use an offset value from the
26040b57cec5SDimitry Andric /// previous iteration. If so, return true and set the base and offset values
26050b57cec5SDimitry Andric /// so that we can rewrite the load, if necessary.
26060b57cec5SDimitry Andric ///   v1 = Phi(v0, v3)
26070b57cec5SDimitry Andric ///   v2 = load v1, 0
26080b57cec5SDimitry Andric ///   v3 = post_store v1, 4, x
26090b57cec5SDimitry Andric /// This function enables the load to be rewritten as v2 = load v3, 4.
26100b57cec5SDimitry Andric bool SwingSchedulerDAG::canUseLastOffsetValue(MachineInstr *MI,
26110b57cec5SDimitry Andric                                               unsigned &BasePos,
26120b57cec5SDimitry Andric                                               unsigned &OffsetPos,
26130b57cec5SDimitry Andric                                               unsigned &NewBase,
26140b57cec5SDimitry Andric                                               int64_t &Offset) {
26150b57cec5SDimitry Andric   // Get the load instruction.
26160b57cec5SDimitry Andric   if (TII->isPostIncrement(*MI))
26170b57cec5SDimitry Andric     return false;
26180b57cec5SDimitry Andric   unsigned BasePosLd, OffsetPosLd;
26190b57cec5SDimitry Andric   if (!TII->getBaseAndOffsetPosition(*MI, BasePosLd, OffsetPosLd))
26200b57cec5SDimitry Andric     return false;
26218bcb0991SDimitry Andric   Register BaseReg = MI->getOperand(BasePosLd).getReg();
26220b57cec5SDimitry Andric 
26230b57cec5SDimitry Andric   // Look for the Phi instruction.
26240b57cec5SDimitry Andric   MachineRegisterInfo &MRI = MI->getMF()->getRegInfo();
26250b57cec5SDimitry Andric   MachineInstr *Phi = MRI.getVRegDef(BaseReg);
26260b57cec5SDimitry Andric   if (!Phi || !Phi->isPHI())
26270b57cec5SDimitry Andric     return false;
26280b57cec5SDimitry Andric   // Get the register defined in the loop block.
26290b57cec5SDimitry Andric   unsigned PrevReg = getLoopPhiReg(*Phi, MI->getParent());
26300b57cec5SDimitry Andric   if (!PrevReg)
26310b57cec5SDimitry Andric     return false;
26320b57cec5SDimitry Andric 
26330b57cec5SDimitry Andric   // Check for the post-increment load/store instruction.
26340b57cec5SDimitry Andric   MachineInstr *PrevDef = MRI.getVRegDef(PrevReg);
26350b57cec5SDimitry Andric   if (!PrevDef || PrevDef == MI)
26360b57cec5SDimitry Andric     return false;
26370b57cec5SDimitry Andric 
26380b57cec5SDimitry Andric   if (!TII->isPostIncrement(*PrevDef))
26390b57cec5SDimitry Andric     return false;
26400b57cec5SDimitry Andric 
26410b57cec5SDimitry Andric   unsigned BasePos1 = 0, OffsetPos1 = 0;
26420b57cec5SDimitry Andric   if (!TII->getBaseAndOffsetPosition(*PrevDef, BasePos1, OffsetPos1))
26430b57cec5SDimitry Andric     return false;
26440b57cec5SDimitry Andric 
26450b57cec5SDimitry Andric   // Make sure that the instructions do not access the same memory location in
26460b57cec5SDimitry Andric   // the next iteration.
26470b57cec5SDimitry Andric   int64_t LoadOffset = MI->getOperand(OffsetPosLd).getImm();
26480b57cec5SDimitry Andric   int64_t StoreOffset = PrevDef->getOperand(OffsetPos1).getImm();
26490b57cec5SDimitry Andric   MachineInstr *NewMI = MF.CloneMachineInstr(MI);
26500b57cec5SDimitry Andric   NewMI->getOperand(OffsetPosLd).setImm(LoadOffset + StoreOffset);
26510b57cec5SDimitry Andric   bool Disjoint = TII->areMemAccessesTriviallyDisjoint(*NewMI, *PrevDef);
26520eae32dcSDimitry Andric   MF.deleteMachineInstr(NewMI);
26530b57cec5SDimitry Andric   if (!Disjoint)
26540b57cec5SDimitry Andric     return false;
26550b57cec5SDimitry Andric 
26560b57cec5SDimitry Andric   // Set the return value once we determine that we return true.
26570b57cec5SDimitry Andric   BasePos = BasePosLd;
26580b57cec5SDimitry Andric   OffsetPos = OffsetPosLd;
26590b57cec5SDimitry Andric   NewBase = PrevReg;
26600b57cec5SDimitry Andric   Offset = StoreOffset;
26610b57cec5SDimitry Andric   return true;
26620b57cec5SDimitry Andric }
26630b57cec5SDimitry Andric 
26640b57cec5SDimitry Andric /// Apply changes to the instruction if needed. The changes are need
26650b57cec5SDimitry Andric /// to improve the scheduling and depend up on the final schedule.
26660b57cec5SDimitry Andric void SwingSchedulerDAG::applyInstrChange(MachineInstr *MI,
26670b57cec5SDimitry Andric                                          SMSchedule &Schedule) {
26680b57cec5SDimitry Andric   SUnit *SU = getSUnit(MI);
26690b57cec5SDimitry Andric   DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
26700b57cec5SDimitry Andric       InstrChanges.find(SU);
26710b57cec5SDimitry Andric   if (It != InstrChanges.end()) {
26720b57cec5SDimitry Andric     std::pair<unsigned, int64_t> RegAndOffset = It->second;
26730b57cec5SDimitry Andric     unsigned BasePos, OffsetPos;
26740b57cec5SDimitry Andric     if (!TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
26750b57cec5SDimitry Andric       return;
26768bcb0991SDimitry Andric     Register BaseReg = MI->getOperand(BasePos).getReg();
26770b57cec5SDimitry Andric     MachineInstr *LoopDef = findDefInLoop(BaseReg);
26780b57cec5SDimitry Andric     int DefStageNum = Schedule.stageScheduled(getSUnit(LoopDef));
26790b57cec5SDimitry Andric     int DefCycleNum = Schedule.cycleScheduled(getSUnit(LoopDef));
26800b57cec5SDimitry Andric     int BaseStageNum = Schedule.stageScheduled(SU);
26810b57cec5SDimitry Andric     int BaseCycleNum = Schedule.cycleScheduled(SU);
26820b57cec5SDimitry Andric     if (BaseStageNum < DefStageNum) {
26830b57cec5SDimitry Andric       MachineInstr *NewMI = MF.CloneMachineInstr(MI);
26840b57cec5SDimitry Andric       int OffsetDiff = DefStageNum - BaseStageNum;
26850b57cec5SDimitry Andric       if (DefCycleNum < BaseCycleNum) {
26860b57cec5SDimitry Andric         NewMI->getOperand(BasePos).setReg(RegAndOffset.first);
26870b57cec5SDimitry Andric         if (OffsetDiff > 0)
26880b57cec5SDimitry Andric           --OffsetDiff;
26890b57cec5SDimitry Andric       }
26900b57cec5SDimitry Andric       int64_t NewOffset =
26910b57cec5SDimitry Andric           MI->getOperand(OffsetPos).getImm() + RegAndOffset.second * OffsetDiff;
26920b57cec5SDimitry Andric       NewMI->getOperand(OffsetPos).setImm(NewOffset);
26930b57cec5SDimitry Andric       SU->setInstr(NewMI);
26940b57cec5SDimitry Andric       MISUnitMap[NewMI] = SU;
26958bcb0991SDimitry Andric       NewMIs[MI] = NewMI;
26960b57cec5SDimitry Andric     }
26970b57cec5SDimitry Andric   }
26980b57cec5SDimitry Andric }
26990b57cec5SDimitry Andric 
27008bcb0991SDimitry Andric /// Return the instruction in the loop that defines the register.
27018bcb0991SDimitry Andric /// If the definition is a Phi, then follow the Phi operand to
27028bcb0991SDimitry Andric /// the instruction in the loop.
2703e8d8bef9SDimitry Andric MachineInstr *SwingSchedulerDAG::findDefInLoop(Register Reg) {
27048bcb0991SDimitry Andric   SmallPtrSet<MachineInstr *, 8> Visited;
27058bcb0991SDimitry Andric   MachineInstr *Def = MRI.getVRegDef(Reg);
27068bcb0991SDimitry Andric   while (Def->isPHI()) {
27078bcb0991SDimitry Andric     if (!Visited.insert(Def).second)
27088bcb0991SDimitry Andric       break;
27098bcb0991SDimitry Andric     for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2)
27108bcb0991SDimitry Andric       if (Def->getOperand(i + 1).getMBB() == BB) {
27118bcb0991SDimitry Andric         Def = MRI.getVRegDef(Def->getOperand(i).getReg());
27128bcb0991SDimitry Andric         break;
27138bcb0991SDimitry Andric       }
27148bcb0991SDimitry Andric   }
27158bcb0991SDimitry Andric   return Def;
27168bcb0991SDimitry Andric }
27178bcb0991SDimitry Andric 
27180b57cec5SDimitry Andric /// Return true for an order or output dependence that is loop carried
27195f757f3fSDimitry Andric /// potentially. A dependence is loop carried if the destination defines a value
27200b57cec5SDimitry Andric /// that may be used or defined by the source in a subsequent iteration.
27210b57cec5SDimitry Andric bool SwingSchedulerDAG::isLoopCarriedDep(SUnit *Source, const SDep &Dep,
27220b57cec5SDimitry Andric                                          bool isSucc) {
27230b57cec5SDimitry Andric   if ((Dep.getKind() != SDep::Order && Dep.getKind() != SDep::Output) ||
272481ad6265SDimitry Andric       Dep.isArtificial() || Dep.getSUnit()->isBoundaryNode())
27250b57cec5SDimitry Andric     return false;
27260b57cec5SDimitry Andric 
27270b57cec5SDimitry Andric   if (!SwpPruneLoopCarried)
27280b57cec5SDimitry Andric     return true;
27290b57cec5SDimitry Andric 
27300b57cec5SDimitry Andric   if (Dep.getKind() == SDep::Output)
27310b57cec5SDimitry Andric     return true;
27320b57cec5SDimitry Andric 
27330b57cec5SDimitry Andric   MachineInstr *SI = Source->getInstr();
27340b57cec5SDimitry Andric   MachineInstr *DI = Dep.getSUnit()->getInstr();
27350b57cec5SDimitry Andric   if (!isSucc)
27360b57cec5SDimitry Andric     std::swap(SI, DI);
27370b57cec5SDimitry Andric   assert(SI != nullptr && DI != nullptr && "Expecting SUnit with an MI.");
27380b57cec5SDimitry Andric 
27390b57cec5SDimitry Andric   // Assume ordered loads and stores may have a loop carried dependence.
27400b57cec5SDimitry Andric   if (SI->hasUnmodeledSideEffects() || DI->hasUnmodeledSideEffects() ||
27410b57cec5SDimitry Andric       SI->mayRaiseFPException() || DI->mayRaiseFPException() ||
27420b57cec5SDimitry Andric       SI->hasOrderedMemoryRef() || DI->hasOrderedMemoryRef())
27430b57cec5SDimitry Andric     return true;
27440b57cec5SDimitry Andric 
27455f757f3fSDimitry Andric   if (!DI->mayLoadOrStore() || !SI->mayLoadOrStore())
27460b57cec5SDimitry Andric     return false;
27470b57cec5SDimitry Andric 
27485f757f3fSDimitry Andric   // The conservative assumption is that a dependence between memory operations
27495f757f3fSDimitry Andric   // may be loop carried. The following code checks when it can be proved that
27505f757f3fSDimitry Andric   // there is no loop carried dependence.
27510b57cec5SDimitry Andric   unsigned DeltaS, DeltaD;
27520b57cec5SDimitry Andric   if (!computeDelta(*SI, DeltaS) || !computeDelta(*DI, DeltaD))
27530b57cec5SDimitry Andric     return true;
27540b57cec5SDimitry Andric 
27550b57cec5SDimitry Andric   const MachineOperand *BaseOpS, *BaseOpD;
27560b57cec5SDimitry Andric   int64_t OffsetS, OffsetD;
27575ffd83dbSDimitry Andric   bool OffsetSIsScalable, OffsetDIsScalable;
27580b57cec5SDimitry Andric   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
27595ffd83dbSDimitry Andric   if (!TII->getMemOperandWithOffset(*SI, BaseOpS, OffsetS, OffsetSIsScalable,
27605ffd83dbSDimitry Andric                                     TRI) ||
27615ffd83dbSDimitry Andric       !TII->getMemOperandWithOffset(*DI, BaseOpD, OffsetD, OffsetDIsScalable,
27625ffd83dbSDimitry Andric                                     TRI))
27630b57cec5SDimitry Andric     return true;
27640b57cec5SDimitry Andric 
27655ffd83dbSDimitry Andric   assert(!OffsetSIsScalable && !OffsetDIsScalable &&
27665ffd83dbSDimitry Andric          "Expected offsets to be byte offsets");
27675ffd83dbSDimitry Andric 
2768bdd1243dSDimitry Andric   MachineInstr *DefS = MRI.getVRegDef(BaseOpS->getReg());
2769bdd1243dSDimitry Andric   MachineInstr *DefD = MRI.getVRegDef(BaseOpD->getReg());
2770bdd1243dSDimitry Andric   if (!DefS || !DefD || !DefS->isPHI() || !DefD->isPHI())
2771bdd1243dSDimitry Andric     return true;
2772bdd1243dSDimitry Andric 
2773bdd1243dSDimitry Andric   unsigned InitValS = 0;
2774bdd1243dSDimitry Andric   unsigned LoopValS = 0;
2775bdd1243dSDimitry Andric   unsigned InitValD = 0;
2776bdd1243dSDimitry Andric   unsigned LoopValD = 0;
2777bdd1243dSDimitry Andric   getPhiRegs(*DefS, BB, InitValS, LoopValS);
2778bdd1243dSDimitry Andric   getPhiRegs(*DefD, BB, InitValD, LoopValD);
2779bdd1243dSDimitry Andric   MachineInstr *InitDefS = MRI.getVRegDef(InitValS);
2780bdd1243dSDimitry Andric   MachineInstr *InitDefD = MRI.getVRegDef(InitValD);
2781bdd1243dSDimitry Andric 
2782bdd1243dSDimitry Andric   if (!InitDefS->isIdenticalTo(*InitDefD))
27830b57cec5SDimitry Andric     return true;
27840b57cec5SDimitry Andric 
27850b57cec5SDimitry Andric   // Check that the base register is incremented by a constant value for each
27860b57cec5SDimitry Andric   // iteration.
2787bdd1243dSDimitry Andric   MachineInstr *LoopDefS = MRI.getVRegDef(LoopValS);
27880b57cec5SDimitry Andric   int D = 0;
2789bdd1243dSDimitry Andric   if (!LoopDefS || !TII->getIncrementValue(*LoopDefS, D))
27900b57cec5SDimitry Andric     return true;
27910b57cec5SDimitry Andric 
27920fca6ea1SDimitry Andric   LocationSize AccessSizeS = (*SI->memoperands_begin())->getSize();
27930fca6ea1SDimitry Andric   LocationSize AccessSizeD = (*DI->memoperands_begin())->getSize();
27940b57cec5SDimitry Andric 
27950b57cec5SDimitry Andric   // This is the main test, which checks the offset values and the loop
27960b57cec5SDimitry Andric   // increment value to determine if the accesses may be loop carried.
27970fca6ea1SDimitry Andric   if (!AccessSizeS.hasValue() || !AccessSizeD.hasValue())
27980b57cec5SDimitry Andric     return true;
27990b57cec5SDimitry Andric 
28000fca6ea1SDimitry Andric   if (DeltaS != DeltaD || DeltaS < AccessSizeS.getValue() ||
28010fca6ea1SDimitry Andric       DeltaD < AccessSizeD.getValue())
28020b57cec5SDimitry Andric     return true;
28030b57cec5SDimitry Andric 
28040fca6ea1SDimitry Andric   return (OffsetS + (int64_t)AccessSizeS.getValue() <
28050fca6ea1SDimitry Andric           OffsetD + (int64_t)AccessSizeD.getValue());
28060b57cec5SDimitry Andric }
28070b57cec5SDimitry Andric 
280806c3fb27SDimitry Andric void SwingSchedulerDAG::postProcessDAG() {
28090b57cec5SDimitry Andric   for (auto &M : Mutations)
28100b57cec5SDimitry Andric     M->apply(this);
28110b57cec5SDimitry Andric }
28120b57cec5SDimitry Andric 
28130b57cec5SDimitry Andric /// Try to schedule the node at the specified StartCycle and continue
28140b57cec5SDimitry Andric /// until the node is schedule or the EndCycle is reached.  This function
28150b57cec5SDimitry Andric /// returns true if the node is scheduled.  This routine may search either
28160b57cec5SDimitry Andric /// forward or backward for a place to insert the instruction based upon
28170b57cec5SDimitry Andric /// the relative values of StartCycle and EndCycle.
28180b57cec5SDimitry Andric bool SMSchedule::insert(SUnit *SU, int StartCycle, int EndCycle, int II) {
28190b57cec5SDimitry Andric   bool forward = true;
28200b57cec5SDimitry Andric   LLVM_DEBUG({
28210b57cec5SDimitry Andric     dbgs() << "Trying to insert node between " << StartCycle << " and "
28220b57cec5SDimitry Andric            << EndCycle << " II: " << II << "\n";
28230b57cec5SDimitry Andric   });
28240b57cec5SDimitry Andric   if (StartCycle > EndCycle)
28250b57cec5SDimitry Andric     forward = false;
28260b57cec5SDimitry Andric 
28270b57cec5SDimitry Andric   // The terminating condition depends on the direction.
28280b57cec5SDimitry Andric   int termCycle = forward ? EndCycle + 1 : EndCycle - 1;
28290b57cec5SDimitry Andric   for (int curCycle = StartCycle; curCycle != termCycle;
28300b57cec5SDimitry Andric        forward ? ++curCycle : --curCycle) {
28310b57cec5SDimitry Andric 
28320b57cec5SDimitry Andric     if (ST.getInstrInfo()->isZeroCost(SU->getInstr()->getOpcode()) ||
2833bdd1243dSDimitry Andric         ProcItinResources.canReserveResources(*SU, curCycle)) {
28340b57cec5SDimitry Andric       LLVM_DEBUG({
28350b57cec5SDimitry Andric         dbgs() << "\tinsert at cycle " << curCycle << " ";
28360b57cec5SDimitry Andric         SU->getInstr()->dump();
28370b57cec5SDimitry Andric       });
28380b57cec5SDimitry Andric 
2839bdd1243dSDimitry Andric       if (!ST.getInstrInfo()->isZeroCost(SU->getInstr()->getOpcode()))
2840bdd1243dSDimitry Andric         ProcItinResources.reserveResources(*SU, curCycle);
28410b57cec5SDimitry Andric       ScheduledInstrs[curCycle].push_back(SU);
28420b57cec5SDimitry Andric       InstrToCycle.insert(std::make_pair(SU, curCycle));
28430b57cec5SDimitry Andric       if (curCycle > LastCycle)
28440b57cec5SDimitry Andric         LastCycle = curCycle;
28450b57cec5SDimitry Andric       if (curCycle < FirstCycle)
28460b57cec5SDimitry Andric         FirstCycle = curCycle;
28470b57cec5SDimitry Andric       return true;
28480b57cec5SDimitry Andric     }
28490b57cec5SDimitry Andric     LLVM_DEBUG({
28500b57cec5SDimitry Andric       dbgs() << "\tfailed to insert at cycle " << curCycle << " ";
28510b57cec5SDimitry Andric       SU->getInstr()->dump();
28520b57cec5SDimitry Andric     });
28530b57cec5SDimitry Andric   }
28540b57cec5SDimitry Andric   return false;
28550b57cec5SDimitry Andric }
28560b57cec5SDimitry Andric 
28570b57cec5SDimitry Andric // Return the cycle of the earliest scheduled instruction in the chain.
28580b57cec5SDimitry Andric int SMSchedule::earliestCycleInChain(const SDep &Dep) {
28590b57cec5SDimitry Andric   SmallPtrSet<SUnit *, 8> Visited;
28600b57cec5SDimitry Andric   SmallVector<SDep, 8> Worklist;
28610b57cec5SDimitry Andric   Worklist.push_back(Dep);
28620b57cec5SDimitry Andric   int EarlyCycle = INT_MAX;
28630b57cec5SDimitry Andric   while (!Worklist.empty()) {
28640b57cec5SDimitry Andric     const SDep &Cur = Worklist.pop_back_val();
28650b57cec5SDimitry Andric     SUnit *PrevSU = Cur.getSUnit();
28660b57cec5SDimitry Andric     if (Visited.count(PrevSU))
28670b57cec5SDimitry Andric       continue;
28680b57cec5SDimitry Andric     std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(PrevSU);
28690b57cec5SDimitry Andric     if (it == InstrToCycle.end())
28700b57cec5SDimitry Andric       continue;
28710b57cec5SDimitry Andric     EarlyCycle = std::min(EarlyCycle, it->second);
28720b57cec5SDimitry Andric     for (const auto &PI : PrevSU->Preds)
28735ffd83dbSDimitry Andric       if (PI.getKind() == SDep::Order || PI.getKind() == SDep::Output)
28740b57cec5SDimitry Andric         Worklist.push_back(PI);
28750b57cec5SDimitry Andric     Visited.insert(PrevSU);
28760b57cec5SDimitry Andric   }
28770b57cec5SDimitry Andric   return EarlyCycle;
28780b57cec5SDimitry Andric }
28790b57cec5SDimitry Andric 
28800b57cec5SDimitry Andric // Return the cycle of the latest scheduled instruction in the chain.
28810b57cec5SDimitry Andric int SMSchedule::latestCycleInChain(const SDep &Dep) {
28820b57cec5SDimitry Andric   SmallPtrSet<SUnit *, 8> Visited;
28830b57cec5SDimitry Andric   SmallVector<SDep, 8> Worklist;
28840b57cec5SDimitry Andric   Worklist.push_back(Dep);
28850b57cec5SDimitry Andric   int LateCycle = INT_MIN;
28860b57cec5SDimitry Andric   while (!Worklist.empty()) {
28870b57cec5SDimitry Andric     const SDep &Cur = Worklist.pop_back_val();
28880b57cec5SDimitry Andric     SUnit *SuccSU = Cur.getSUnit();
288981ad6265SDimitry Andric     if (Visited.count(SuccSU) || SuccSU->isBoundaryNode())
28900b57cec5SDimitry Andric       continue;
28910b57cec5SDimitry Andric     std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SuccSU);
28920b57cec5SDimitry Andric     if (it == InstrToCycle.end())
28930b57cec5SDimitry Andric       continue;
28940b57cec5SDimitry Andric     LateCycle = std::max(LateCycle, it->second);
28950b57cec5SDimitry Andric     for (const auto &SI : SuccSU->Succs)
28965ffd83dbSDimitry Andric       if (SI.getKind() == SDep::Order || SI.getKind() == SDep::Output)
28970b57cec5SDimitry Andric         Worklist.push_back(SI);
28980b57cec5SDimitry Andric     Visited.insert(SuccSU);
28990b57cec5SDimitry Andric   }
29000b57cec5SDimitry Andric   return LateCycle;
29010b57cec5SDimitry Andric }
29020b57cec5SDimitry Andric 
29030b57cec5SDimitry Andric /// If an instruction has a use that spans multiple iterations, then
29040b57cec5SDimitry Andric /// return true. These instructions are characterized by having a back-ege
29050b57cec5SDimitry Andric /// to a Phi, which contains a reference to another Phi.
29060b57cec5SDimitry Andric static SUnit *multipleIterations(SUnit *SU, SwingSchedulerDAG *DAG) {
29070b57cec5SDimitry Andric   for (auto &P : SU->Preds)
29080b57cec5SDimitry Andric     if (DAG->isBackedge(SU, P) && P.getSUnit()->getInstr()->isPHI())
29090b57cec5SDimitry Andric       for (auto &S : P.getSUnit()->Succs)
29100b57cec5SDimitry Andric         if (S.getKind() == SDep::Data && S.getSUnit()->getInstr()->isPHI())
29110b57cec5SDimitry Andric           return P.getSUnit();
29120b57cec5SDimitry Andric   return nullptr;
29130b57cec5SDimitry Andric }
29140b57cec5SDimitry Andric 
29150b57cec5SDimitry Andric /// Compute the scheduling start slot for the instruction.  The start slot
29160b57cec5SDimitry Andric /// depends on any predecessor or successor nodes scheduled already.
29170b57cec5SDimitry Andric void SMSchedule::computeStart(SUnit *SU, int *MaxEarlyStart, int *MinLateStart,
29180fca6ea1SDimitry Andric                               int II, SwingSchedulerDAG *DAG) {
29190b57cec5SDimitry Andric   // Iterate over each instruction that has been scheduled already.  The start
29200b57cec5SDimitry Andric   // slot computation depends on whether the previously scheduled instruction
29210b57cec5SDimitry Andric   // is a predecessor or successor of the specified instruction.
29220b57cec5SDimitry Andric   for (int cycle = getFirstCycle(); cycle <= LastCycle; ++cycle) {
29230b57cec5SDimitry Andric 
29240b57cec5SDimitry Andric     // Iterate over each instruction in the current cycle.
29250b57cec5SDimitry Andric     for (SUnit *I : getInstructions(cycle)) {
29260b57cec5SDimitry Andric       // Because we're processing a DAG for the dependences, we recognize
29270b57cec5SDimitry Andric       // the back-edge in recurrences by anti dependences.
29280b57cec5SDimitry Andric       for (unsigned i = 0, e = (unsigned)SU->Preds.size(); i != e; ++i) {
29290b57cec5SDimitry Andric         const SDep &Dep = SU->Preds[i];
29300b57cec5SDimitry Andric         if (Dep.getSUnit() == I) {
29310b57cec5SDimitry Andric           if (!DAG->isBackedge(SU, Dep)) {
29320b57cec5SDimitry Andric             int EarlyStart = cycle + Dep.getLatency() -
29330b57cec5SDimitry Andric                              DAG->getDistance(Dep.getSUnit(), SU, Dep) * II;
29340b57cec5SDimitry Andric             *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
29350b57cec5SDimitry Andric             if (DAG->isLoopCarriedDep(SU, Dep, false)) {
29360b57cec5SDimitry Andric               int End = earliestCycleInChain(Dep) + (II - 1);
29370fca6ea1SDimitry Andric               *MinLateStart = std::min(*MinLateStart, End);
29380b57cec5SDimitry Andric             }
29390b57cec5SDimitry Andric           } else {
29400b57cec5SDimitry Andric             int LateStart = cycle - Dep.getLatency() +
29410b57cec5SDimitry Andric                             DAG->getDistance(SU, Dep.getSUnit(), Dep) * II;
29420b57cec5SDimitry Andric             *MinLateStart = std::min(*MinLateStart, LateStart);
29430b57cec5SDimitry Andric           }
29440b57cec5SDimitry Andric         }
29450b57cec5SDimitry Andric         // For instruction that requires multiple iterations, make sure that
29460b57cec5SDimitry Andric         // the dependent instruction is not scheduled past the definition.
29470b57cec5SDimitry Andric         SUnit *BE = multipleIterations(I, DAG);
29480b57cec5SDimitry Andric         if (BE && Dep.getSUnit() == BE && !SU->getInstr()->isPHI() &&
29490b57cec5SDimitry Andric             !SU->isPred(I))
29500b57cec5SDimitry Andric           *MinLateStart = std::min(*MinLateStart, cycle);
29510b57cec5SDimitry Andric       }
29520b57cec5SDimitry Andric       for (unsigned i = 0, e = (unsigned)SU->Succs.size(); i != e; ++i) {
29530b57cec5SDimitry Andric         if (SU->Succs[i].getSUnit() == I) {
29540b57cec5SDimitry Andric           const SDep &Dep = SU->Succs[i];
29550b57cec5SDimitry Andric           if (!DAG->isBackedge(SU, Dep)) {
29560b57cec5SDimitry Andric             int LateStart = cycle - Dep.getLatency() +
29570b57cec5SDimitry Andric                             DAG->getDistance(SU, Dep.getSUnit(), Dep) * II;
29580b57cec5SDimitry Andric             *MinLateStart = std::min(*MinLateStart, LateStart);
29590b57cec5SDimitry Andric             if (DAG->isLoopCarriedDep(SU, Dep)) {
29600b57cec5SDimitry Andric               int Start = latestCycleInChain(Dep) + 1 - II;
29610fca6ea1SDimitry Andric               *MaxEarlyStart = std::max(*MaxEarlyStart, Start);
29620b57cec5SDimitry Andric             }
29630b57cec5SDimitry Andric           } else {
29640b57cec5SDimitry Andric             int EarlyStart = cycle + Dep.getLatency() -
29650b57cec5SDimitry Andric                              DAG->getDistance(Dep.getSUnit(), SU, Dep) * II;
29660b57cec5SDimitry Andric             *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
29670b57cec5SDimitry Andric           }
29680b57cec5SDimitry Andric         }
29690b57cec5SDimitry Andric       }
29700b57cec5SDimitry Andric     }
29710b57cec5SDimitry Andric   }
29720b57cec5SDimitry Andric }
29730b57cec5SDimitry Andric 
29740b57cec5SDimitry Andric /// Order the instructions within a cycle so that the definitions occur
29750b57cec5SDimitry Andric /// before the uses. Returns true if the instruction is added to the start
29760b57cec5SDimitry Andric /// of the list, or false if added to the end.
29777a6dacacSDimitry Andric void SMSchedule::orderDependence(const SwingSchedulerDAG *SSD, SUnit *SU,
29787a6dacacSDimitry Andric                                  std::deque<SUnit *> &Insts) const {
29790b57cec5SDimitry Andric   MachineInstr *MI = SU->getInstr();
29800b57cec5SDimitry Andric   bool OrderBeforeUse = false;
29810b57cec5SDimitry Andric   bool OrderAfterDef = false;
29820b57cec5SDimitry Andric   bool OrderBeforeDef = false;
29830b57cec5SDimitry Andric   unsigned MoveDef = 0;
29840b57cec5SDimitry Andric   unsigned MoveUse = 0;
29850b57cec5SDimitry Andric   int StageInst1 = stageScheduled(SU);
29860b57cec5SDimitry Andric 
29870b57cec5SDimitry Andric   unsigned Pos = 0;
29880b57cec5SDimitry Andric   for (std::deque<SUnit *>::iterator I = Insts.begin(), E = Insts.end(); I != E;
29890b57cec5SDimitry Andric        ++I, ++Pos) {
29904824e7fdSDimitry Andric     for (MachineOperand &MO : MI->operands()) {
2991bdd1243dSDimitry Andric       if (!MO.isReg() || !MO.getReg().isVirtual())
29920b57cec5SDimitry Andric         continue;
29930b57cec5SDimitry Andric 
29948bcb0991SDimitry Andric       Register Reg = MO.getReg();
29950b57cec5SDimitry Andric       unsigned BasePos, OffsetPos;
29960b57cec5SDimitry Andric       if (ST.getInstrInfo()->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
29970b57cec5SDimitry Andric         if (MI->getOperand(BasePos).getReg() == Reg)
29980b57cec5SDimitry Andric           if (unsigned NewReg = SSD->getInstrBaseReg(SU))
29990b57cec5SDimitry Andric             Reg = NewReg;
30000b57cec5SDimitry Andric       bool Reads, Writes;
30010b57cec5SDimitry Andric       std::tie(Reads, Writes) =
30020b57cec5SDimitry Andric           (*I)->getInstr()->readsWritesVirtualRegister(Reg);
30030b57cec5SDimitry Andric       if (MO.isDef() && Reads && stageScheduled(*I) <= StageInst1) {
30040b57cec5SDimitry Andric         OrderBeforeUse = true;
30050b57cec5SDimitry Andric         if (MoveUse == 0)
30060b57cec5SDimitry Andric           MoveUse = Pos;
30070b57cec5SDimitry Andric       } else if (MO.isDef() && Reads && stageScheduled(*I) > StageInst1) {
30080b57cec5SDimitry Andric         // Add the instruction after the scheduled instruction.
30090b57cec5SDimitry Andric         OrderAfterDef = true;
30100b57cec5SDimitry Andric         MoveDef = Pos;
30110b57cec5SDimitry Andric       } else if (MO.isUse() && Writes && stageScheduled(*I) == StageInst1) {
30120b57cec5SDimitry Andric         if (cycleScheduled(*I) == cycleScheduled(SU) && !(*I)->isSucc(SU)) {
30130b57cec5SDimitry Andric           OrderBeforeUse = true;
30140b57cec5SDimitry Andric           if (MoveUse == 0)
30150b57cec5SDimitry Andric             MoveUse = Pos;
30160b57cec5SDimitry Andric         } else {
30170b57cec5SDimitry Andric           OrderAfterDef = true;
30180b57cec5SDimitry Andric           MoveDef = Pos;
30190b57cec5SDimitry Andric         }
30200b57cec5SDimitry Andric       } else if (MO.isUse() && Writes && stageScheduled(*I) > StageInst1) {
30210b57cec5SDimitry Andric         OrderBeforeUse = true;
30220b57cec5SDimitry Andric         if (MoveUse == 0)
30230b57cec5SDimitry Andric           MoveUse = Pos;
30240b57cec5SDimitry Andric         if (MoveUse != 0) {
30250b57cec5SDimitry Andric           OrderAfterDef = true;
30260b57cec5SDimitry Andric           MoveDef = Pos - 1;
30270b57cec5SDimitry Andric         }
30280b57cec5SDimitry Andric       } else if (MO.isUse() && Writes && stageScheduled(*I) < StageInst1) {
30290b57cec5SDimitry Andric         // Add the instruction before the scheduled instruction.
30300b57cec5SDimitry Andric         OrderBeforeUse = true;
30310b57cec5SDimitry Andric         if (MoveUse == 0)
30320b57cec5SDimitry Andric           MoveUse = Pos;
30330b57cec5SDimitry Andric       } else if (MO.isUse() && stageScheduled(*I) == StageInst1 &&
30340b57cec5SDimitry Andric                  isLoopCarriedDefOfUse(SSD, (*I)->getInstr(), MO)) {
30350b57cec5SDimitry Andric         if (MoveUse == 0) {
30360b57cec5SDimitry Andric           OrderBeforeDef = true;
30370b57cec5SDimitry Andric           MoveUse = Pos;
30380b57cec5SDimitry Andric         }
30390b57cec5SDimitry Andric       }
30400b57cec5SDimitry Andric     }
30410b57cec5SDimitry Andric     // Check for order dependences between instructions. Make sure the source
30420b57cec5SDimitry Andric     // is ordered before the destination.
30430b57cec5SDimitry Andric     for (auto &S : SU->Succs) {
30440b57cec5SDimitry Andric       if (S.getSUnit() != *I)
30450b57cec5SDimitry Andric         continue;
30460b57cec5SDimitry Andric       if (S.getKind() == SDep::Order && stageScheduled(*I) == StageInst1) {
30470b57cec5SDimitry Andric         OrderBeforeUse = true;
30480b57cec5SDimitry Andric         if (Pos < MoveUse)
30490b57cec5SDimitry Andric           MoveUse = Pos;
30500b57cec5SDimitry Andric       }
30510b57cec5SDimitry Andric       // We did not handle HW dependences in previous for loop,
30520b57cec5SDimitry Andric       // and we normally set Latency = 0 for Anti deps,
30530b57cec5SDimitry Andric       // so may have nodes in same cycle with Anti denpendent on HW regs.
30540b57cec5SDimitry Andric       else if (S.getKind() == SDep::Anti && stageScheduled(*I) == StageInst1) {
30550b57cec5SDimitry Andric         OrderBeforeUse = true;
30560b57cec5SDimitry Andric         if ((MoveUse == 0) || (Pos < MoveUse))
30570b57cec5SDimitry Andric           MoveUse = Pos;
30580b57cec5SDimitry Andric       }
30590b57cec5SDimitry Andric     }
30600b57cec5SDimitry Andric     for (auto &P : SU->Preds) {
30610b57cec5SDimitry Andric       if (P.getSUnit() != *I)
30620b57cec5SDimitry Andric         continue;
30630b57cec5SDimitry Andric       if (P.getKind() == SDep::Order && stageScheduled(*I) == StageInst1) {
30640b57cec5SDimitry Andric         OrderAfterDef = true;
30650b57cec5SDimitry Andric         MoveDef = Pos;
30660b57cec5SDimitry Andric       }
30670b57cec5SDimitry Andric     }
30680b57cec5SDimitry Andric   }
30690b57cec5SDimitry Andric 
30700b57cec5SDimitry Andric   // A circular dependence.
30710b57cec5SDimitry Andric   if (OrderAfterDef && OrderBeforeUse && MoveUse == MoveDef)
30720b57cec5SDimitry Andric     OrderBeforeUse = false;
30730b57cec5SDimitry Andric 
30740b57cec5SDimitry Andric   // OrderAfterDef takes precedences over OrderBeforeDef. The latter is due
30750b57cec5SDimitry Andric   // to a loop-carried dependence.
30760b57cec5SDimitry Andric   if (OrderBeforeDef)
30770b57cec5SDimitry Andric     OrderBeforeUse = !OrderAfterDef || (MoveUse > MoveDef);
30780b57cec5SDimitry Andric 
30790b57cec5SDimitry Andric   // The uncommon case when the instruction order needs to be updated because
30800b57cec5SDimitry Andric   // there is both a use and def.
30810b57cec5SDimitry Andric   if (OrderBeforeUse && OrderAfterDef) {
30820b57cec5SDimitry Andric     SUnit *UseSU = Insts.at(MoveUse);
30830b57cec5SDimitry Andric     SUnit *DefSU = Insts.at(MoveDef);
30840b57cec5SDimitry Andric     if (MoveUse > MoveDef) {
30850b57cec5SDimitry Andric       Insts.erase(Insts.begin() + MoveUse);
30860b57cec5SDimitry Andric       Insts.erase(Insts.begin() + MoveDef);
30870b57cec5SDimitry Andric     } else {
30880b57cec5SDimitry Andric       Insts.erase(Insts.begin() + MoveDef);
30890b57cec5SDimitry Andric       Insts.erase(Insts.begin() + MoveUse);
30900b57cec5SDimitry Andric     }
30910b57cec5SDimitry Andric     orderDependence(SSD, UseSU, Insts);
30920b57cec5SDimitry Andric     orderDependence(SSD, SU, Insts);
30930b57cec5SDimitry Andric     orderDependence(SSD, DefSU, Insts);
30940b57cec5SDimitry Andric     return;
30950b57cec5SDimitry Andric   }
30960b57cec5SDimitry Andric   // Put the new instruction first if there is a use in the list. Otherwise,
30970b57cec5SDimitry Andric   // put it at the end of the list.
30980b57cec5SDimitry Andric   if (OrderBeforeUse)
30990b57cec5SDimitry Andric     Insts.push_front(SU);
31000b57cec5SDimitry Andric   else
31010b57cec5SDimitry Andric     Insts.push_back(SU);
31020b57cec5SDimitry Andric }
31030b57cec5SDimitry Andric 
31040b57cec5SDimitry Andric /// Return true if the scheduled Phi has a loop carried operand.
31057a6dacacSDimitry Andric bool SMSchedule::isLoopCarried(const SwingSchedulerDAG *SSD,
31067a6dacacSDimitry Andric                                MachineInstr &Phi) const {
31070b57cec5SDimitry Andric   if (!Phi.isPHI())
31080b57cec5SDimitry Andric     return false;
31090b57cec5SDimitry Andric   assert(Phi.isPHI() && "Expecting a Phi.");
31100b57cec5SDimitry Andric   SUnit *DefSU = SSD->getSUnit(&Phi);
31110b57cec5SDimitry Andric   unsigned DefCycle = cycleScheduled(DefSU);
31120b57cec5SDimitry Andric   int DefStage = stageScheduled(DefSU);
31130b57cec5SDimitry Andric 
31140b57cec5SDimitry Andric   unsigned InitVal = 0;
31150b57cec5SDimitry Andric   unsigned LoopVal = 0;
31160b57cec5SDimitry Andric   getPhiRegs(Phi, Phi.getParent(), InitVal, LoopVal);
31170b57cec5SDimitry Andric   SUnit *UseSU = SSD->getSUnit(MRI.getVRegDef(LoopVal));
31180b57cec5SDimitry Andric   if (!UseSU)
31190b57cec5SDimitry Andric     return true;
31200b57cec5SDimitry Andric   if (UseSU->getInstr()->isPHI())
31210b57cec5SDimitry Andric     return true;
31220b57cec5SDimitry Andric   unsigned LoopCycle = cycleScheduled(UseSU);
31230b57cec5SDimitry Andric   int LoopStage = stageScheduled(UseSU);
31240b57cec5SDimitry Andric   return (LoopCycle > DefCycle) || (LoopStage <= DefStage);
31250b57cec5SDimitry Andric }
31260b57cec5SDimitry Andric 
31270b57cec5SDimitry Andric /// Return true if the instruction is a definition that is loop carried
31280b57cec5SDimitry Andric /// and defines the use on the next iteration.
31290b57cec5SDimitry Andric ///        v1 = phi(v2, v3)
31300b57cec5SDimitry Andric ///  (Def) v3 = op v1
31310b57cec5SDimitry Andric ///  (MO)   = v1
31325f757f3fSDimitry Andric /// If MO appears before Def, then v1 and v3 may get assigned to the same
31330b57cec5SDimitry Andric /// register.
31347a6dacacSDimitry Andric bool SMSchedule::isLoopCarriedDefOfUse(const SwingSchedulerDAG *SSD,
31357a6dacacSDimitry Andric                                        MachineInstr *Def,
31367a6dacacSDimitry Andric                                        MachineOperand &MO) const {
31370b57cec5SDimitry Andric   if (!MO.isReg())
31380b57cec5SDimitry Andric     return false;
31390b57cec5SDimitry Andric   if (Def->isPHI())
31400b57cec5SDimitry Andric     return false;
31410b57cec5SDimitry Andric   MachineInstr *Phi = MRI.getVRegDef(MO.getReg());
31420b57cec5SDimitry Andric   if (!Phi || !Phi->isPHI() || Phi->getParent() != Def->getParent())
31430b57cec5SDimitry Andric     return false;
31440b57cec5SDimitry Andric   if (!isLoopCarried(SSD, *Phi))
31450b57cec5SDimitry Andric     return false;
31460b57cec5SDimitry Andric   unsigned LoopReg = getLoopPhiReg(*Phi, Phi->getParent());
314706c3fb27SDimitry Andric   for (MachineOperand &DMO : Def->all_defs()) {
31480b57cec5SDimitry Andric     if (DMO.getReg() == LoopReg)
31490b57cec5SDimitry Andric       return true;
31500b57cec5SDimitry Andric   }
31510b57cec5SDimitry Andric   return false;
31520b57cec5SDimitry Andric }
31530b57cec5SDimitry Andric 
31540fca6ea1SDimitry Andric /// Return true if all scheduled predecessors are loop-carried output/order
31550fca6ea1SDimitry Andric /// dependencies.
31560fca6ea1SDimitry Andric bool SMSchedule::onlyHasLoopCarriedOutputOrOrderPreds(
31570fca6ea1SDimitry Andric     SUnit *SU, SwingSchedulerDAG *DAG) const {
31580fca6ea1SDimitry Andric   for (const SDep &Pred : SU->Preds)
31590fca6ea1SDimitry Andric     if (InstrToCycle.count(Pred.getSUnit()) && !DAG->isBackedge(SU, Pred))
31600fca6ea1SDimitry Andric       return false;
31610fca6ea1SDimitry Andric   for (const SDep &Succ : SU->Succs)
31620fca6ea1SDimitry Andric     if (InstrToCycle.count(Succ.getSUnit()) && DAG->isBackedge(SU, Succ))
31630fca6ea1SDimitry Andric       return false;
31640fca6ea1SDimitry Andric   return true;
31650fca6ea1SDimitry Andric }
31660fca6ea1SDimitry Andric 
316781ad6265SDimitry Andric /// Determine transitive dependences of unpipelineable instructions
316881ad6265SDimitry Andric SmallSet<SUnit *, 8> SMSchedule::computeUnpipelineableNodes(
316981ad6265SDimitry Andric     SwingSchedulerDAG *SSD, TargetInstrInfo::PipelinerLoopInfo *PLI) {
317081ad6265SDimitry Andric   SmallSet<SUnit *, 8> DoNotPipeline;
317181ad6265SDimitry Andric   SmallVector<SUnit *, 8> Worklist;
317281ad6265SDimitry Andric 
317381ad6265SDimitry Andric   for (auto &SU : SSD->SUnits)
317481ad6265SDimitry Andric     if (SU.isInstr() && PLI->shouldIgnoreForPipelining(SU.getInstr()))
317581ad6265SDimitry Andric       Worklist.push_back(&SU);
317681ad6265SDimitry Andric 
317781ad6265SDimitry Andric   while (!Worklist.empty()) {
317881ad6265SDimitry Andric     auto SU = Worklist.pop_back_val();
317981ad6265SDimitry Andric     if (DoNotPipeline.count(SU))
318081ad6265SDimitry Andric       continue;
318181ad6265SDimitry Andric     LLVM_DEBUG(dbgs() << "Do not pipeline SU(" << SU->NodeNum << ")\n");
318281ad6265SDimitry Andric     DoNotPipeline.insert(SU);
318381ad6265SDimitry Andric     for (auto &Dep : SU->Preds)
318481ad6265SDimitry Andric       Worklist.push_back(Dep.getSUnit());
318581ad6265SDimitry Andric     if (SU->getInstr()->isPHI())
318681ad6265SDimitry Andric       for (auto &Dep : SU->Succs)
318781ad6265SDimitry Andric         if (Dep.getKind() == SDep::Anti)
318881ad6265SDimitry Andric           Worklist.push_back(Dep.getSUnit());
318981ad6265SDimitry Andric   }
319081ad6265SDimitry Andric   return DoNotPipeline;
319181ad6265SDimitry Andric }
319281ad6265SDimitry Andric 
319381ad6265SDimitry Andric // Determine all instructions upon which any unpipelineable instruction depends
319481ad6265SDimitry Andric // and ensure that they are in stage 0.  If unable to do so, return false.
319581ad6265SDimitry Andric bool SMSchedule::normalizeNonPipelinedInstructions(
319681ad6265SDimitry Andric     SwingSchedulerDAG *SSD, TargetInstrInfo::PipelinerLoopInfo *PLI) {
319781ad6265SDimitry Andric   SmallSet<SUnit *, 8> DNP = computeUnpipelineableNodes(SSD, PLI);
319881ad6265SDimitry Andric 
319981ad6265SDimitry Andric   int NewLastCycle = INT_MIN;
320081ad6265SDimitry Andric   for (SUnit &SU : SSD->SUnits) {
320181ad6265SDimitry Andric     if (!SU.isInstr())
320281ad6265SDimitry Andric       continue;
320381ad6265SDimitry Andric     if (!DNP.contains(&SU) || stageScheduled(&SU) == 0) {
320481ad6265SDimitry Andric       NewLastCycle = std::max(NewLastCycle, InstrToCycle[&SU]);
320581ad6265SDimitry Andric       continue;
320681ad6265SDimitry Andric     }
320781ad6265SDimitry Andric 
320881ad6265SDimitry Andric     // Put the non-pipelined instruction as early as possible in the schedule
320981ad6265SDimitry Andric     int NewCycle = getFirstCycle();
321081ad6265SDimitry Andric     for (auto &Dep : SU.Preds)
321181ad6265SDimitry Andric       NewCycle = std::max(InstrToCycle[Dep.getSUnit()], NewCycle);
321281ad6265SDimitry Andric 
321381ad6265SDimitry Andric     int OldCycle = InstrToCycle[&SU];
321481ad6265SDimitry Andric     if (OldCycle != NewCycle) {
321581ad6265SDimitry Andric       InstrToCycle[&SU] = NewCycle;
321681ad6265SDimitry Andric       auto &OldS = getInstructions(OldCycle);
32175f757f3fSDimitry Andric       llvm::erase(OldS, &SU);
321881ad6265SDimitry Andric       getInstructions(NewCycle).emplace_back(&SU);
321981ad6265SDimitry Andric       LLVM_DEBUG(dbgs() << "SU(" << SU.NodeNum
322081ad6265SDimitry Andric                         << ") is not pipelined; moving from cycle " << OldCycle
322181ad6265SDimitry Andric                         << " to " << NewCycle << " Instr:" << *SU.getInstr());
322281ad6265SDimitry Andric     }
322381ad6265SDimitry Andric     NewLastCycle = std::max(NewLastCycle, NewCycle);
322481ad6265SDimitry Andric   }
322581ad6265SDimitry Andric   LastCycle = NewLastCycle;
322681ad6265SDimitry Andric   return true;
322781ad6265SDimitry Andric }
322881ad6265SDimitry Andric 
32290b57cec5SDimitry Andric // Check if the generated schedule is valid. This function checks if
32300b57cec5SDimitry Andric // an instruction that uses a physical register is scheduled in a
32310b57cec5SDimitry Andric // different stage than the definition. The pipeliner does not handle
32320b57cec5SDimitry Andric // physical register values that may cross a basic block boundary.
323381ad6265SDimitry Andric // Furthermore, if a physical def/use pair is assigned to the same
323481ad6265SDimitry Andric // cycle, orderDependence does not guarantee def/use ordering, so that
323581ad6265SDimitry Andric // case should be considered invalid.  (The test checks for both
323681ad6265SDimitry Andric // earlier and same-cycle use to be more robust.)
32370b57cec5SDimitry Andric bool SMSchedule::isValidSchedule(SwingSchedulerDAG *SSD) {
3238fe6060f1SDimitry Andric   for (SUnit &SU : SSD->SUnits) {
32390b57cec5SDimitry Andric     if (!SU.hasPhysRegDefs)
32400b57cec5SDimitry Andric       continue;
32410b57cec5SDimitry Andric     int StageDef = stageScheduled(&SU);
324281ad6265SDimitry Andric     int CycleDef = InstrToCycle[&SU];
32430b57cec5SDimitry Andric     assert(StageDef != -1 && "Instruction should have been scheduled.");
32440b57cec5SDimitry Andric     for (auto &SI : SU.Succs)
324581ad6265SDimitry Andric       if (SI.isAssignedRegDep() && !SI.getSUnit()->isBoundaryNode())
324681ad6265SDimitry Andric         if (Register::isPhysicalRegister(SI.getReg())) {
32470b57cec5SDimitry Andric           if (stageScheduled(SI.getSUnit()) != StageDef)
32480b57cec5SDimitry Andric             return false;
324981ad6265SDimitry Andric           if (InstrToCycle[SI.getSUnit()] <= CycleDef)
325081ad6265SDimitry Andric             return false;
325181ad6265SDimitry Andric         }
32520b57cec5SDimitry Andric   }
32530b57cec5SDimitry Andric   return true;
32540b57cec5SDimitry Andric }
32550b57cec5SDimitry Andric 
32560b57cec5SDimitry Andric /// A property of the node order in swing-modulo-scheduling is
32570b57cec5SDimitry Andric /// that for nodes outside circuits the following holds:
32580b57cec5SDimitry Andric /// none of them is scheduled after both a successor and a
32590b57cec5SDimitry Andric /// predecessor.
32600b57cec5SDimitry Andric /// The method below checks whether the property is met.
32610b57cec5SDimitry Andric /// If not, debug information is printed and statistics information updated.
32620b57cec5SDimitry Andric /// Note that we do not use an assert statement.
32630b57cec5SDimitry Andric /// The reason is that although an invalid node oder may prevent
32640b57cec5SDimitry Andric /// the pipeliner from finding a pipelined schedule for arbitrary II,
32650b57cec5SDimitry Andric /// it does not lead to the generation of incorrect code.
32660b57cec5SDimitry Andric void SwingSchedulerDAG::checkValidNodeOrder(const NodeSetType &Circuits) const {
32670b57cec5SDimitry Andric 
32680b57cec5SDimitry Andric   // a sorted vector that maps each SUnit to its index in the NodeOrder
32690b57cec5SDimitry Andric   typedef std::pair<SUnit *, unsigned> UnitIndex;
32700b57cec5SDimitry Andric   std::vector<UnitIndex> Indices(NodeOrder.size(), std::make_pair(nullptr, 0));
32710b57cec5SDimitry Andric 
32720b57cec5SDimitry Andric   for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i)
32730b57cec5SDimitry Andric     Indices.push_back(std::make_pair(NodeOrder[i], i));
32740b57cec5SDimitry Andric 
32750b57cec5SDimitry Andric   auto CompareKey = [](UnitIndex i1, UnitIndex i2) {
32760b57cec5SDimitry Andric     return std::get<0>(i1) < std::get<0>(i2);
32770b57cec5SDimitry Andric   };
32780b57cec5SDimitry Andric 
32790b57cec5SDimitry Andric   // sort, so that we can perform a binary search
32800b57cec5SDimitry Andric   llvm::sort(Indices, CompareKey);
32810b57cec5SDimitry Andric 
32820b57cec5SDimitry Andric   bool Valid = true;
32830b57cec5SDimitry Andric   (void)Valid;
32840b57cec5SDimitry Andric   // for each SUnit in the NodeOrder, check whether
32850b57cec5SDimitry Andric   // it appears after both a successor and a predecessor
32860b57cec5SDimitry Andric   // of the SUnit. If this is the case, and the SUnit
32870b57cec5SDimitry Andric   // is not part of circuit, then the NodeOrder is not
32880b57cec5SDimitry Andric   // valid.
32890b57cec5SDimitry Andric   for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i) {
32900b57cec5SDimitry Andric     SUnit *SU = NodeOrder[i];
32910b57cec5SDimitry Andric     unsigned Index = i;
32920b57cec5SDimitry Andric 
32930b57cec5SDimitry Andric     bool PredBefore = false;
32940b57cec5SDimitry Andric     bool SuccBefore = false;
32950b57cec5SDimitry Andric 
32960b57cec5SDimitry Andric     SUnit *Succ;
32970b57cec5SDimitry Andric     SUnit *Pred;
32980b57cec5SDimitry Andric     (void)Succ;
32990b57cec5SDimitry Andric     (void)Pred;
33000b57cec5SDimitry Andric 
33010b57cec5SDimitry Andric     for (SDep &PredEdge : SU->Preds) {
33020b57cec5SDimitry Andric       SUnit *PredSU = PredEdge.getSUnit();
33030b57cec5SDimitry Andric       unsigned PredIndex = std::get<1>(
33040b57cec5SDimitry Andric           *llvm::lower_bound(Indices, std::make_pair(PredSU, 0), CompareKey));
33050b57cec5SDimitry Andric       if (!PredSU->getInstr()->isPHI() && PredIndex < Index) {
33060b57cec5SDimitry Andric         PredBefore = true;
33070b57cec5SDimitry Andric         Pred = PredSU;
33080b57cec5SDimitry Andric         break;
33090b57cec5SDimitry Andric       }
33100b57cec5SDimitry Andric     }
33110b57cec5SDimitry Andric 
33120b57cec5SDimitry Andric     for (SDep &SuccEdge : SU->Succs) {
33130b57cec5SDimitry Andric       SUnit *SuccSU = SuccEdge.getSUnit();
33140b57cec5SDimitry Andric       // Do not process a boundary node, it was not included in NodeOrder,
33150b57cec5SDimitry Andric       // hence not in Indices either, call to std::lower_bound() below will
33160b57cec5SDimitry Andric       // return Indices.end().
33170b57cec5SDimitry Andric       if (SuccSU->isBoundaryNode())
33180b57cec5SDimitry Andric         continue;
33190b57cec5SDimitry Andric       unsigned SuccIndex = std::get<1>(
33200b57cec5SDimitry Andric           *llvm::lower_bound(Indices, std::make_pair(SuccSU, 0), CompareKey));
33210b57cec5SDimitry Andric       if (!SuccSU->getInstr()->isPHI() && SuccIndex < Index) {
33220b57cec5SDimitry Andric         SuccBefore = true;
33230b57cec5SDimitry Andric         Succ = SuccSU;
33240b57cec5SDimitry Andric         break;
33250b57cec5SDimitry Andric       }
33260b57cec5SDimitry Andric     }
33270b57cec5SDimitry Andric 
33280b57cec5SDimitry Andric     if (PredBefore && SuccBefore && !SU->getInstr()->isPHI()) {
33290b57cec5SDimitry Andric       // instructions in circuits are allowed to be scheduled
33300b57cec5SDimitry Andric       // after both a successor and predecessor.
33310b57cec5SDimitry Andric       bool InCircuit = llvm::any_of(
33320b57cec5SDimitry Andric           Circuits, [SU](const NodeSet &Circuit) { return Circuit.count(SU); });
33330b57cec5SDimitry Andric       if (InCircuit)
33340b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "In a circuit, predecessor ";);
33350b57cec5SDimitry Andric       else {
33360b57cec5SDimitry Andric         Valid = false;
33370b57cec5SDimitry Andric         NumNodeOrderIssues++;
33380b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "Predecessor ";);
33390b57cec5SDimitry Andric       }
33400b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << Pred->NodeNum << " and successor " << Succ->NodeNum
33410b57cec5SDimitry Andric                         << " are scheduled before node " << SU->NodeNum
33420b57cec5SDimitry Andric                         << "\n";);
33430b57cec5SDimitry Andric     }
33440b57cec5SDimitry Andric   }
33450b57cec5SDimitry Andric 
33460b57cec5SDimitry Andric   LLVM_DEBUG({
33470b57cec5SDimitry Andric     if (!Valid)
33480b57cec5SDimitry Andric       dbgs() << "Invalid node order found!\n";
33490b57cec5SDimitry Andric   });
33500b57cec5SDimitry Andric }
33510b57cec5SDimitry Andric 
33520b57cec5SDimitry Andric /// Attempt to fix the degenerate cases when the instruction serialization
33530b57cec5SDimitry Andric /// causes the register lifetimes to overlap. For example,
33540b57cec5SDimitry Andric ///   p' = store_pi(p, b)
33550b57cec5SDimitry Andric ///      = load p, offset
33560b57cec5SDimitry Andric /// In this case p and p' overlap, which means that two registers are needed.
33570b57cec5SDimitry Andric /// Instead, this function changes the load to use p' and updates the offset.
33580b57cec5SDimitry Andric void SwingSchedulerDAG::fixupRegisterOverlaps(std::deque<SUnit *> &Instrs) {
33590b57cec5SDimitry Andric   unsigned OverlapReg = 0;
33600b57cec5SDimitry Andric   unsigned NewBaseReg = 0;
33610b57cec5SDimitry Andric   for (SUnit *SU : Instrs) {
33620b57cec5SDimitry Andric     MachineInstr *MI = SU->getInstr();
33630b57cec5SDimitry Andric     for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
33640b57cec5SDimitry Andric       const MachineOperand &MO = MI->getOperand(i);
33650b57cec5SDimitry Andric       // Look for an instruction that uses p. The instruction occurs in the
33660b57cec5SDimitry Andric       // same cycle but occurs later in the serialized order.
33670b57cec5SDimitry Andric       if (MO.isReg() && MO.isUse() && MO.getReg() == OverlapReg) {
33680b57cec5SDimitry Andric         // Check that the instruction appears in the InstrChanges structure,
33690b57cec5SDimitry Andric         // which contains instructions that can have the offset updated.
33700b57cec5SDimitry Andric         DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
33710b57cec5SDimitry Andric           InstrChanges.find(SU);
33720b57cec5SDimitry Andric         if (It != InstrChanges.end()) {
33730b57cec5SDimitry Andric           unsigned BasePos, OffsetPos;
33740b57cec5SDimitry Andric           // Update the base register and adjust the offset.
33750b57cec5SDimitry Andric           if (TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos)) {
33760b57cec5SDimitry Andric             MachineInstr *NewMI = MF.CloneMachineInstr(MI);
33770b57cec5SDimitry Andric             NewMI->getOperand(BasePos).setReg(NewBaseReg);
33780b57cec5SDimitry Andric             int64_t NewOffset =
33790b57cec5SDimitry Andric                 MI->getOperand(OffsetPos).getImm() - It->second.second;
33800b57cec5SDimitry Andric             NewMI->getOperand(OffsetPos).setImm(NewOffset);
33810b57cec5SDimitry Andric             SU->setInstr(NewMI);
33820b57cec5SDimitry Andric             MISUnitMap[NewMI] = SU;
33838bcb0991SDimitry Andric             NewMIs[MI] = NewMI;
33840b57cec5SDimitry Andric           }
33850b57cec5SDimitry Andric         }
33860b57cec5SDimitry Andric         OverlapReg = 0;
33870b57cec5SDimitry Andric         NewBaseReg = 0;
33880b57cec5SDimitry Andric         break;
33890b57cec5SDimitry Andric       }
33900b57cec5SDimitry Andric       // Look for an instruction of the form p' = op(p), which uses and defines
33910b57cec5SDimitry Andric       // two virtual registers that get allocated to the same physical register.
33920b57cec5SDimitry Andric       unsigned TiedUseIdx = 0;
33930b57cec5SDimitry Andric       if (MI->isRegTiedToUseOperand(i, &TiedUseIdx)) {
33940b57cec5SDimitry Andric         // OverlapReg is p in the example above.
33950b57cec5SDimitry Andric         OverlapReg = MI->getOperand(TiedUseIdx).getReg();
33960b57cec5SDimitry Andric         // NewBaseReg is p' in the example above.
33970b57cec5SDimitry Andric         NewBaseReg = MI->getOperand(i).getReg();
33980b57cec5SDimitry Andric         break;
33990b57cec5SDimitry Andric       }
34000b57cec5SDimitry Andric     }
34010b57cec5SDimitry Andric   }
34020b57cec5SDimitry Andric }
34030b57cec5SDimitry Andric 
34047a6dacacSDimitry Andric std::deque<SUnit *>
34057a6dacacSDimitry Andric SMSchedule::reorderInstructions(const SwingSchedulerDAG *SSD,
34067a6dacacSDimitry Andric                                 const std::deque<SUnit *> &Instrs) const {
34077a6dacacSDimitry Andric   std::deque<SUnit *> NewOrderPhi;
34087a6dacacSDimitry Andric   for (SUnit *SU : Instrs) {
34097a6dacacSDimitry Andric     if (SU->getInstr()->isPHI())
34107a6dacacSDimitry Andric       NewOrderPhi.push_back(SU);
34117a6dacacSDimitry Andric   }
34127a6dacacSDimitry Andric   std::deque<SUnit *> NewOrderI;
34137a6dacacSDimitry Andric   for (SUnit *SU : Instrs) {
34147a6dacacSDimitry Andric     if (!SU->getInstr()->isPHI())
34157a6dacacSDimitry Andric       orderDependence(SSD, SU, NewOrderI);
34167a6dacacSDimitry Andric   }
34177a6dacacSDimitry Andric   llvm::append_range(NewOrderPhi, NewOrderI);
34187a6dacacSDimitry Andric   return NewOrderPhi;
34197a6dacacSDimitry Andric }
34207a6dacacSDimitry Andric 
34210b57cec5SDimitry Andric /// After the schedule has been formed, call this function to combine
34220b57cec5SDimitry Andric /// the instructions from the different stages/cycles.  That is, this
34230b57cec5SDimitry Andric /// function creates a schedule that represents a single iteration.
34240b57cec5SDimitry Andric void SMSchedule::finalizeSchedule(SwingSchedulerDAG *SSD) {
34250b57cec5SDimitry Andric   // Move all instructions to the first stage from later stages.
34260b57cec5SDimitry Andric   for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
34270b57cec5SDimitry Andric     for (int stage = 1, lastStage = getMaxStageCount(); stage <= lastStage;
34280b57cec5SDimitry Andric          ++stage) {
34290b57cec5SDimitry Andric       std::deque<SUnit *> &cycleInstrs =
34300b57cec5SDimitry Andric           ScheduledInstrs[cycle + (stage * InitiationInterval)];
34310eae32dcSDimitry Andric       for (SUnit *SU : llvm::reverse(cycleInstrs))
34320eae32dcSDimitry Andric         ScheduledInstrs[cycle].push_front(SU);
34330b57cec5SDimitry Andric     }
34340b57cec5SDimitry Andric   }
34350b57cec5SDimitry Andric 
34360b57cec5SDimitry Andric   // Erase all the elements in the later stages. Only one iteration should
34370b57cec5SDimitry Andric   // remain in the scheduled list, and it contains all the instructions.
34380b57cec5SDimitry Andric   for (int cycle = getFinalCycle() + 1; cycle <= LastCycle; ++cycle)
34390b57cec5SDimitry Andric     ScheduledInstrs.erase(cycle);
34400b57cec5SDimitry Andric 
34410b57cec5SDimitry Andric   // Change the registers in instruction as specified in the InstrChanges
34420b57cec5SDimitry Andric   // map. We need to use the new registers to create the correct order.
34430eae32dcSDimitry Andric   for (const SUnit &SU : SSD->SUnits)
34440eae32dcSDimitry Andric     SSD->applyInstrChange(SU.getInstr(), *this);
34450b57cec5SDimitry Andric 
34460b57cec5SDimitry Andric   // Reorder the instructions in each cycle to fix and improve the
34470b57cec5SDimitry Andric   // generated code.
34480b57cec5SDimitry Andric   for (int Cycle = getFirstCycle(), E = getFinalCycle(); Cycle <= E; ++Cycle) {
34490b57cec5SDimitry Andric     std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[Cycle];
34507a6dacacSDimitry Andric     cycleInstrs = reorderInstructions(SSD, cycleInstrs);
34510b57cec5SDimitry Andric     SSD->fixupRegisterOverlaps(cycleInstrs);
34520b57cec5SDimitry Andric   }
34530b57cec5SDimitry Andric 
34540b57cec5SDimitry Andric   LLVM_DEBUG(dump(););
34550b57cec5SDimitry Andric }
34560b57cec5SDimitry Andric 
34570b57cec5SDimitry Andric void NodeSet::print(raw_ostream &os) const {
34580b57cec5SDimitry Andric   os << "Num nodes " << size() << " rec " << RecMII << " mov " << MaxMOV
34590b57cec5SDimitry Andric      << " depth " << MaxDepth << " col " << Colocate << "\n";
34600b57cec5SDimitry Andric   for (const auto &I : Nodes)
34610b57cec5SDimitry Andric     os << "   SU(" << I->NodeNum << ") " << *(I->getInstr());
34620b57cec5SDimitry Andric   os << "\n";
34630b57cec5SDimitry Andric }
34640b57cec5SDimitry Andric 
34650b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
34660b57cec5SDimitry Andric /// Print the schedule information to the given output.
34670b57cec5SDimitry Andric void SMSchedule::print(raw_ostream &os) const {
34680b57cec5SDimitry Andric   // Iterate over each cycle.
34690b57cec5SDimitry Andric   for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
34700b57cec5SDimitry Andric     // Iterate over each instruction in the cycle.
34710b57cec5SDimitry Andric     const_sched_iterator cycleInstrs = ScheduledInstrs.find(cycle);
34720b57cec5SDimitry Andric     for (SUnit *CI : cycleInstrs->second) {
34730b57cec5SDimitry Andric       os << "cycle " << cycle << " (" << stageScheduled(CI) << ") ";
34740b57cec5SDimitry Andric       os << "(" << CI->NodeNum << ") ";
34750b57cec5SDimitry Andric       CI->getInstr()->print(os);
34760b57cec5SDimitry Andric       os << "\n";
34770b57cec5SDimitry Andric     }
34780b57cec5SDimitry Andric   }
34790b57cec5SDimitry Andric }
34800b57cec5SDimitry Andric 
34810b57cec5SDimitry Andric /// Utility function used for debugging to print the schedule.
34820b57cec5SDimitry Andric LLVM_DUMP_METHOD void SMSchedule::dump() const { print(dbgs()); }
34830b57cec5SDimitry Andric LLVM_DUMP_METHOD void NodeSet::dump() const { print(dbgs()); }
34840b57cec5SDimitry Andric 
3485bdd1243dSDimitry Andric void ResourceManager::dumpMRT() const {
3486bdd1243dSDimitry Andric   LLVM_DEBUG({
3487bdd1243dSDimitry Andric     if (UseDFA)
3488bdd1243dSDimitry Andric       return;
3489bdd1243dSDimitry Andric     std::stringstream SS;
3490bdd1243dSDimitry Andric     SS << "MRT:\n";
3491bdd1243dSDimitry Andric     SS << std::setw(4) << "Slot";
3492bdd1243dSDimitry Andric     for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I)
3493bdd1243dSDimitry Andric       SS << std::setw(3) << I;
3494bdd1243dSDimitry Andric     SS << std::setw(7) << "#Mops"
3495bdd1243dSDimitry Andric        << "\n";
3496bdd1243dSDimitry Andric     for (int Slot = 0; Slot < InitiationInterval; ++Slot) {
3497bdd1243dSDimitry Andric       SS << std::setw(4) << Slot;
3498bdd1243dSDimitry Andric       for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I)
3499bdd1243dSDimitry Andric         SS << std::setw(3) << MRT[Slot][I];
3500bdd1243dSDimitry Andric       SS << std::setw(7) << NumScheduledMops[Slot] << "\n";
3501bdd1243dSDimitry Andric     }
3502bdd1243dSDimitry Andric     dbgs() << SS.str();
3503bdd1243dSDimitry Andric   });
3504bdd1243dSDimitry Andric }
35050b57cec5SDimitry Andric #endif
35060b57cec5SDimitry Andric 
35070b57cec5SDimitry Andric void ResourceManager::initProcResourceVectors(
35080b57cec5SDimitry Andric     const MCSchedModel &SM, SmallVectorImpl<uint64_t> &Masks) {
35090b57cec5SDimitry Andric   unsigned ProcResourceID = 0;
35100b57cec5SDimitry Andric 
35110b57cec5SDimitry Andric   // We currently limit the resource kinds to 64 and below so that we can use
35120b57cec5SDimitry Andric   // uint64_t for Masks
35130b57cec5SDimitry Andric   assert(SM.getNumProcResourceKinds() < 64 &&
35140b57cec5SDimitry Andric          "Too many kinds of resources, unsupported");
35150b57cec5SDimitry Andric   // Create a unique bitmask for every processor resource unit.
35160b57cec5SDimitry Andric   // Skip resource at index 0, since it always references 'InvalidUnit'.
35170b57cec5SDimitry Andric   Masks.resize(SM.getNumProcResourceKinds());
35180b57cec5SDimitry Andric   for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
35190b57cec5SDimitry Andric     const MCProcResourceDesc &Desc = *SM.getProcResource(I);
35200b57cec5SDimitry Andric     if (Desc.SubUnitsIdxBegin)
35210b57cec5SDimitry Andric       continue;
35220b57cec5SDimitry Andric     Masks[I] = 1ULL << ProcResourceID;
35230b57cec5SDimitry Andric     ProcResourceID++;
35240b57cec5SDimitry Andric   }
35250b57cec5SDimitry Andric   // Create a unique bitmask for every processor resource group.
35260b57cec5SDimitry Andric   for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
35270b57cec5SDimitry Andric     const MCProcResourceDesc &Desc = *SM.getProcResource(I);
35280b57cec5SDimitry Andric     if (!Desc.SubUnitsIdxBegin)
35290b57cec5SDimitry Andric       continue;
35300b57cec5SDimitry Andric     Masks[I] = 1ULL << ProcResourceID;
35310b57cec5SDimitry Andric     for (unsigned U = 0; U < Desc.NumUnits; ++U)
35320b57cec5SDimitry Andric       Masks[I] |= Masks[Desc.SubUnitsIdxBegin[U]];
35330b57cec5SDimitry Andric     ProcResourceID++;
35340b57cec5SDimitry Andric   }
35350b57cec5SDimitry Andric   LLVM_DEBUG({
35360b57cec5SDimitry Andric     if (SwpShowResMask) {
35370b57cec5SDimitry Andric       dbgs() << "ProcResourceDesc:\n";
35380b57cec5SDimitry Andric       for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
35390b57cec5SDimitry Andric         const MCProcResourceDesc *ProcResource = SM.getProcResource(I);
35400b57cec5SDimitry Andric         dbgs() << format(" %16s(%2d): Mask: 0x%08x, NumUnits:%2d\n",
35410b57cec5SDimitry Andric                          ProcResource->Name, I, Masks[I],
35420b57cec5SDimitry Andric                          ProcResource->NumUnits);
35430b57cec5SDimitry Andric       }
35440b57cec5SDimitry Andric       dbgs() << " -----------------\n";
35450b57cec5SDimitry Andric     }
35460b57cec5SDimitry Andric   });
35470b57cec5SDimitry Andric }
35480b57cec5SDimitry Andric 
3549bdd1243dSDimitry Andric bool ResourceManager::canReserveResources(SUnit &SU, int Cycle) {
35500b57cec5SDimitry Andric   LLVM_DEBUG({
35510b57cec5SDimitry Andric     if (SwpDebugResource)
35520b57cec5SDimitry Andric       dbgs() << "canReserveResources:\n";
35530b57cec5SDimitry Andric   });
35540b57cec5SDimitry Andric   if (UseDFA)
3555bdd1243dSDimitry Andric     return DFAResources[positiveModulo(Cycle, InitiationInterval)]
3556bdd1243dSDimitry Andric         ->canReserveResources(&SU.getInstr()->getDesc());
35570b57cec5SDimitry Andric 
3558bdd1243dSDimitry Andric   const MCSchedClassDesc *SCDesc = DAG->getSchedClass(&SU);
35590b57cec5SDimitry Andric   if (!SCDesc->isValid()) {
35600b57cec5SDimitry Andric     LLVM_DEBUG({
35610b57cec5SDimitry Andric       dbgs() << "No valid Schedule Class Desc for schedClass!\n";
3562bdd1243dSDimitry Andric       dbgs() << "isPseudo:" << SU.getInstr()->isPseudo() << "\n";
35630b57cec5SDimitry Andric     });
35640b57cec5SDimitry Andric     return true;
35650b57cec5SDimitry Andric   }
35660b57cec5SDimitry Andric 
3567bdd1243dSDimitry Andric   reserveResources(SCDesc, Cycle);
3568bdd1243dSDimitry Andric   bool Result = !isOverbooked();
3569bdd1243dSDimitry Andric   unreserveResources(SCDesc, Cycle);
3570bdd1243dSDimitry Andric 
3571bdd1243dSDimitry Andric   LLVM_DEBUG(if (SwpDebugResource) dbgs() << "return " << Result << "\n\n";);
3572bdd1243dSDimitry Andric   return Result;
35730b57cec5SDimitry Andric }
35740b57cec5SDimitry Andric 
3575bdd1243dSDimitry Andric void ResourceManager::reserveResources(SUnit &SU, int Cycle) {
35760b57cec5SDimitry Andric   LLVM_DEBUG({
35770b57cec5SDimitry Andric     if (SwpDebugResource)
35780b57cec5SDimitry Andric       dbgs() << "reserveResources:\n";
35790b57cec5SDimitry Andric   });
35800b57cec5SDimitry Andric   if (UseDFA)
3581bdd1243dSDimitry Andric     return DFAResources[positiveModulo(Cycle, InitiationInterval)]
3582bdd1243dSDimitry Andric         ->reserveResources(&SU.getInstr()->getDesc());
35830b57cec5SDimitry Andric 
3584bdd1243dSDimitry Andric   const MCSchedClassDesc *SCDesc = DAG->getSchedClass(&SU);
35850b57cec5SDimitry Andric   if (!SCDesc->isValid()) {
35860b57cec5SDimitry Andric     LLVM_DEBUG({
35870b57cec5SDimitry Andric       dbgs() << "No valid Schedule Class Desc for schedClass!\n";
3588bdd1243dSDimitry Andric       dbgs() << "isPseudo:" << SU.getInstr()->isPseudo() << "\n";
35890b57cec5SDimitry Andric     });
35900b57cec5SDimitry Andric     return;
35910b57cec5SDimitry Andric   }
3592bdd1243dSDimitry Andric 
3593bdd1243dSDimitry Andric   reserveResources(SCDesc, Cycle);
3594bdd1243dSDimitry Andric 
3595bdd1243dSDimitry Andric   LLVM_DEBUG({
3596bdd1243dSDimitry Andric     if (SwpDebugResource) {
3597bdd1243dSDimitry Andric       dumpMRT();
3598bdd1243dSDimitry Andric       dbgs() << "reserveResources: done!\n\n";
3599bdd1243dSDimitry Andric     }
3600bdd1243dSDimitry Andric   });
3601bdd1243dSDimitry Andric }
3602bdd1243dSDimitry Andric 
3603bdd1243dSDimitry Andric void ResourceManager::reserveResources(const MCSchedClassDesc *SCDesc,
3604bdd1243dSDimitry Andric                                        int Cycle) {
3605bdd1243dSDimitry Andric   assert(!UseDFA);
3606bdd1243dSDimitry Andric   for (const MCWriteProcResEntry &PRE : make_range(
3607bdd1243dSDimitry Andric            STI->getWriteProcResBegin(SCDesc), STI->getWriteProcResEnd(SCDesc)))
36085f757f3fSDimitry Andric     for (int C = Cycle; C < Cycle + PRE.ReleaseAtCycle; ++C)
3609bdd1243dSDimitry Andric       ++MRT[positiveModulo(C, InitiationInterval)][PRE.ProcResourceIdx];
3610bdd1243dSDimitry Andric 
3611bdd1243dSDimitry Andric   for (int C = Cycle; C < Cycle + SCDesc->NumMicroOps; ++C)
3612bdd1243dSDimitry Andric     ++NumScheduledMops[positiveModulo(C, InitiationInterval)];
3613bdd1243dSDimitry Andric }
3614bdd1243dSDimitry Andric 
3615bdd1243dSDimitry Andric void ResourceManager::unreserveResources(const MCSchedClassDesc *SCDesc,
3616bdd1243dSDimitry Andric                                          int Cycle) {
3617bdd1243dSDimitry Andric   assert(!UseDFA);
3618bdd1243dSDimitry Andric   for (const MCWriteProcResEntry &PRE : make_range(
3619bdd1243dSDimitry Andric            STI->getWriteProcResBegin(SCDesc), STI->getWriteProcResEnd(SCDesc)))
36205f757f3fSDimitry Andric     for (int C = Cycle; C < Cycle + PRE.ReleaseAtCycle; ++C)
3621bdd1243dSDimitry Andric       --MRT[positiveModulo(C, InitiationInterval)][PRE.ProcResourceIdx];
3622bdd1243dSDimitry Andric 
3623bdd1243dSDimitry Andric   for (int C = Cycle; C < Cycle + SCDesc->NumMicroOps; ++C)
3624bdd1243dSDimitry Andric     --NumScheduledMops[positiveModulo(C, InitiationInterval)];
3625bdd1243dSDimitry Andric }
3626bdd1243dSDimitry Andric 
3627bdd1243dSDimitry Andric bool ResourceManager::isOverbooked() const {
3628bdd1243dSDimitry Andric   assert(!UseDFA);
3629bdd1243dSDimitry Andric   for (int Slot = 0; Slot < InitiationInterval; ++Slot) {
3630bdd1243dSDimitry Andric     for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
3631bdd1243dSDimitry Andric       const MCProcResourceDesc *Desc = SM.getProcResource(I);
3632bdd1243dSDimitry Andric       if (MRT[Slot][I] > Desc->NumUnits)
3633bdd1243dSDimitry Andric         return true;
3634bdd1243dSDimitry Andric     }
3635bdd1243dSDimitry Andric     if (NumScheduledMops[Slot] > IssueWidth)
3636bdd1243dSDimitry Andric       return true;
3637bdd1243dSDimitry Andric   }
3638bdd1243dSDimitry Andric   return false;
3639bdd1243dSDimitry Andric }
3640bdd1243dSDimitry Andric 
3641bdd1243dSDimitry Andric int ResourceManager::calculateResMIIDFA() const {
3642bdd1243dSDimitry Andric   assert(UseDFA);
3643bdd1243dSDimitry Andric 
3644bdd1243dSDimitry Andric   // Sort the instructions by the number of available choices for scheduling,
3645bdd1243dSDimitry Andric   // least to most. Use the number of critical resources as the tie breaker.
3646bdd1243dSDimitry Andric   FuncUnitSorter FUS = FuncUnitSorter(*ST);
3647bdd1243dSDimitry Andric   for (SUnit &SU : DAG->SUnits)
3648bdd1243dSDimitry Andric     FUS.calcCriticalResources(*SU.getInstr());
3649bdd1243dSDimitry Andric   PriorityQueue<MachineInstr *, std::vector<MachineInstr *>, FuncUnitSorter>
3650bdd1243dSDimitry Andric       FuncUnitOrder(FUS);
3651bdd1243dSDimitry Andric 
3652bdd1243dSDimitry Andric   for (SUnit &SU : DAG->SUnits)
3653bdd1243dSDimitry Andric     FuncUnitOrder.push(SU.getInstr());
3654bdd1243dSDimitry Andric 
3655bdd1243dSDimitry Andric   SmallVector<std::unique_ptr<DFAPacketizer>, 8> Resources;
3656bdd1243dSDimitry Andric   Resources.push_back(
3657bdd1243dSDimitry Andric       std::unique_ptr<DFAPacketizer>(TII->CreateTargetScheduleState(*ST)));
3658bdd1243dSDimitry Andric 
3659bdd1243dSDimitry Andric   while (!FuncUnitOrder.empty()) {
3660bdd1243dSDimitry Andric     MachineInstr *MI = FuncUnitOrder.top();
3661bdd1243dSDimitry Andric     FuncUnitOrder.pop();
3662bdd1243dSDimitry Andric     if (TII->isZeroCost(MI->getOpcode()))
3663bdd1243dSDimitry Andric       continue;
3664bdd1243dSDimitry Andric 
3665bdd1243dSDimitry Andric     // Attempt to reserve the instruction in an existing DFA. At least one
3666bdd1243dSDimitry Andric     // DFA is needed for each cycle.
3667bdd1243dSDimitry Andric     unsigned NumCycles = DAG->getSUnit(MI)->Latency;
3668bdd1243dSDimitry Andric     unsigned ReservedCycles = 0;
3669bdd1243dSDimitry Andric     auto *RI = Resources.begin();
3670bdd1243dSDimitry Andric     auto *RE = Resources.end();
3671bdd1243dSDimitry Andric     LLVM_DEBUG({
3672bdd1243dSDimitry Andric       dbgs() << "Trying to reserve resource for " << NumCycles
3673bdd1243dSDimitry Andric              << " cycles for \n";
3674bdd1243dSDimitry Andric       MI->dump();
3675bdd1243dSDimitry Andric     });
3676bdd1243dSDimitry Andric     for (unsigned C = 0; C < NumCycles; ++C)
3677bdd1243dSDimitry Andric       while (RI != RE) {
3678bdd1243dSDimitry Andric         if ((*RI)->canReserveResources(*MI)) {
3679bdd1243dSDimitry Andric           (*RI)->reserveResources(*MI);
3680bdd1243dSDimitry Andric           ++ReservedCycles;
3681bdd1243dSDimitry Andric           break;
3682bdd1243dSDimitry Andric         }
3683bdd1243dSDimitry Andric         RI++;
3684bdd1243dSDimitry Andric       }
3685bdd1243dSDimitry Andric     LLVM_DEBUG(dbgs() << "ReservedCycles:" << ReservedCycles
3686bdd1243dSDimitry Andric                       << ", NumCycles:" << NumCycles << "\n");
3687bdd1243dSDimitry Andric     // Add new DFAs, if needed, to reserve resources.
3688bdd1243dSDimitry Andric     for (unsigned C = ReservedCycles; C < NumCycles; ++C) {
3689bdd1243dSDimitry Andric       LLVM_DEBUG(if (SwpDebugResource) dbgs()
3690bdd1243dSDimitry Andric                  << "NewResource created to reserve resources"
3691bdd1243dSDimitry Andric                  << "\n");
3692bdd1243dSDimitry Andric       auto *NewResource = TII->CreateTargetScheduleState(*ST);
3693bdd1243dSDimitry Andric       assert(NewResource->canReserveResources(*MI) && "Reserve error.");
3694bdd1243dSDimitry Andric       NewResource->reserveResources(*MI);
3695bdd1243dSDimitry Andric       Resources.push_back(std::unique_ptr<DFAPacketizer>(NewResource));
3696bdd1243dSDimitry Andric     }
3697bdd1243dSDimitry Andric   }
3698bdd1243dSDimitry Andric 
3699bdd1243dSDimitry Andric   int Resmii = Resources.size();
3700bdd1243dSDimitry Andric   LLVM_DEBUG(dbgs() << "Return Res MII:" << Resmii << "\n");
3701bdd1243dSDimitry Andric   return Resmii;
3702bdd1243dSDimitry Andric }
3703bdd1243dSDimitry Andric 
3704bdd1243dSDimitry Andric int ResourceManager::calculateResMII() const {
3705bdd1243dSDimitry Andric   if (UseDFA)
3706bdd1243dSDimitry Andric     return calculateResMIIDFA();
3707bdd1243dSDimitry Andric 
3708bdd1243dSDimitry Andric   // Count each resource consumption and divide it by the number of units.
3709bdd1243dSDimitry Andric   // ResMII is the max value among them.
3710bdd1243dSDimitry Andric 
3711bdd1243dSDimitry Andric   int NumMops = 0;
3712bdd1243dSDimitry Andric   SmallVector<uint64_t> ResourceCount(SM.getNumProcResourceKinds());
3713bdd1243dSDimitry Andric   for (SUnit &SU : DAG->SUnits) {
3714bdd1243dSDimitry Andric     if (TII->isZeroCost(SU.getInstr()->getOpcode()))
3715bdd1243dSDimitry Andric       continue;
3716bdd1243dSDimitry Andric 
3717bdd1243dSDimitry Andric     const MCSchedClassDesc *SCDesc = DAG->getSchedClass(&SU);
3718bdd1243dSDimitry Andric     if (!SCDesc->isValid())
3719bdd1243dSDimitry Andric       continue;
3720bdd1243dSDimitry Andric 
3721bdd1243dSDimitry Andric     LLVM_DEBUG({
3722bdd1243dSDimitry Andric       if (SwpDebugResource) {
3723bdd1243dSDimitry Andric         DAG->dumpNode(SU);
3724bdd1243dSDimitry Andric         dbgs() << "  #Mops: " << SCDesc->NumMicroOps << "\n"
3725bdd1243dSDimitry Andric                << "  WriteProcRes: ";
3726bdd1243dSDimitry Andric       }
3727bdd1243dSDimitry Andric     });
3728bdd1243dSDimitry Andric     NumMops += SCDesc->NumMicroOps;
37290b57cec5SDimitry Andric     for (const MCWriteProcResEntry &PRE :
37300b57cec5SDimitry Andric          make_range(STI->getWriteProcResBegin(SCDesc),
37310b57cec5SDimitry Andric                     STI->getWriteProcResEnd(SCDesc))) {
37320b57cec5SDimitry Andric       LLVM_DEBUG({
37330b57cec5SDimitry Andric         if (SwpDebugResource) {
3734bdd1243dSDimitry Andric           const MCProcResourceDesc *Desc =
37350b57cec5SDimitry Andric               SM.getProcResource(PRE.ProcResourceIdx);
37365f757f3fSDimitry Andric           dbgs() << Desc->Name << ": " << PRE.ReleaseAtCycle << ", ";
37370b57cec5SDimitry Andric         }
37380b57cec5SDimitry Andric       });
37395f757f3fSDimitry Andric       ResourceCount[PRE.ProcResourceIdx] += PRE.ReleaseAtCycle;
37400b57cec5SDimitry Andric     }
3741bdd1243dSDimitry Andric     LLVM_DEBUG(if (SwpDebugResource) dbgs() << "\n");
3742bdd1243dSDimitry Andric   }
3743bdd1243dSDimitry Andric 
3744bdd1243dSDimitry Andric   int Result = (NumMops + IssueWidth - 1) / IssueWidth;
37450b57cec5SDimitry Andric   LLVM_DEBUG({
37460b57cec5SDimitry Andric     if (SwpDebugResource)
3747bdd1243dSDimitry Andric       dbgs() << "#Mops: " << NumMops << ", "
3748bdd1243dSDimitry Andric              << "IssueWidth: " << IssueWidth << ", "
3749bdd1243dSDimitry Andric              << "Cycles: " << Result << "\n";
37500b57cec5SDimitry Andric   });
3751bdd1243dSDimitry Andric 
3752bdd1243dSDimitry Andric   LLVM_DEBUG({
3753bdd1243dSDimitry Andric     if (SwpDebugResource) {
3754bdd1243dSDimitry Andric       std::stringstream SS;
3755bdd1243dSDimitry Andric       SS << std::setw(2) << "ID" << std::setw(16) << "Name" << std::setw(10)
3756bdd1243dSDimitry Andric          << "Units" << std::setw(10) << "Consumed" << std::setw(10) << "Cycles"
3757bdd1243dSDimitry Andric          << "\n";
3758bdd1243dSDimitry Andric       dbgs() << SS.str();
3759bdd1243dSDimitry Andric     }
3760bdd1243dSDimitry Andric   });
3761bdd1243dSDimitry Andric   for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
3762bdd1243dSDimitry Andric     const MCProcResourceDesc *Desc = SM.getProcResource(I);
3763bdd1243dSDimitry Andric     int Cycles = (ResourceCount[I] + Desc->NumUnits - 1) / Desc->NumUnits;
3764bdd1243dSDimitry Andric     LLVM_DEBUG({
3765bdd1243dSDimitry Andric       if (SwpDebugResource) {
3766bdd1243dSDimitry Andric         std::stringstream SS;
3767bdd1243dSDimitry Andric         SS << std::setw(2) << I << std::setw(16) << Desc->Name << std::setw(10)
3768bdd1243dSDimitry Andric            << Desc->NumUnits << std::setw(10) << ResourceCount[I]
3769bdd1243dSDimitry Andric            << std::setw(10) << Cycles << "\n";
3770bdd1243dSDimitry Andric         dbgs() << SS.str();
3771bdd1243dSDimitry Andric       }
3772bdd1243dSDimitry Andric     });
3773bdd1243dSDimitry Andric     if (Cycles > Result)
3774bdd1243dSDimitry Andric       Result = Cycles;
3775bdd1243dSDimitry Andric   }
3776bdd1243dSDimitry Andric   return Result;
37770b57cec5SDimitry Andric }
37780b57cec5SDimitry Andric 
3779bdd1243dSDimitry Andric void ResourceManager::init(int II) {
3780bdd1243dSDimitry Andric   InitiationInterval = II;
3781bdd1243dSDimitry Andric   DFAResources.clear();
3782bdd1243dSDimitry Andric   DFAResources.resize(II);
3783bdd1243dSDimitry Andric   for (auto &I : DFAResources)
3784bdd1243dSDimitry Andric     I.reset(ST->getInstrInfo()->CreateTargetScheduleState(*ST));
3785bdd1243dSDimitry Andric   MRT.clear();
3786bdd1243dSDimitry Andric   MRT.resize(II, SmallVector<uint64_t>(SM.getNumProcResourceKinds()));
3787bdd1243dSDimitry Andric   NumScheduledMops.clear();
3788bdd1243dSDimitry Andric   NumScheduledMops.resize(II);
37890b57cec5SDimitry Andric }
3790