ScheduleDAG.h 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753
  1. //===------- llvm/CodeGen/ScheduleDAG.h - Common Base Class------*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the ScheduleDAG class, which is used as the common
  11. // base class for instruction schedulers. This encapsulates the scheduling DAG,
  12. // which is shared between SelectionDAG and MachineInstr scheduling.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #ifndef LLVM_CODEGEN_SCHEDULEDAG_H
  16. #define LLVM_CODEGEN_SCHEDULEDAG_H
  17. #include "llvm/ADT/BitVector.h"
  18. #include "llvm/ADT/GraphTraits.h"
  19. #include "llvm/ADT/PointerIntPair.h"
  20. #include "llvm/ADT/SmallVector.h"
  21. #include "llvm/CodeGen/MachineInstr.h"
  22. #include "llvm/Target/TargetLowering.h"
  23. namespace llvm {
  24. class AliasAnalysis;
  25. class SUnit;
  26. class MachineConstantPool;
  27. class MachineFunction;
  28. class MachineRegisterInfo;
  29. class MachineInstr;
  30. struct MCSchedClassDesc;
  31. class TargetRegisterInfo;
  32. class ScheduleDAG;
  33. class SDNode;
  34. class TargetInstrInfo;
  35. class MCInstrDesc;
  36. class TargetMachine;
  37. class TargetRegisterClass;
  38. template<class Graph> class GraphWriter;
  39. /// SDep - Scheduling dependency. This represents one direction of an
  40. /// edge in the scheduling DAG.
  41. class SDep {
  42. public:
  43. /// Kind - These are the different kinds of scheduling dependencies.
  44. enum Kind {
  45. Data, ///< Regular data dependence (aka true-dependence).
  46. Anti, ///< A register anti-dependedence (aka WAR).
  47. Output, ///< A register output-dependence (aka WAW).
  48. Order ///< Any other ordering dependency.
  49. };
  50. // Strong dependencies must be respected by the scheduler. Artificial
  51. // dependencies may be removed only if they are redundant with another
  52. // strong depedence.
  53. //
  54. // Weak dependencies may be violated by the scheduling strategy, but only if
  55. // the strategy can prove it is correct to do so.
  56. //
  57. // Strong OrderKinds must occur before "Weak".
  58. // Weak OrderKinds must occur after "Weak".
  59. enum OrderKind {
  60. Barrier, ///< An unknown scheduling barrier.
  61. MayAliasMem, ///< Nonvolatile load/Store instructions that may alias.
  62. MustAliasMem, ///< Nonvolatile load/Store instructions that must alias.
  63. Artificial, ///< Arbitrary strong DAG edge (no real dependence).
  64. Weak, ///< Arbitrary weak DAG edge.
  65. Cluster ///< Weak DAG edge linking a chain of clustered instrs.
  66. };
  67. private:
  68. /// Dep - A pointer to the depending/depended-on SUnit, and an enum
  69. /// indicating the kind of the dependency.
  70. PointerIntPair<SUnit *, 2, Kind> Dep;
  71. /// Contents - A union discriminated by the dependence kind.
  72. union {
  73. /// Reg - For Data, Anti, and Output dependencies, the associated
  74. /// register. For Data dependencies that don't currently have a register
  75. /// assigned, this is set to zero.
  76. unsigned Reg;
  77. /// Order - Additional information about Order dependencies.
  78. unsigned OrdKind; // enum OrderKind
  79. } Contents;
  80. /// Latency - The time associated with this edge. Often this is just
  81. /// the value of the Latency field of the predecessor, however advanced
  82. /// models may provide additional information about specific edges.
  83. unsigned Latency;
  84. public:
  85. /// SDep - Construct a null SDep. This is only for use by container
  86. /// classes which require default constructors. SUnits may not
  87. /// have null SDep edges.
  88. SDep() : Dep(nullptr, Data) {}
  89. /// SDep - Construct an SDep with the specified values.
  90. SDep(SUnit *S, Kind kind, unsigned Reg)
  91. : Dep(S, kind), Contents() {
  92. switch (kind) {
  93. default:
  94. llvm_unreachable("Reg given for non-register dependence!");
  95. case Anti:
  96. case Output:
  97. assert(Reg != 0 &&
  98. "SDep::Anti and SDep::Output must use a non-zero Reg!");
  99. Contents.Reg = Reg;
  100. Latency = 0;
  101. break;
  102. case Data:
  103. Contents.Reg = Reg;
  104. Latency = 1;
  105. break;
  106. }
  107. }
  108. SDep(SUnit *S, OrderKind kind)
  109. : Dep(S, Order), Contents(), Latency(0) {
  110. Contents.OrdKind = kind;
  111. }
  112. /// Return true if the specified SDep is equivalent except for latency.
  113. bool overlaps(const SDep &Other) const {
  114. if (Dep != Other.Dep) return false;
  115. switch (Dep.getInt()) {
  116. case Data:
  117. case Anti:
  118. case Output:
  119. return Contents.Reg == Other.Contents.Reg;
  120. case Order:
  121. return Contents.OrdKind == Other.Contents.OrdKind;
  122. }
  123. llvm_unreachable("Invalid dependency kind!");
  124. }
  125. bool operator==(const SDep &Other) const {
  126. return overlaps(Other) && Latency == Other.Latency;
  127. }
  128. bool operator!=(const SDep &Other) const {
  129. return !operator==(Other);
  130. }
  131. /// getLatency - Return the latency value for this edge, which roughly
  132. /// means the minimum number of cycles that must elapse between the
  133. /// predecessor and the successor, given that they have this edge
  134. /// between them.
  135. unsigned getLatency() const {
  136. return Latency;
  137. }
  138. /// setLatency - Set the latency for this edge.
  139. void setLatency(unsigned Lat) {
  140. Latency = Lat;
  141. }
  142. //// getSUnit - Return the SUnit to which this edge points.
  143. SUnit *getSUnit() const {
  144. return Dep.getPointer();
  145. }
  146. //// setSUnit - Assign the SUnit to which this edge points.
  147. void setSUnit(SUnit *SU) {
  148. Dep.setPointer(SU);
  149. }
  150. /// getKind - Return an enum value representing the kind of the dependence.
  151. Kind getKind() const {
  152. return Dep.getInt();
  153. }
  154. /// isCtrl - Shorthand for getKind() != SDep::Data.
  155. bool isCtrl() const {
  156. return getKind() != Data;
  157. }
  158. /// isNormalMemory - Test if this is an Order dependence between two
  159. /// memory accesses where both sides of the dependence access memory
  160. /// in non-volatile and fully modeled ways.
  161. bool isNormalMemory() const {
  162. return getKind() == Order && (Contents.OrdKind == MayAliasMem
  163. || Contents.OrdKind == MustAliasMem);
  164. }
  165. /// isBarrier - Test if this is an Order dependence that is marked
  166. /// as a barrier.
  167. bool isBarrier() const {
  168. return getKind() == Order && Contents.OrdKind == Barrier;
  169. }
  170. /// isNormalMemoryOrBarrier - Test if this is could be any kind of memory
  171. /// dependence.
  172. bool isNormalMemoryOrBarrier() const {
  173. return (isNormalMemory() || isBarrier());
  174. }
  175. /// isMustAlias - Test if this is an Order dependence that is marked
  176. /// as "must alias", meaning that the SUnits at either end of the edge
  177. /// have a memory dependence on a known memory location.
  178. bool isMustAlias() const {
  179. return getKind() == Order && Contents.OrdKind == MustAliasMem;
  180. }
  181. /// isWeak - Test if this a weak dependence. Weak dependencies are
  182. /// considered DAG edges for height computation and other heuristics, but do
  183. /// not force ordering. Breaking a weak edge may require the scheduler to
  184. /// compensate, for example by inserting a copy.
  185. bool isWeak() const {
  186. return getKind() == Order && Contents.OrdKind >= Weak;
  187. }
  188. /// isArtificial - Test if this is an Order dependence that is marked
  189. /// as "artificial", meaning it isn't necessary for correctness.
  190. bool isArtificial() const {
  191. return getKind() == Order && Contents.OrdKind == Artificial;
  192. }
  193. /// isCluster - Test if this is an Order dependence that is marked
  194. /// as "cluster", meaning it is artificial and wants to be adjacent.
  195. bool isCluster() const {
  196. return getKind() == Order && Contents.OrdKind == Cluster;
  197. }
  198. /// isAssignedRegDep - Test if this is a Data dependence that is
  199. /// associated with a register.
  200. bool isAssignedRegDep() const {
  201. return getKind() == Data && Contents.Reg != 0;
  202. }
  203. /// getReg - Return the register associated with this edge. This is
  204. /// only valid on Data, Anti, and Output edges. On Data edges, this
  205. /// value may be zero, meaning there is no associated register.
  206. unsigned getReg() const {
  207. assert((getKind() == Data || getKind() == Anti || getKind() == Output) &&
  208. "getReg called on non-register dependence edge!");
  209. return Contents.Reg;
  210. }
  211. /// setReg - Assign the associated register for this edge. This is
  212. /// only valid on Data, Anti, and Output edges. On Anti and Output
  213. /// edges, this value must not be zero. On Data edges, the value may
  214. /// be zero, which would mean that no specific register is associated
  215. /// with this edge.
  216. void setReg(unsigned Reg) {
  217. assert((getKind() == Data || getKind() == Anti || getKind() == Output) &&
  218. "setReg called on non-register dependence edge!");
  219. assert((getKind() != Anti || Reg != 0) &&
  220. "SDep::Anti edge cannot use the zero register!");
  221. assert((getKind() != Output || Reg != 0) &&
  222. "SDep::Output edge cannot use the zero register!");
  223. Contents.Reg = Reg;
  224. }
  225. };
  226. template <>
  227. struct isPodLike<SDep> { static const bool value = true; };
  228. /// SUnit - Scheduling unit. This is a node in the scheduling DAG.
  229. class SUnit {
  230. private:
  231. enum : unsigned { BoundaryID = ~0u };
  232. SDNode *Node; // Representative node.
  233. MachineInstr *Instr; // Alternatively, a MachineInstr.
  234. public:
  235. SUnit *OrigNode; // If not this, the node from which
  236. // this node was cloned.
  237. // (SD scheduling only)
  238. const MCSchedClassDesc *SchedClass; // NULL or resolved SchedClass.
  239. // Preds/Succs - The SUnits before/after us in the graph.
  240. SmallVector<SDep, 4> Preds; // All sunit predecessors.
  241. SmallVector<SDep, 4> Succs; // All sunit successors.
  242. typedef SmallVectorImpl<SDep>::iterator pred_iterator;
  243. typedef SmallVectorImpl<SDep>::iterator succ_iterator;
  244. typedef SmallVectorImpl<SDep>::const_iterator const_pred_iterator;
  245. typedef SmallVectorImpl<SDep>::const_iterator const_succ_iterator;
  246. unsigned NodeNum; // Entry # of node in the node vector.
  247. unsigned NodeQueueId; // Queue id of node.
  248. unsigned NumPreds; // # of SDep::Data preds.
  249. unsigned NumSuccs; // # of SDep::Data sucss.
  250. unsigned NumPredsLeft; // # of preds not scheduled.
  251. unsigned NumSuccsLeft; // # of succs not scheduled.
  252. unsigned WeakPredsLeft; // # of weak preds not scheduled.
  253. unsigned WeakSuccsLeft; // # of weak succs not scheduled.
  254. unsigned short NumRegDefsLeft; // # of reg defs with no scheduled use.
  255. unsigned short Latency; // Node latency.
  256. bool isVRegCycle : 1; // May use and def the same vreg.
  257. bool isCall : 1; // Is a function call.
  258. bool isCallOp : 1; // Is a function call operand.
  259. bool isTwoAddress : 1; // Is a two-address instruction.
  260. bool isCommutable : 1; // Is a commutable instruction.
  261. bool hasPhysRegUses : 1; // Has physreg uses.
  262. bool hasPhysRegDefs : 1; // Has physreg defs that are being used.
  263. bool hasPhysRegClobbers : 1; // Has any physreg defs, used or not.
  264. bool isPending : 1; // True once pending.
  265. bool isAvailable : 1; // True once available.
  266. bool isScheduled : 1; // True once scheduled.
  267. bool isScheduleHigh : 1; // True if preferable to schedule high.
  268. bool isScheduleLow : 1; // True if preferable to schedule low.
  269. bool isCloned : 1; // True if this node has been cloned.
  270. bool isUnbuffered : 1; // Uses an unbuffered resource.
  271. bool hasReservedResource : 1; // Uses a reserved resource.
  272. Sched::Preference SchedulingPref; // Scheduling preference.
  273. private:
  274. bool isDepthCurrent : 1; // True if Depth is current.
  275. bool isHeightCurrent : 1; // True if Height is current.
  276. unsigned Depth; // Node depth.
  277. unsigned Height; // Node height.
  278. public:
  279. unsigned TopReadyCycle; // Cycle relative to start when node is ready.
  280. unsigned BotReadyCycle; // Cycle relative to end when node is ready.
  281. const TargetRegisterClass *CopyDstRC; // Is a special copy node if not null.
  282. const TargetRegisterClass *CopySrcRC;
  283. /// SUnit - Construct an SUnit for pre-regalloc scheduling to represent
  284. /// an SDNode and any nodes flagged to it.
  285. SUnit(SDNode *node, unsigned nodenum)
  286. : Node(node), Instr(nullptr), OrigNode(nullptr), SchedClass(nullptr),
  287. NodeNum(nodenum), NodeQueueId(0), NumPreds(0), NumSuccs(0),
  288. NumPredsLeft(0), NumSuccsLeft(0), WeakPredsLeft(0), WeakSuccsLeft(0),
  289. NumRegDefsLeft(0), Latency(0), isVRegCycle(false), isCall(false),
  290. isCallOp(false), isTwoAddress(false), isCommutable(false),
  291. hasPhysRegUses(false), hasPhysRegDefs(false), hasPhysRegClobbers(false),
  292. isPending(false), isAvailable(false), isScheduled(false),
  293. isScheduleHigh(false), isScheduleLow(false), isCloned(false),
  294. isUnbuffered(false), hasReservedResource(false),
  295. SchedulingPref(Sched::None), isDepthCurrent(false),
  296. isHeightCurrent(false), Depth(0), Height(0), TopReadyCycle(0),
  297. BotReadyCycle(0), CopyDstRC(nullptr), CopySrcRC(nullptr) {}
  298. /// SUnit - Construct an SUnit for post-regalloc scheduling to represent
  299. /// a MachineInstr.
  300. SUnit(MachineInstr *instr, unsigned nodenum)
  301. : Node(nullptr), Instr(instr), OrigNode(nullptr), SchedClass(nullptr),
  302. NodeNum(nodenum), NodeQueueId(0), NumPreds(0), NumSuccs(0),
  303. NumPredsLeft(0), NumSuccsLeft(0), WeakPredsLeft(0), WeakSuccsLeft(0),
  304. NumRegDefsLeft(0), Latency(0), isVRegCycle(false), isCall(false),
  305. isCallOp(false), isTwoAddress(false), isCommutable(false),
  306. hasPhysRegUses(false), hasPhysRegDefs(false), hasPhysRegClobbers(false),
  307. isPending(false), isAvailable(false), isScheduled(false),
  308. isScheduleHigh(false), isScheduleLow(false), isCloned(false),
  309. isUnbuffered(false), hasReservedResource(false),
  310. SchedulingPref(Sched::None), isDepthCurrent(false),
  311. isHeightCurrent(false), Depth(0), Height(0), TopReadyCycle(0),
  312. BotReadyCycle(0), CopyDstRC(nullptr), CopySrcRC(nullptr) {}
  313. /// SUnit - Construct a placeholder SUnit.
  314. SUnit()
  315. : Node(nullptr), Instr(nullptr), OrigNode(nullptr), SchedClass(nullptr),
  316. NodeNum(BoundaryID), NodeQueueId(0), NumPreds(0), NumSuccs(0),
  317. NumPredsLeft(0), NumSuccsLeft(0), WeakPredsLeft(0), WeakSuccsLeft(0),
  318. NumRegDefsLeft(0), Latency(0), isVRegCycle(false), isCall(false),
  319. isCallOp(false), isTwoAddress(false), isCommutable(false),
  320. hasPhysRegUses(false), hasPhysRegDefs(false), hasPhysRegClobbers(false),
  321. isPending(false), isAvailable(false), isScheduled(false),
  322. isScheduleHigh(false), isScheduleLow(false), isCloned(false),
  323. isUnbuffered(false), hasReservedResource(false),
  324. SchedulingPref(Sched::None), isDepthCurrent(false),
  325. isHeightCurrent(false), Depth(0), Height(0), TopReadyCycle(0),
  326. BotReadyCycle(0), CopyDstRC(nullptr), CopySrcRC(nullptr) {}
  327. /// \brief Boundary nodes are placeholders for the boundary of the
  328. /// scheduling region.
  329. ///
  330. /// BoundaryNodes can have DAG edges, including Data edges, but they do not
  331. /// correspond to schedulable entities (e.g. instructions) and do not have a
  332. /// valid ID. Consequently, always check for boundary nodes before accessing
  333. /// an assoicative data structure keyed on node ID.
  334. bool isBoundaryNode() const { return NodeNum == BoundaryID; };
  335. /// setNode - Assign the representative SDNode for this SUnit.
  336. /// This may be used during pre-regalloc scheduling.
  337. void setNode(SDNode *N) {
  338. assert(!Instr && "Setting SDNode of SUnit with MachineInstr!");
  339. Node = N;
  340. }
  341. /// getNode - Return the representative SDNode for this SUnit.
  342. /// This may be used during pre-regalloc scheduling.
  343. SDNode *getNode() const {
  344. assert(!Instr && "Reading SDNode of SUnit with MachineInstr!");
  345. return Node;
  346. }
  347. /// isInstr - Return true if this SUnit refers to a machine instruction as
  348. /// opposed to an SDNode.
  349. bool isInstr() const { return Instr; }
  350. /// setInstr - Assign the instruction for the SUnit.
  351. /// This may be used during post-regalloc scheduling.
  352. void setInstr(MachineInstr *MI) {
  353. assert(!Node && "Setting MachineInstr of SUnit with SDNode!");
  354. Instr = MI;
  355. }
  356. /// getInstr - Return the representative MachineInstr for this SUnit.
  357. /// This may be used during post-regalloc scheduling.
  358. MachineInstr *getInstr() const {
  359. assert(!Node && "Reading MachineInstr of SUnit with SDNode!");
  360. return Instr;
  361. }
  362. /// addPred - This adds the specified edge as a pred of the current node if
  363. /// not already. It also adds the current node as a successor of the
  364. /// specified node.
  365. bool addPred(const SDep &D, bool Required = true);
  366. /// removePred - This removes the specified edge as a pred of the current
  367. /// node if it exists. It also removes the current node as a successor of
  368. /// the specified node.
  369. void removePred(const SDep &D);
  370. /// getDepth - Return the depth of this node, which is the length of the
  371. /// maximum path up to any node which has no predecessors.
  372. unsigned getDepth() const {
  373. if (!isDepthCurrent)
  374. const_cast<SUnit *>(this)->ComputeDepth();
  375. return Depth;
  376. }
  377. /// getHeight - Return the height of this node, which is the length of the
  378. /// maximum path down to any node which has no successors.
  379. unsigned getHeight() const {
  380. if (!isHeightCurrent)
  381. const_cast<SUnit *>(this)->ComputeHeight();
  382. return Height;
  383. }
  384. /// setDepthToAtLeast - If NewDepth is greater than this node's
  385. /// depth value, set it to be the new depth value. This also
  386. /// recursively marks successor nodes dirty.
  387. void setDepthToAtLeast(unsigned NewDepth);
  388. /// setDepthToAtLeast - If NewDepth is greater than this node's
  389. /// depth value, set it to be the new height value. This also
  390. /// recursively marks predecessor nodes dirty.
  391. void setHeightToAtLeast(unsigned NewHeight);
  392. /// setDepthDirty - Set a flag in this node to indicate that its
  393. /// stored Depth value will require recomputation the next time
  394. /// getDepth() is called.
  395. void setDepthDirty();
  396. /// setHeightDirty - Set a flag in this node to indicate that its
  397. /// stored Height value will require recomputation the next time
  398. /// getHeight() is called.
  399. void setHeightDirty();
  400. /// isPred - Test if node N is a predecessor of this node.
  401. bool isPred(SUnit *N) {
  402. for (unsigned i = 0, e = (unsigned)Preds.size(); i != e; ++i)
  403. if (Preds[i].getSUnit() == N)
  404. return true;
  405. return false;
  406. }
  407. /// isSucc - Test if node N is a successor of this node.
  408. bool isSucc(SUnit *N) {
  409. for (unsigned i = 0, e = (unsigned)Succs.size(); i != e; ++i)
  410. if (Succs[i].getSUnit() == N)
  411. return true;
  412. return false;
  413. }
  414. bool isTopReady() const {
  415. return NumPredsLeft == 0;
  416. }
  417. bool isBottomReady() const {
  418. return NumSuccsLeft == 0;
  419. }
  420. /// \brief Order this node's predecessor edges such that the critical path
  421. /// edge occurs first.
  422. void biasCriticalPath();
  423. void dump(const ScheduleDAG *G) const;
  424. void dumpAll(const ScheduleDAG *G) const;
  425. void print(raw_ostream &O, const ScheduleDAG *G) const;
  426. private:
  427. void ComputeDepth();
  428. void ComputeHeight();
  429. };
  430. //===--------------------------------------------------------------------===//
  431. /// SchedulingPriorityQueue - This interface is used to plug different
  432. /// priorities computation algorithms into the list scheduler. It implements
  433. /// the interface of a standard priority queue, where nodes are inserted in
  434. /// arbitrary order and returned in priority order. The computation of the
  435. /// priority and the representation of the queue are totally up to the
  436. /// implementation to decide.
  437. ///
  438. class SchedulingPriorityQueue {
  439. virtual void anchor();
  440. unsigned CurCycle;
  441. bool HasReadyFilter;
  442. public:
  443. SchedulingPriorityQueue(bool rf = false):
  444. CurCycle(0), HasReadyFilter(rf) {}
  445. virtual ~SchedulingPriorityQueue() {}
  446. virtual bool isBottomUp() const = 0;
  447. virtual void initNodes(std::vector<SUnit> &SUnits) = 0;
  448. virtual void addNode(const SUnit *SU) = 0;
  449. virtual void updateNode(const SUnit *SU) = 0;
  450. virtual void releaseState() = 0;
  451. virtual bool empty() const = 0;
  452. bool hasReadyFilter() const { return HasReadyFilter; }
  453. virtual bool tracksRegPressure() const { return false; }
  454. virtual bool isReady(SUnit *) const {
  455. assert(!HasReadyFilter && "The ready filter must override isReady()");
  456. return true;
  457. }
  458. virtual void push(SUnit *U) = 0;
  459. void push_all(const std::vector<SUnit *> &Nodes) {
  460. for (std::vector<SUnit *>::const_iterator I = Nodes.begin(),
  461. E = Nodes.end(); I != E; ++I)
  462. push(*I);
  463. }
  464. virtual SUnit *pop() = 0;
  465. virtual void remove(SUnit *SU) = 0;
  466. virtual void dump(ScheduleDAG *) const {}
  467. /// scheduledNode - As each node is scheduled, this method is invoked. This
  468. /// allows the priority function to adjust the priority of related
  469. /// unscheduled nodes, for example.
  470. ///
  471. virtual void scheduledNode(SUnit *) {}
  472. virtual void unscheduledNode(SUnit *) {}
  473. void setCurCycle(unsigned Cycle) {
  474. CurCycle = Cycle;
  475. }
  476. unsigned getCurCycle() const {
  477. return CurCycle;
  478. }
  479. };
  480. class ScheduleDAG {
  481. public:
  482. const TargetMachine &TM; // Target processor
  483. const TargetInstrInfo *TII; // Target instruction information
  484. const TargetRegisterInfo *TRI; // Target processor register info
  485. MachineFunction &MF; // Machine function
  486. MachineRegisterInfo &MRI; // Virtual/real register map
  487. std::vector<SUnit> SUnits; // The scheduling units.
  488. SUnit EntrySU; // Special node for the region entry.
  489. SUnit ExitSU; // Special node for the region exit.
  490. #ifdef NDEBUG
  491. static const bool StressSched = false;
  492. #else
  493. bool StressSched;
  494. #endif
  495. explicit ScheduleDAG(MachineFunction &mf);
  496. virtual ~ScheduleDAG();
  497. /// clearDAG - clear the DAG state (between regions).
  498. void clearDAG();
  499. /// getInstrDesc - Return the MCInstrDesc of this SUnit.
  500. /// Return NULL for SDNodes without a machine opcode.
  501. const MCInstrDesc *getInstrDesc(const SUnit *SU) const {
  502. if (SU->isInstr()) return &SU->getInstr()->getDesc();
  503. return getNodeDesc(SU->getNode());
  504. }
  505. /// viewGraph - Pop up a GraphViz/gv window with the ScheduleDAG rendered
  506. /// using 'dot'.
  507. ///
  508. virtual void viewGraph(const Twine &Name, const Twine &Title);
  509. virtual void viewGraph();
  510. virtual void dumpNode(const SUnit *SU) const = 0;
  511. /// getGraphNodeLabel - Return a label for an SUnit node in a visualization
  512. /// of the ScheduleDAG.
  513. virtual std::string getGraphNodeLabel(const SUnit *SU) const = 0;
  514. /// getDAGLabel - Return a label for the region of code covered by the DAG.
  515. virtual std::string getDAGName() const = 0;
  516. /// addCustomGraphFeatures - Add custom features for a visualization of
  517. /// the ScheduleDAG.
  518. virtual void addCustomGraphFeatures(GraphWriter<ScheduleDAG*> &) const {}
  519. #ifndef NDEBUG
  520. /// VerifyScheduledDAG - Verify that all SUnits were scheduled and that
  521. /// their state is consistent. Return the number of scheduled SUnits.
  522. unsigned VerifyScheduledDAG(bool isBottomUp);
  523. #endif
  524. private:
  525. // Return the MCInstrDesc of this SDNode or NULL.
  526. const MCInstrDesc *getNodeDesc(const SDNode *Node) const;
  527. };
  528. class SUnitIterator : public std::iterator<std::forward_iterator_tag,
  529. SUnit, ptrdiff_t> {
  530. SUnit *Node;
  531. unsigned Operand;
  532. SUnitIterator(SUnit *N, unsigned Op) : Node(N), Operand(Op) {}
  533. public:
  534. bool operator==(const SUnitIterator& x) const {
  535. return Operand == x.Operand;
  536. }
  537. bool operator!=(const SUnitIterator& x) const { return !operator==(x); }
  538. pointer operator*() const {
  539. return Node->Preds[Operand].getSUnit();
  540. }
  541. pointer operator->() const { return operator*(); }
  542. SUnitIterator& operator++() { // Preincrement
  543. ++Operand;
  544. return *this;
  545. }
  546. SUnitIterator operator++(int) { // Postincrement
  547. SUnitIterator tmp = *this; ++*this; return tmp;
  548. }
  549. static SUnitIterator begin(SUnit *N) { return SUnitIterator(N, 0); }
  550. static SUnitIterator end (SUnit *N) {
  551. return SUnitIterator(N, (unsigned)N->Preds.size());
  552. }
  553. unsigned getOperand() const { return Operand; }
  554. const SUnit *getNode() const { return Node; }
  555. /// isCtrlDep - Test if this is not an SDep::Data dependence.
  556. bool isCtrlDep() const {
  557. return getSDep().isCtrl();
  558. }
  559. bool isArtificialDep() const {
  560. return getSDep().isArtificial();
  561. }
  562. const SDep &getSDep() const {
  563. return Node->Preds[Operand];
  564. }
  565. };
  566. template <> struct GraphTraits<SUnit*> {
  567. typedef SUnit NodeType;
  568. typedef SUnitIterator ChildIteratorType;
  569. static inline NodeType *getEntryNode(SUnit *N) { return N; }
  570. static inline ChildIteratorType child_begin(NodeType *N) {
  571. return SUnitIterator::begin(N);
  572. }
  573. static inline ChildIteratorType child_end(NodeType *N) {
  574. return SUnitIterator::end(N);
  575. }
  576. };
  577. template <> struct GraphTraits<ScheduleDAG*> : public GraphTraits<SUnit*> {
  578. typedef std::vector<SUnit>::iterator nodes_iterator;
  579. static nodes_iterator nodes_begin(ScheduleDAG *G) {
  580. return G->SUnits.begin();
  581. }
  582. static nodes_iterator nodes_end(ScheduleDAG *G) {
  583. return G->SUnits.end();
  584. }
  585. };
  586. /// ScheduleDAGTopologicalSort is a class that computes a topological
  587. /// ordering for SUnits and provides methods for dynamically updating
  588. /// the ordering as new edges are added.
  589. ///
  590. /// This allows a very fast implementation of IsReachable, for example.
  591. ///
  592. class ScheduleDAGTopologicalSort {
  593. /// SUnits - A reference to the ScheduleDAG's SUnits.
  594. std::vector<SUnit> &SUnits;
  595. SUnit *ExitSU;
  596. /// Index2Node - Maps topological index to the node number.
  597. std::vector<int> Index2Node;
  598. /// Node2Index - Maps the node number to its topological index.
  599. std::vector<int> Node2Index;
  600. /// Visited - a set of nodes visited during a DFS traversal.
  601. BitVector Visited;
  602. /// DFS - make a DFS traversal and mark all nodes affected by the
  603. /// edge insertion. These nodes will later get new topological indexes
  604. /// by means of the Shift method.
  605. void DFS(const SUnit *SU, int UpperBound, bool& HasLoop);
  606. /// Shift - reassign topological indexes for the nodes in the DAG
  607. /// to preserve the topological ordering.
  608. void Shift(BitVector& Visited, int LowerBound, int UpperBound);
  609. /// Allocate - assign the topological index to the node n.
  610. void Allocate(int n, int index);
  611. public:
  612. ScheduleDAGTopologicalSort(std::vector<SUnit> &SUnits, SUnit *ExitSU);
  613. /// InitDAGTopologicalSorting - create the initial topological
  614. /// ordering from the DAG to be scheduled.
  615. void InitDAGTopologicalSorting();
  616. /// IsReachable - Checks if SU is reachable from TargetSU.
  617. bool IsReachable(const SUnit *SU, const SUnit *TargetSU);
  618. /// WillCreateCycle - Return true if addPred(TargetSU, SU) creates a cycle.
  619. bool WillCreateCycle(SUnit *TargetSU, SUnit *SU);
  620. /// AddPred - Updates the topological ordering to accommodate an edge
  621. /// to be added from SUnit X to SUnit Y.
  622. void AddPred(SUnit *Y, SUnit *X);
  623. /// RemovePred - Updates the topological ordering to accommodate an
  624. /// an edge to be removed from the specified node N from the predecessors
  625. /// of the current node M.
  626. void RemovePred(SUnit *M, SUnit *N);
  627. typedef std::vector<int>::iterator iterator;
  628. typedef std::vector<int>::const_iterator const_iterator;
  629. iterator begin() { return Index2Node.begin(); }
  630. const_iterator begin() const { return Index2Node.begin(); }
  631. iterator end() { return Index2Node.end(); }
  632. const_iterator end() const { return Index2Node.end(); }
  633. typedef std::vector<int>::reverse_iterator reverse_iterator;
  634. typedef std::vector<int>::const_reverse_iterator const_reverse_iterator;
  635. reverse_iterator rbegin() { return Index2Node.rbegin(); }
  636. const_reverse_iterator rbegin() const { return Index2Node.rbegin(); }
  637. reverse_iterator rend() { return Index2Node.rend(); }
  638. const_reverse_iterator rend() const { return Index2Node.rend(); }
  639. };
  640. }
  641. #endif