ScheduleDAGInstrs.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- ScheduleDAGInstrs.h - MachineInstr Scheduling ------------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. /// \file Implements the ScheduleDAGInstrs class, which implements scheduling
  15. /// for a MachineInstr-based dependency graph.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #ifndef LLVM_CODEGEN_SCHEDULEDAGINSTRS_H
  19. #define LLVM_CODEGEN_SCHEDULEDAGINSTRS_H
  20. #include "llvm/ADT/DenseMap.h"
  21. #include "llvm/ADT/PointerIntPair.h"
  22. #include "llvm/ADT/STLExtras.h"
  23. #include "llvm/ADT/SmallVector.h"
  24. #include "llvm/ADT/SparseMultiSet.h"
  25. #include "llvm/ADT/SparseSet.h"
  26. #include "llvm/CodeGen/LivePhysRegs.h"
  27. #include "llvm/CodeGen/MachineBasicBlock.h"
  28. #include "llvm/CodeGen/ScheduleDAG.h"
  29. #include "llvm/CodeGen/TargetRegisterInfo.h"
  30. #include "llvm/CodeGen/TargetSchedule.h"
  31. #include "llvm/MC/LaneBitmask.h"
  32. #include <cassert>
  33. #include <cstdint>
  34. #include <list>
  35. #include <utility>
  36. #include <vector>
  37. namespace llvm {
  38. class AAResults;
  39. class LiveIntervals;
  40. class MachineFrameInfo;
  41. class MachineFunction;
  42. class MachineInstr;
  43. class MachineLoopInfo;
  44. class MachineOperand;
  45. struct MCSchedClassDesc;
  46. class PressureDiffs;
  47. class PseudoSourceValue;
  48. class RegPressureTracker;
  49. class UndefValue;
  50. class Value;
  51. /// An individual mapping from virtual register number to SUnit.
  52. struct VReg2SUnit {
  53. unsigned VirtReg;
  54. LaneBitmask LaneMask;
  55. SUnit *SU;
  56. VReg2SUnit(unsigned VReg, LaneBitmask LaneMask, SUnit *SU)
  57. : VirtReg(VReg), LaneMask(LaneMask), SU(SU) {}
  58. unsigned getSparseSetIndex() const {
  59. return Register::virtReg2Index(VirtReg);
  60. }
  61. };
  62. /// Mapping from virtual register to SUnit including an operand index.
  63. struct VReg2SUnitOperIdx : public VReg2SUnit {
  64. unsigned OperandIndex;
  65. VReg2SUnitOperIdx(unsigned VReg, LaneBitmask LaneMask,
  66. unsigned OperandIndex, SUnit *SU)
  67. : VReg2SUnit(VReg, LaneMask, SU), OperandIndex(OperandIndex) {}
  68. };
  69. /// Record a physical register access.
  70. /// For non-data-dependent uses, OpIdx == -1.
  71. struct PhysRegSUOper {
  72. SUnit *SU;
  73. int OpIdx;
  74. unsigned Reg;
  75. PhysRegSUOper(SUnit *su, int op, unsigned R): SU(su), OpIdx(op), Reg(R) {}
  76. unsigned getSparseSetIndex() const { return Reg; }
  77. };
  78. /// Use a SparseMultiSet to track physical registers. Storage is only
  79. /// allocated once for the pass. It can be cleared in constant time and reused
  80. /// without any frees.
  81. using Reg2SUnitsMap =
  82. SparseMultiSet<PhysRegSUOper, identity<unsigned>, uint16_t>;
  83. /// Use SparseSet as a SparseMap by relying on the fact that it never
  84. /// compares ValueT's, only unsigned keys. This allows the set to be cleared
  85. /// between scheduling regions in constant time as long as ValueT does not
  86. /// require a destructor.
  87. using VReg2SUnitMap = SparseSet<VReg2SUnit, VirtReg2IndexFunctor>;
  88. /// Track local uses of virtual registers. These uses are gathered by the DAG
  89. /// builder and may be consulted by the scheduler to avoid iterating an entire
  90. /// vreg use list.
  91. using VReg2SUnitMultiMap = SparseMultiSet<VReg2SUnit, VirtReg2IndexFunctor>;
  92. using VReg2SUnitOperIdxMultiMap =
  93. SparseMultiSet<VReg2SUnitOperIdx, VirtReg2IndexFunctor>;
  94. using ValueType = PointerUnion<const Value *, const PseudoSourceValue *>;
  95. struct UnderlyingObject : PointerIntPair<ValueType, 1, bool> {
  96. UnderlyingObject(ValueType V, bool MayAlias)
  97. : PointerIntPair<ValueType, 1, bool>(V, MayAlias) {}
  98. ValueType getValue() const { return getPointer(); }
  99. bool mayAlias() const { return getInt(); }
  100. };
  101. using UnderlyingObjectsVector = SmallVector<UnderlyingObject, 4>;
  102. /// A ScheduleDAG for scheduling lists of MachineInstr.
  103. class ScheduleDAGInstrs : public ScheduleDAG {
  104. protected:
  105. const MachineLoopInfo *MLI;
  106. const MachineFrameInfo &MFI;
  107. /// TargetSchedModel provides an interface to the machine model.
  108. TargetSchedModel SchedModel;
  109. /// True if the DAG builder should remove kill flags (in preparation for
  110. /// rescheduling).
  111. bool RemoveKillFlags;
  112. /// The standard DAG builder does not normally include terminators as DAG
  113. /// nodes because it does not create the necessary dependencies to prevent
  114. /// reordering. A specialized scheduler can override
  115. /// TargetInstrInfo::isSchedulingBoundary then enable this flag to indicate
  116. /// it has taken responsibility for scheduling the terminator correctly.
  117. bool CanHandleTerminators = false;
  118. /// Whether lane masks should get tracked.
  119. bool TrackLaneMasks = false;
  120. // State specific to the current scheduling region.
  121. // ------------------------------------------------
  122. /// The block in which to insert instructions
  123. MachineBasicBlock *BB;
  124. /// The beginning of the range to be scheduled.
  125. MachineBasicBlock::iterator RegionBegin;
  126. /// The end of the range to be scheduled.
  127. MachineBasicBlock::iterator RegionEnd;
  128. /// Instructions in this region (distance(RegionBegin, RegionEnd)).
  129. unsigned NumRegionInstrs;
  130. /// After calling BuildSchedGraph, each machine instruction in the current
  131. /// scheduling region is mapped to an SUnit.
  132. DenseMap<MachineInstr*, SUnit*> MISUnitMap;
  133. // State internal to DAG building.
  134. // -------------------------------
  135. /// Defs, Uses - Remember where defs and uses of each register are as we
  136. /// iterate upward through the instructions. This is allocated here instead
  137. /// of inside BuildSchedGraph to avoid the need for it to be initialized and
  138. /// destructed for each block.
  139. Reg2SUnitsMap Defs;
  140. Reg2SUnitsMap Uses;
  141. /// Tracks the last instruction(s) in this region defining each virtual
  142. /// register. There may be multiple current definitions for a register with
  143. /// disjunct lanemasks.
  144. VReg2SUnitMultiMap CurrentVRegDefs;
  145. /// Tracks the last instructions in this region using each virtual register.
  146. VReg2SUnitOperIdxMultiMap CurrentVRegUses;
  147. AAResults *AAForDep = nullptr;
  148. /// Remember a generic side-effecting instruction as we proceed.
  149. /// No other SU ever gets scheduled around it (except in the special
  150. /// case of a huge region that gets reduced).
  151. SUnit *BarrierChain = nullptr;
  152. public:
  153. /// A list of SUnits, used in Value2SUsMap, during DAG construction.
  154. /// Note: to gain speed it might be worth investigating an optimized
  155. /// implementation of this data structure, such as a singly linked list
  156. /// with a memory pool (SmallVector was tried but slow and SparseSet is not
  157. /// applicable).
  158. using SUList = std::list<SUnit *>;
  159. protected:
  160. /// A map from ValueType to SUList, used during DAG construction, as
  161. /// a means of remembering which SUs depend on which memory locations.
  162. class Value2SUsMap;
  163. /// Reduces maps in FIFO order, by N SUs. This is better than turning
  164. /// every Nth memory SU into BarrierChain in buildSchedGraph(), since
  165. /// it avoids unnecessary edges between seen SUs above the new BarrierChain,
  166. /// and those below it.
  167. void reduceHugeMemNodeMaps(Value2SUsMap &stores,
  168. Value2SUsMap &loads, unsigned N);
  169. /// Adds a chain edge between SUa and SUb, but only if both
  170. /// AAResults and Target fail to deny the dependency.
  171. void addChainDependency(SUnit *SUa, SUnit *SUb,
  172. unsigned Latency = 0);
  173. /// Adds dependencies as needed from all SUs in list to SU.
  174. void addChainDependencies(SUnit *SU, SUList &SUs, unsigned Latency) {
  175. for (SUnit *Entry : SUs)
  176. addChainDependency(SU, Entry, Latency);
  177. }
  178. /// Adds dependencies as needed from all SUs in map, to SU.
  179. void addChainDependencies(SUnit *SU, Value2SUsMap &Val2SUsMap);
  180. /// Adds dependencies as needed to SU, from all SUs mapped to V.
  181. void addChainDependencies(SUnit *SU, Value2SUsMap &Val2SUsMap,
  182. ValueType V);
  183. /// Adds barrier chain edges from all SUs in map, and then clear the map.
  184. /// This is equivalent to insertBarrierChain(), but optimized for the common
  185. /// case where the new BarrierChain (a global memory object) has a higher
  186. /// NodeNum than all SUs in map. It is assumed BarrierChain has been set
  187. /// before calling this.
  188. void addBarrierChain(Value2SUsMap &map);
  189. /// Inserts a barrier chain in a huge region, far below current SU.
  190. /// Adds barrier chain edges from all SUs in map with higher NodeNums than
  191. /// this new BarrierChain, and remove them from map. It is assumed
  192. /// BarrierChain has been set before calling this.
  193. void insertBarrierChain(Value2SUsMap &map);
  194. /// For an unanalyzable memory access, this Value is used in maps.
  195. UndefValue *UnknownValue;
  196. /// Topo - A topological ordering for SUnits which permits fast IsReachable
  197. /// and similar queries.
  198. ScheduleDAGTopologicalSort Topo;
  199. using DbgValueVector =
  200. std::vector<std::pair<MachineInstr *, MachineInstr *>>;
  201. /// Remember instruction that precedes DBG_VALUE.
  202. /// These are generated by buildSchedGraph but persist so they can be
  203. /// referenced when emitting the final schedule.
  204. DbgValueVector DbgValues;
  205. MachineInstr *FirstDbgValue = nullptr;
  206. /// Set of live physical registers for updating kill flags.
  207. LivePhysRegs LiveRegs;
  208. public:
  209. explicit ScheduleDAGInstrs(MachineFunction &mf,
  210. const MachineLoopInfo *mli,
  211. bool RemoveKillFlags = false);
  212. ~ScheduleDAGInstrs() override = default;
  213. /// Gets the machine model for instruction scheduling.
  214. const TargetSchedModel *getSchedModel() const { return &SchedModel; }
  215. /// Resolves and cache a resolved scheduling class for an SUnit.
  216. const MCSchedClassDesc *getSchedClass(SUnit *SU) const {
  217. if (!SU->SchedClass && SchedModel.hasInstrSchedModel())
  218. SU->SchedClass = SchedModel.resolveSchedClass(SU->getInstr());
  219. return SU->SchedClass;
  220. }
  221. /// IsReachable - Checks if SU is reachable from TargetSU.
  222. bool IsReachable(SUnit *SU, SUnit *TargetSU) {
  223. return Topo.IsReachable(SU, TargetSU);
  224. }
  225. /// Returns an iterator to the top of the current scheduling region.
  226. MachineBasicBlock::iterator begin() const { return RegionBegin; }
  227. /// Returns an iterator to the bottom of the current scheduling region.
  228. MachineBasicBlock::iterator end() const { return RegionEnd; }
  229. /// Creates a new SUnit and return a ptr to it.
  230. SUnit *newSUnit(MachineInstr *MI);
  231. /// Returns an existing SUnit for this MI, or nullptr.
  232. SUnit *getSUnit(MachineInstr *MI) const;
  233. /// If this method returns true, handling of the scheduling regions
  234. /// themselves (in case of a scheduling boundary in MBB) will be done
  235. /// beginning with the topmost region of MBB.
  236. virtual bool doMBBSchedRegionsTopDown() const { return false; }
  237. /// Prepares to perform scheduling in the given block.
  238. virtual void startBlock(MachineBasicBlock *BB);
  239. /// Cleans up after scheduling in the given block.
  240. virtual void finishBlock();
  241. /// Initialize the DAG and common scheduler state for a new
  242. /// scheduling region. This does not actually create the DAG, only clears
  243. /// it. The scheduling driver may call BuildSchedGraph multiple times per
  244. /// scheduling region.
  245. virtual void enterRegion(MachineBasicBlock *bb,
  246. MachineBasicBlock::iterator begin,
  247. MachineBasicBlock::iterator end,
  248. unsigned regioninstrs);
  249. /// Called when the scheduler has finished scheduling the current region.
  250. virtual void exitRegion();
  251. /// Builds SUnits for the current region.
  252. /// If \p RPTracker is non-null, compute register pressure as a side effect.
  253. /// The DAG builder is an efficient place to do it because it already visits
  254. /// operands.
  255. void buildSchedGraph(AAResults *AA,
  256. RegPressureTracker *RPTracker = nullptr,
  257. PressureDiffs *PDiffs = nullptr,
  258. LiveIntervals *LIS = nullptr,
  259. bool TrackLaneMasks = false);
  260. /// Adds dependencies from instructions in the current list of
  261. /// instructions being scheduled to scheduling barrier. We want to make sure
  262. /// instructions which define registers that are either used by the
  263. /// terminator or are live-out are properly scheduled. This is especially
  264. /// important when the definition latency of the return value(s) are too
  265. /// high to be hidden by the branch or when the liveout registers used by
  266. /// instructions in the fallthrough block.
  267. void addSchedBarrierDeps();
  268. /// Orders nodes according to selected style.
  269. ///
  270. /// Typically, a scheduling algorithm will implement schedule() without
  271. /// overriding enterRegion() or exitRegion().
  272. virtual void schedule() = 0;
  273. /// Allow targets to perform final scheduling actions at the level of the
  274. /// whole MachineFunction. By default does nothing.
  275. virtual void finalizeSchedule() {}
  276. void dumpNode(const SUnit &SU) const override;
  277. void dump() const override;
  278. /// Returns a label for a DAG node that points to an instruction.
  279. std::string getGraphNodeLabel(const SUnit *SU) const override;
  280. /// Returns a label for the region of code covered by the DAG.
  281. std::string getDAGName() const override;
  282. /// Fixes register kill flags that scheduling has made invalid.
  283. void fixupKills(MachineBasicBlock &MBB);
  284. /// True if an edge can be added from PredSU to SuccSU without creating
  285. /// a cycle.
  286. bool canAddEdge(SUnit *SuccSU, SUnit *PredSU);
  287. /// Add a DAG edge to the given SU with the given predecessor
  288. /// dependence data.
  289. ///
  290. /// \returns true if the edge may be added without creating a cycle OR if an
  291. /// equivalent edge already existed (false indicates failure).
  292. bool addEdge(SUnit *SuccSU, const SDep &PredDep);
  293. protected:
  294. void initSUnits();
  295. void addPhysRegDataDeps(SUnit *SU, unsigned OperIdx);
  296. void addPhysRegDeps(SUnit *SU, unsigned OperIdx);
  297. void addVRegDefDeps(SUnit *SU, unsigned OperIdx);
  298. void addVRegUseDeps(SUnit *SU, unsigned OperIdx);
  299. /// Returns a mask for which lanes get read/written by the given (register)
  300. /// machine operand.
  301. LaneBitmask getLaneMaskForMO(const MachineOperand &MO) const;
  302. /// Returns true if the def register in \p MO has no uses.
  303. bool deadDefHasNoUse(const MachineOperand &MO);
  304. };
  305. /// Creates a new SUnit and return a ptr to it.
  306. inline SUnit *ScheduleDAGInstrs::newSUnit(MachineInstr *MI) {
  307. #ifndef NDEBUG
  308. const SUnit *Addr = SUnits.empty() ? nullptr : &SUnits[0];
  309. #endif
  310. SUnits.emplace_back(MI, (unsigned)SUnits.size());
  311. assert((Addr == nullptr || Addr == &SUnits[0]) &&
  312. "SUnits std::vector reallocated on the fly!");
  313. return &SUnits.back();
  314. }
  315. /// Returns an existing SUnit for this MI, or nullptr.
  316. inline SUnit *ScheduleDAGInstrs::getSUnit(MachineInstr *MI) const {
  317. return MISUnitMap.lookup(MI);
  318. }
  319. } // end namespace llvm
  320. #endif // LLVM_CODEGEN_SCHEDULEDAGINSTRS_H
  321. #ifdef __GNUC__
  322. #pragma GCC diagnostic pop
  323. #endif