MachinePipeliner.h 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. //===- MachinePipeliner.h - Machine Software Pipeliner Pass -------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // An implementation of the Swing Modulo Scheduling (SMS) software pipeliner.
  10. //
  11. // Software pipelining (SWP) is an instruction scheduling technique for loops
  12. // that overlap loop iterations and exploits ILP via a compiler transformation.
  13. //
  14. // Swing Modulo Scheduling is an implementation of software pipelining
  15. // that generates schedules that are near optimal in terms of initiation
  16. // interval, register requirements, and stage count. See the papers:
  17. //
  18. // "Swing Modulo Scheduling: A Lifetime-Sensitive Approach", by J. Llosa,
  19. // A. Gonzalez, E. Ayguade, and M. Valero. In PACT '96 Proceedings of the 1996
  20. // Conference on Parallel Architectures and Compilation Techiniques.
  21. //
  22. // "Lifetime-Sensitive Modulo Scheduling in a Production Environment", by J.
  23. // Llosa, E. Ayguade, A. Gonzalez, M. Valero, and J. Eckhardt. In IEEE
  24. // Transactions on Computers, Vol. 50, No. 3, 2001.
  25. //
  26. // "An Implementation of Swing Modulo Scheduling With Extensions for
  27. // Superblocks", by T. Lattner, Master's Thesis, University of Illinois at
  28. // Urbana-Champaign, 2005.
  29. //
  30. //
  31. // The SMS algorithm consists of three main steps after computing the minimal
  32. // initiation interval (MII).
  33. // 1) Analyze the dependence graph and compute information about each
  34. // instruction in the graph.
  35. // 2) Order the nodes (instructions) by priority based upon the heuristics
  36. // described in the algorithm.
  37. // 3) Attempt to schedule the nodes in the specified order using the MII.
  38. //
  39. //===----------------------------------------------------------------------===//
  40. #ifndef LLVM_CODEGEN_MACHINEPIPELINER_H
  41. #define LLVM_CODEGEN_MACHINEPIPELINER_H
  42. #include "llvm/CodeGen/MachineDominators.h"
  43. #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
  44. #include "llvm/CodeGen/RegisterClassInfo.h"
  45. #include "llvm/CodeGen/ScheduleDAGInstrs.h"
  46. #include "llvm/CodeGen/TargetInstrInfo.h"
  47. #include "llvm/InitializePasses.h"
  48. namespace llvm {
  49. class AAResults;
  50. class NodeSet;
  51. class SMSchedule;
  52. extern cl::opt<bool> SwpEnableCopyToPhi;
  53. /// The main class in the implementation of the target independent
  54. /// software pipeliner pass.
  55. class MachinePipeliner : public MachineFunctionPass {
  56. public:
  57. MachineFunction *MF = nullptr;
  58. MachineOptimizationRemarkEmitter *ORE = nullptr;
  59. const MachineLoopInfo *MLI = nullptr;
  60. const MachineDominatorTree *MDT = nullptr;
  61. const InstrItineraryData *InstrItins;
  62. const TargetInstrInfo *TII = nullptr;
  63. RegisterClassInfo RegClassInfo;
  64. bool disabledByPragma = false;
  65. unsigned II_setByPragma = 0;
  66. #ifndef NDEBUG
  67. static int NumTries;
  68. #endif
  69. /// Cache the target analysis information about the loop.
  70. struct LoopInfo {
  71. MachineBasicBlock *TBB = nullptr;
  72. MachineBasicBlock *FBB = nullptr;
  73. SmallVector<MachineOperand, 4> BrCond;
  74. MachineInstr *LoopInductionVar = nullptr;
  75. MachineInstr *LoopCompare = nullptr;
  76. };
  77. LoopInfo LI;
  78. static char ID;
  79. MachinePipeliner() : MachineFunctionPass(ID) {
  80. initializeMachinePipelinerPass(*PassRegistry::getPassRegistry());
  81. }
  82. bool runOnMachineFunction(MachineFunction &MF) override;
  83. void getAnalysisUsage(AnalysisUsage &AU) const override;
  84. private:
  85. void preprocessPhiNodes(MachineBasicBlock &B);
  86. bool canPipelineLoop(MachineLoop &L);
  87. bool scheduleLoop(MachineLoop &L);
  88. bool swingModuloScheduler(MachineLoop &L);
  89. void setPragmaPipelineOptions(MachineLoop &L);
  90. };
  91. /// This class builds the dependence graph for the instructions in a loop,
  92. /// and attempts to schedule the instructions using the SMS algorithm.
  93. class SwingSchedulerDAG : public ScheduleDAGInstrs {
  94. MachinePipeliner &Pass;
  95. /// The minimum initiation interval between iterations for this schedule.
  96. unsigned MII = 0;
  97. /// The maximum initiation interval between iterations for this schedule.
  98. unsigned MAX_II = 0;
  99. /// Set to true if a valid pipelined schedule is found for the loop.
  100. bool Scheduled = false;
  101. MachineLoop &Loop;
  102. LiveIntervals &LIS;
  103. const RegisterClassInfo &RegClassInfo;
  104. unsigned II_setByPragma = 0;
  105. /// A toplogical ordering of the SUnits, which is needed for changing
  106. /// dependences and iterating over the SUnits.
  107. ScheduleDAGTopologicalSort Topo;
  108. struct NodeInfo {
  109. int ASAP = 0;
  110. int ALAP = 0;
  111. int ZeroLatencyDepth = 0;
  112. int ZeroLatencyHeight = 0;
  113. NodeInfo() = default;
  114. };
  115. /// Computed properties for each node in the graph.
  116. std::vector<NodeInfo> ScheduleInfo;
  117. enum OrderKind { BottomUp = 0, TopDown = 1 };
  118. /// Computed node ordering for scheduling.
  119. SetVector<SUnit *> NodeOrder;
  120. using NodeSetType = SmallVector<NodeSet, 8>;
  121. using ValueMapTy = DenseMap<unsigned, unsigned>;
  122. using MBBVectorTy = SmallVectorImpl<MachineBasicBlock *>;
  123. using InstrMapTy = DenseMap<MachineInstr *, MachineInstr *>;
  124. /// Instructions to change when emitting the final schedule.
  125. DenseMap<SUnit *, std::pair<unsigned, int64_t>> InstrChanges;
  126. /// We may create a new instruction, so remember it because it
  127. /// must be deleted when the pass is finished.
  128. DenseMap<MachineInstr*, MachineInstr *> NewMIs;
  129. /// Ordered list of DAG postprocessing steps.
  130. std::vector<std::unique_ptr<ScheduleDAGMutation>> Mutations;
  131. /// Helper class to implement Johnson's circuit finding algorithm.
  132. class Circuits {
  133. std::vector<SUnit> &SUnits;
  134. SetVector<SUnit *> Stack;
  135. BitVector Blocked;
  136. SmallVector<SmallPtrSet<SUnit *, 4>, 10> B;
  137. SmallVector<SmallVector<int, 4>, 16> AdjK;
  138. // Node to Index from ScheduleDAGTopologicalSort
  139. std::vector<int> *Node2Idx;
  140. unsigned NumPaths;
  141. static unsigned MaxPaths;
  142. public:
  143. Circuits(std::vector<SUnit> &SUs, ScheduleDAGTopologicalSort &Topo)
  144. : SUnits(SUs), Blocked(SUs.size()), B(SUs.size()), AdjK(SUs.size()) {
  145. Node2Idx = new std::vector<int>(SUs.size());
  146. unsigned Idx = 0;
  147. for (const auto &NodeNum : Topo)
  148. Node2Idx->at(NodeNum) = Idx++;
  149. }
  150. ~Circuits() { delete Node2Idx; }
  151. /// Reset the data structures used in the circuit algorithm.
  152. void reset() {
  153. Stack.clear();
  154. Blocked.reset();
  155. B.assign(SUnits.size(), SmallPtrSet<SUnit *, 4>());
  156. NumPaths = 0;
  157. }
  158. void createAdjacencyStructure(SwingSchedulerDAG *DAG);
  159. bool circuit(int V, int S, NodeSetType &NodeSets, bool HasBackedge = false);
  160. void unblock(int U);
  161. };
  162. struct CopyToPhiMutation : public ScheduleDAGMutation {
  163. void apply(ScheduleDAGInstrs *DAG) override;
  164. };
  165. public:
  166. SwingSchedulerDAG(MachinePipeliner &P, MachineLoop &L, LiveIntervals &lis,
  167. const RegisterClassInfo &rci, unsigned II)
  168. : ScheduleDAGInstrs(*P.MF, P.MLI, false), Pass(P), Loop(L), LIS(lis),
  169. RegClassInfo(rci), II_setByPragma(II), Topo(SUnits, &ExitSU) {
  170. P.MF->getSubtarget().getSMSMutations(Mutations);
  171. if (SwpEnableCopyToPhi)
  172. Mutations.push_back(std::make_unique<CopyToPhiMutation>());
  173. }
  174. void schedule() override;
  175. void finishBlock() override;
  176. /// Return true if the loop kernel has been scheduled.
  177. bool hasNewSchedule() { return Scheduled; }
  178. /// Return the earliest time an instruction may be scheduled.
  179. int getASAP(SUnit *Node) { return ScheduleInfo[Node->NodeNum].ASAP; }
  180. /// Return the latest time an instruction my be scheduled.
  181. int getALAP(SUnit *Node) { return ScheduleInfo[Node->NodeNum].ALAP; }
  182. /// The mobility function, which the number of slots in which
  183. /// an instruction may be scheduled.
  184. int getMOV(SUnit *Node) { return getALAP(Node) - getASAP(Node); }
  185. /// The depth, in the dependence graph, for a node.
  186. unsigned getDepth(SUnit *Node) { return Node->getDepth(); }
  187. /// The maximum unweighted length of a path from an arbitrary node to the
  188. /// given node in which each edge has latency 0
  189. int getZeroLatencyDepth(SUnit *Node) {
  190. return ScheduleInfo[Node->NodeNum].ZeroLatencyDepth;
  191. }
  192. /// The height, in the dependence graph, for a node.
  193. unsigned getHeight(SUnit *Node) { return Node->getHeight(); }
  194. /// The maximum unweighted length of a path from the given node to an
  195. /// arbitrary node in which each edge has latency 0
  196. int getZeroLatencyHeight(SUnit *Node) {
  197. return ScheduleInfo[Node->NodeNum].ZeroLatencyHeight;
  198. }
  199. /// Return true if the dependence is a back-edge in the data dependence graph.
  200. /// Since the DAG doesn't contain cycles, we represent a cycle in the graph
  201. /// using an anti dependence from a Phi to an instruction.
  202. bool isBackedge(SUnit *Source, const SDep &Dep) {
  203. if (Dep.getKind() != SDep::Anti)
  204. return false;
  205. return Source->getInstr()->isPHI() || Dep.getSUnit()->getInstr()->isPHI();
  206. }
  207. bool isLoopCarriedDep(SUnit *Source, const SDep &Dep, bool isSucc = true);
  208. /// The distance function, which indicates that operation V of iteration I
  209. /// depends on operations U of iteration I-distance.
  210. unsigned getDistance(SUnit *U, SUnit *V, const SDep &Dep) {
  211. // Instructions that feed a Phi have a distance of 1. Computing larger
  212. // values for arrays requires data dependence information.
  213. if (V->getInstr()->isPHI() && Dep.getKind() == SDep::Anti)
  214. return 1;
  215. return 0;
  216. }
  217. void applyInstrChange(MachineInstr *MI, SMSchedule &Schedule);
  218. void fixupRegisterOverlaps(std::deque<SUnit *> &Instrs);
  219. /// Return the new base register that was stored away for the changed
  220. /// instruction.
  221. unsigned getInstrBaseReg(SUnit *SU) {
  222. DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
  223. InstrChanges.find(SU);
  224. if (It != InstrChanges.end())
  225. return It->second.first;
  226. return 0;
  227. }
  228. void addMutation(std::unique_ptr<ScheduleDAGMutation> Mutation) {
  229. Mutations.push_back(std::move(Mutation));
  230. }
  231. static bool classof(const ScheduleDAGInstrs *DAG) { return true; }
  232. private:
  233. void addLoopCarriedDependences(AAResults *AA);
  234. void updatePhiDependences();
  235. void changeDependences();
  236. unsigned calculateResMII();
  237. unsigned calculateRecMII(NodeSetType &RecNodeSets);
  238. void findCircuits(NodeSetType &NodeSets);
  239. void fuseRecs(NodeSetType &NodeSets);
  240. void removeDuplicateNodes(NodeSetType &NodeSets);
  241. void computeNodeFunctions(NodeSetType &NodeSets);
  242. void registerPressureFilter(NodeSetType &NodeSets);
  243. void colocateNodeSets(NodeSetType &NodeSets);
  244. void checkNodeSets(NodeSetType &NodeSets);
  245. void groupRemainingNodes(NodeSetType &NodeSets);
  246. void addConnectedNodes(SUnit *SU, NodeSet &NewSet,
  247. SetVector<SUnit *> &NodesAdded);
  248. void computeNodeOrder(NodeSetType &NodeSets);
  249. void checkValidNodeOrder(const NodeSetType &Circuits) const;
  250. bool schedulePipeline(SMSchedule &Schedule);
  251. bool computeDelta(MachineInstr &MI, unsigned &Delta);
  252. MachineInstr *findDefInLoop(Register Reg);
  253. bool canUseLastOffsetValue(MachineInstr *MI, unsigned &BasePos,
  254. unsigned &OffsetPos, unsigned &NewBase,
  255. int64_t &NewOffset);
  256. void postprocessDAG();
  257. /// Set the Minimum Initiation Interval for this schedule attempt.
  258. void setMII(unsigned ResMII, unsigned RecMII);
  259. /// Set the Maximum Initiation Interval for this schedule attempt.
  260. void setMAX_II();
  261. };
  262. /// A NodeSet contains a set of SUnit DAG nodes with additional information
  263. /// that assigns a priority to the set.
  264. class NodeSet {
  265. SetVector<SUnit *> Nodes;
  266. bool HasRecurrence = false;
  267. unsigned RecMII = 0;
  268. int MaxMOV = 0;
  269. unsigned MaxDepth = 0;
  270. unsigned Colocate = 0;
  271. SUnit *ExceedPressure = nullptr;
  272. unsigned Latency = 0;
  273. public:
  274. using iterator = SetVector<SUnit *>::const_iterator;
  275. NodeSet() = default;
  276. NodeSet(iterator S, iterator E) : Nodes(S, E), HasRecurrence(true) {
  277. Latency = 0;
  278. for (unsigned i = 0, e = Nodes.size(); i < e; ++i) {
  279. DenseMap<SUnit *, unsigned> SuccSUnitLatency;
  280. for (const SDep &Succ : Nodes[i]->Succs) {
  281. auto SuccSUnit = Succ.getSUnit();
  282. if (!Nodes.count(SuccSUnit))
  283. continue;
  284. unsigned CurLatency = Succ.getLatency();
  285. unsigned MaxLatency = 0;
  286. if (SuccSUnitLatency.count(SuccSUnit))
  287. MaxLatency = SuccSUnitLatency[SuccSUnit];
  288. if (CurLatency > MaxLatency)
  289. SuccSUnitLatency[SuccSUnit] = CurLatency;
  290. }
  291. for (auto SUnitLatency : SuccSUnitLatency)
  292. Latency += SUnitLatency.second;
  293. }
  294. }
  295. bool insert(SUnit *SU) { return Nodes.insert(SU); }
  296. void insert(iterator S, iterator E) { Nodes.insert(S, E); }
  297. template <typename UnaryPredicate> bool remove_if(UnaryPredicate P) {
  298. return Nodes.remove_if(P);
  299. }
  300. unsigned count(SUnit *SU) const { return Nodes.count(SU); }
  301. bool hasRecurrence() { return HasRecurrence; };
  302. unsigned size() const { return Nodes.size(); }
  303. bool empty() const { return Nodes.empty(); }
  304. SUnit *getNode(unsigned i) const { return Nodes[i]; };
  305. void setRecMII(unsigned mii) { RecMII = mii; };
  306. void setColocate(unsigned c) { Colocate = c; };
  307. void setExceedPressure(SUnit *SU) { ExceedPressure = SU; }
  308. bool isExceedSU(SUnit *SU) { return ExceedPressure == SU; }
  309. int compareRecMII(NodeSet &RHS) { return RecMII - RHS.RecMII; }
  310. int getRecMII() { return RecMII; }
  311. /// Summarize node functions for the entire node set.
  312. void computeNodeSetInfo(SwingSchedulerDAG *SSD) {
  313. for (SUnit *SU : *this) {
  314. MaxMOV = std::max(MaxMOV, SSD->getMOV(SU));
  315. MaxDepth = std::max(MaxDepth, SSD->getDepth(SU));
  316. }
  317. }
  318. unsigned getLatency() { return Latency; }
  319. unsigned getMaxDepth() { return MaxDepth; }
  320. void clear() {
  321. Nodes.clear();
  322. RecMII = 0;
  323. HasRecurrence = false;
  324. MaxMOV = 0;
  325. MaxDepth = 0;
  326. Colocate = 0;
  327. ExceedPressure = nullptr;
  328. }
  329. operator SetVector<SUnit *> &() { return Nodes; }
  330. /// Sort the node sets by importance. First, rank them by recurrence MII,
  331. /// then by mobility (least mobile done first), and finally by depth.
  332. /// Each node set may contain a colocate value which is used as the first
  333. /// tie breaker, if it's set.
  334. bool operator>(const NodeSet &RHS) const {
  335. if (RecMII == RHS.RecMII) {
  336. if (Colocate != 0 && RHS.Colocate != 0 && Colocate != RHS.Colocate)
  337. return Colocate < RHS.Colocate;
  338. if (MaxMOV == RHS.MaxMOV)
  339. return MaxDepth > RHS.MaxDepth;
  340. return MaxMOV < RHS.MaxMOV;
  341. }
  342. return RecMII > RHS.RecMII;
  343. }
  344. bool operator==(const NodeSet &RHS) const {
  345. return RecMII == RHS.RecMII && MaxMOV == RHS.MaxMOV &&
  346. MaxDepth == RHS.MaxDepth;
  347. }
  348. bool operator!=(const NodeSet &RHS) const { return !operator==(RHS); }
  349. iterator begin() { return Nodes.begin(); }
  350. iterator end() { return Nodes.end(); }
  351. void print(raw_ostream &os) const;
  352. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  353. LLVM_DUMP_METHOD void dump() const;
  354. #endif
  355. };
  356. // 16 was selected based on the number of ProcResource kinds for all
  357. // existing Subtargets, so that SmallVector don't need to resize too often.
  358. static const int DefaultProcResSize = 16;
  359. class ResourceManager {
  360. private:
  361. const MCSubtargetInfo *STI;
  362. const MCSchedModel &SM;
  363. const bool UseDFA;
  364. std::unique_ptr<DFAPacketizer> DFAResources;
  365. /// Each processor resource is associated with a so-called processor resource
  366. /// mask. This vector allows to correlate processor resource IDs with
  367. /// processor resource masks. There is exactly one element per each processor
  368. /// resource declared by the scheduling model.
  369. llvm::SmallVector<uint64_t, DefaultProcResSize> ProcResourceMasks;
  370. llvm::SmallVector<uint64_t, DefaultProcResSize> ProcResourceCount;
  371. public:
  372. ResourceManager(const TargetSubtargetInfo *ST)
  373. : STI(ST), SM(ST->getSchedModel()), UseDFA(ST->useDFAforSMS()),
  374. ProcResourceMasks(SM.getNumProcResourceKinds(), 0),
  375. ProcResourceCount(SM.getNumProcResourceKinds(), 0) {
  376. if (UseDFA)
  377. DFAResources.reset(ST->getInstrInfo()->CreateTargetScheduleState(*ST));
  378. initProcResourceVectors(SM, ProcResourceMasks);
  379. }
  380. void initProcResourceVectors(const MCSchedModel &SM,
  381. SmallVectorImpl<uint64_t> &Masks);
  382. /// Check if the resources occupied by a MCInstrDesc are available in
  383. /// the current state.
  384. bool canReserveResources(const MCInstrDesc *MID) const;
  385. /// Reserve the resources occupied by a MCInstrDesc and change the current
  386. /// state to reflect that change.
  387. void reserveResources(const MCInstrDesc *MID);
  388. /// Check if the resources occupied by a machine instruction are available
  389. /// in the current state.
  390. bool canReserveResources(const MachineInstr &MI) const;
  391. /// Reserve the resources occupied by a machine instruction and change the
  392. /// current state to reflect that change.
  393. void reserveResources(const MachineInstr &MI);
  394. /// Reset the state
  395. void clearResources();
  396. };
  397. /// This class represents the scheduled code. The main data structure is a
  398. /// map from scheduled cycle to instructions. During scheduling, the
  399. /// data structure explicitly represents all stages/iterations. When
  400. /// the algorithm finshes, the schedule is collapsed into a single stage,
  401. /// which represents instructions from different loop iterations.
  402. ///
  403. /// The SMS algorithm allows negative values for cycles, so the first cycle
  404. /// in the schedule is the smallest cycle value.
  405. class SMSchedule {
  406. private:
  407. /// Map from execution cycle to instructions.
  408. DenseMap<int, std::deque<SUnit *>> ScheduledInstrs;
  409. /// Map from instruction to execution cycle.
  410. std::map<SUnit *, int> InstrToCycle;
  411. /// Keep track of the first cycle value in the schedule. It starts
  412. /// as zero, but the algorithm allows negative values.
  413. int FirstCycle = 0;
  414. /// Keep track of the last cycle value in the schedule.
  415. int LastCycle = 0;
  416. /// The initiation interval (II) for the schedule.
  417. int InitiationInterval = 0;
  418. /// Target machine information.
  419. const TargetSubtargetInfo &ST;
  420. /// Virtual register information.
  421. MachineRegisterInfo &MRI;
  422. ResourceManager ProcItinResources;
  423. public:
  424. SMSchedule(MachineFunction *mf)
  425. : ST(mf->getSubtarget()), MRI(mf->getRegInfo()), ProcItinResources(&ST) {}
  426. void reset() {
  427. ScheduledInstrs.clear();
  428. InstrToCycle.clear();
  429. FirstCycle = 0;
  430. LastCycle = 0;
  431. InitiationInterval = 0;
  432. }
  433. /// Set the initiation interval for this schedule.
  434. void setInitiationInterval(int ii) { InitiationInterval = ii; }
  435. /// Return the initiation interval for this schedule.
  436. int getInitiationInterval() const { return InitiationInterval; }
  437. /// Return the first cycle in the completed schedule. This
  438. /// can be a negative value.
  439. int getFirstCycle() const { return FirstCycle; }
  440. /// Return the last cycle in the finalized schedule.
  441. int getFinalCycle() const { return FirstCycle + InitiationInterval - 1; }
  442. /// Return the cycle of the earliest scheduled instruction in the dependence
  443. /// chain.
  444. int earliestCycleInChain(const SDep &Dep);
  445. /// Return the cycle of the latest scheduled instruction in the dependence
  446. /// chain.
  447. int latestCycleInChain(const SDep &Dep);
  448. void computeStart(SUnit *SU, int *MaxEarlyStart, int *MinLateStart,
  449. int *MinEnd, int *MaxStart, int II, SwingSchedulerDAG *DAG);
  450. bool insert(SUnit *SU, int StartCycle, int EndCycle, int II);
  451. /// Iterators for the cycle to instruction map.
  452. using sched_iterator = DenseMap<int, std::deque<SUnit *>>::iterator;
  453. using const_sched_iterator =
  454. DenseMap<int, std::deque<SUnit *>>::const_iterator;
  455. /// Return true if the instruction is scheduled at the specified stage.
  456. bool isScheduledAtStage(SUnit *SU, unsigned StageNum) {
  457. return (stageScheduled(SU) == (int)StageNum);
  458. }
  459. /// Return the stage for a scheduled instruction. Return -1 if
  460. /// the instruction has not been scheduled.
  461. int stageScheduled(SUnit *SU) const {
  462. std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SU);
  463. if (it == InstrToCycle.end())
  464. return -1;
  465. return (it->second - FirstCycle) / InitiationInterval;
  466. }
  467. /// Return the cycle for a scheduled instruction. This function normalizes
  468. /// the first cycle to be 0.
  469. unsigned cycleScheduled(SUnit *SU) const {
  470. std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SU);
  471. assert(it != InstrToCycle.end() && "Instruction hasn't been scheduled.");
  472. return (it->second - FirstCycle) % InitiationInterval;
  473. }
  474. /// Return the maximum stage count needed for this schedule.
  475. unsigned getMaxStageCount() {
  476. return (LastCycle - FirstCycle) / InitiationInterval;
  477. }
  478. /// Return the instructions that are scheduled at the specified cycle.
  479. std::deque<SUnit *> &getInstructions(int cycle) {
  480. return ScheduledInstrs[cycle];
  481. }
  482. bool isValidSchedule(SwingSchedulerDAG *SSD);
  483. void finalizeSchedule(SwingSchedulerDAG *SSD);
  484. void orderDependence(SwingSchedulerDAG *SSD, SUnit *SU,
  485. std::deque<SUnit *> &Insts);
  486. bool isLoopCarried(SwingSchedulerDAG *SSD, MachineInstr &Phi);
  487. bool isLoopCarriedDefOfUse(SwingSchedulerDAG *SSD, MachineInstr *Def,
  488. MachineOperand &MO);
  489. void print(raw_ostream &os) const;
  490. void dump() const;
  491. };
  492. } // end namespace llvm
  493. #endif // LLVM_CODEGEN_MACHINEPIPELINER_H