ScheduleDAG.h revision 47ac0f0c7c39289f5970688154e385be22b7f293
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.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CODEGEN_SCHEDULEDAG_H
16#define LLVM_CODEGEN_SCHEDULEDAG_H
17
18#include "llvm/CodeGen/MachineBasicBlock.h"
19#include "llvm/ADT/DenseMap.h"
20#include "llvm/ADT/BitVector.h"
21#include "llvm/ADT/GraphTraits.h"
22#include "llvm/ADT/SmallVector.h"
23#include "llvm/ADT/PointerIntPair.h"
24
25namespace llvm {
26  struct SUnit;
27  class MachineConstantPool;
28  class MachineFunction;
29  class MachineModuleInfo;
30  class MachineRegisterInfo;
31  class MachineInstr;
32  class TargetRegisterInfo;
33  class ScheduleDAG;
34  class SDNode;
35  class TargetInstrInfo;
36  class TargetInstrDesc;
37  class TargetLowering;
38  class TargetMachine;
39  class TargetRegisterClass;
40  template<class Graph> class GraphWriter;
41
42  /// SDep - Scheduling dependency. This represents one direction of an
43  /// edge in the scheduling DAG.
44  class SDep {
45  public:
46    /// Kind - These are the different kinds of scheduling dependencies.
47    enum Kind {
48      Data,        ///< Regular data dependence (aka true-dependence).
49      Anti,        ///< A register anti-dependedence (aka WAR).
50      Output,      ///< A register output-dependence (aka WAW).
51      Order        ///< Any other ordering dependency.
52    };
53
54  private:
55    /// Dep - A pointer to the depending/depended-on SUnit, and an enum
56    /// indicating the kind of the dependency.
57    PointerIntPair<SUnit *, 2, Kind> Dep;
58
59    /// Contents - A union discriminated by the dependence kind.
60    union {
61      /// Reg - For Data, Anti, and Output dependencies, the associated
62      /// register. For Data dependencies that don't currently have a register
63      /// assigned, this is set to zero.
64      unsigned Reg;
65
66      /// Order - Additional information about Order dependencies.
67      struct {
68        /// isNormalMemory - True if both sides of the dependence
69        /// access memory in non-volatile and fully modeled ways.
70        bool isNormalMemory : 1;
71
72        /// isMustAlias - True if both sides of the dependence are known to
73        /// access the same memory.
74        bool isMustAlias : 1;
75
76        /// isArtificial - True if this is an artificial dependency, meaning
77        /// it is not necessary for program correctness, and may be safely
78        /// deleted if necessary.
79        bool isArtificial : 1;
80      } Order;
81    } Contents;
82
83    /// Latency - The time associated with this edge. Often this is just
84    /// the value of the Latency field of the predecessor, however advanced
85    /// models may provide additional information about specific edges.
86    unsigned Latency;
87
88  public:
89    /// SDep - Construct a null SDep. This is only for use by container
90    /// classes which require default constructors. SUnits may not
91    /// have null SDep edges.
92    SDep() : Dep(0, Data) {}
93
94    /// SDep - Construct an SDep with the specified values.
95    SDep(SUnit *S, Kind kind, unsigned latency = 1, unsigned Reg = 0,
96         bool isNormalMemory = false, bool isMustAlias = false,
97         bool isArtificial = false)
98      : Dep(S, kind), Contents(), Latency(latency) {
99      switch (kind) {
100      case Anti:
101      case Output:
102        assert(Reg != 0 &&
103               "SDep::Anti and SDep::Output must use a non-zero Reg!");
104        // fall through
105      case Data:
106        assert(!isMustAlias && "isMustAlias only applies with SDep::Order!");
107        assert(!isArtificial && "isArtificial only applies with SDep::Order!");
108        Contents.Reg = Reg;
109        break;
110      case Order:
111        assert(Reg == 0 && "Reg given for non-register dependence!");
112        Contents.Order.isNormalMemory = isNormalMemory;
113        Contents.Order.isMustAlias = isMustAlias;
114        Contents.Order.isArtificial = isArtificial;
115        break;
116      }
117    }
118
119    bool operator==(const SDep &Other) const {
120      if (Dep != Other.Dep || Latency != Other.Latency) return false;
121      switch (Dep.getInt()) {
122      case Data:
123      case Anti:
124      case Output:
125        return Contents.Reg == Other.Contents.Reg;
126      case Order:
127        return Contents.Order.isNormalMemory ==
128                 Other.Contents.Order.isNormalMemory &&
129               Contents.Order.isMustAlias == Other.Contents.Order.isMustAlias &&
130               Contents.Order.isArtificial == Other.Contents.Order.isArtificial;
131      }
132      assert(0 && "Invalid dependency kind!");
133      return false;
134    }
135
136    bool operator!=(const SDep &Other) const {
137      return !operator==(Other);
138    }
139
140    /// getLatency - Return the latency value for this edge, which roughly
141    /// means the minimum number of cycles that must elapse between the
142    /// predecessor and the successor, given that they have this edge
143    /// between them.
144    unsigned getLatency() const {
145      return Latency;
146    }
147
148    //// getSUnit - Return the SUnit to which this edge points.
149    SUnit *getSUnit() const {
150      return Dep.getPointer();
151    }
152
153    //// setSUnit - Assign the SUnit to which this edge points.
154    void setSUnit(SUnit *SU) {
155      Dep.setPointer(SU);
156    }
157
158    /// getKind - Return an enum value representing the kind of the dependence.
159    Kind getKind() const {
160      return Dep.getInt();
161    }
162
163    /// isCtrl - Shorthand for getKind() != SDep::Data.
164    bool isCtrl() const {
165      return getKind() != Data;
166    }
167
168    /// isNormalMemory - Test if this is an Order dependence between two
169    /// memory accesses where both sides of the dependence access memory
170    /// in non-volatile and fully modeled ways.
171    bool isNormalMemory() const {
172      return getKind() == Order && Contents.Order.isNormalMemory;
173    }
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.Order.isMustAlias;
180    }
181
182    /// isArtificial - Test if this is an Order dependence that is marked
183    /// as "artificial", meaning it isn't necessary for correctness.
184    bool isArtificial() const {
185      return getKind() == Order && Contents.Order.isArtificial;
186    }
187
188    /// isAssignedRegDep - Test if this is a Data dependence that is
189    /// associated with a register.
190    bool isAssignedRegDep() const {
191      return getKind() == Data && Contents.Reg != 0;
192    }
193
194    /// getReg - Return the register associated with this edge. This is
195    /// only valid on Data, Anti, and Output edges. On Data edges, this
196    /// value may be zero, meaning there is no associated register.
197    unsigned getReg() const {
198      assert((getKind() == Data || getKind() == Anti || getKind() == Output) &&
199             "getReg called on non-register dependence edge!");
200      return Contents.Reg;
201    }
202
203    /// setReg - Assign the associated register for this edge. This is
204    /// only valid on Data, Anti, and Output edges. On Anti and Output
205    /// edges, this value must not be zero. On Data edges, the value may
206    /// be zero, which would mean that no specific register is associated
207    /// with this edge.
208    void setReg(unsigned Reg) {
209      assert((getKind() == Data || getKind() == Anti || getKind() == Output) &&
210             "setReg called on non-register dependence edge!");
211      assert((getKind() != Anti || Reg != 0) &&
212             "SDep::Anti edge cannot use the zero register!");
213      assert((getKind() != Output || Reg != 0) &&
214             "SDep::Output edge cannot use the zero register!");
215      Contents.Reg = Reg;
216    }
217  };
218
219  /// SUnit - Scheduling unit. This is a node in the scheduling DAG.
220  struct SUnit {
221  private:
222    SDNode *Node;                       // Representative node.
223    MachineInstr *Instr;                // Alternatively, a MachineInstr.
224  public:
225    SUnit *OrigNode;                    // If not this, the node from which
226                                        // this node was cloned.
227
228    // Preds/Succs - The SUnits before/after us in the graph.  The boolean value
229    // is true if the edge is a token chain edge, false if it is a value edge.
230    SmallVector<SDep, 4> Preds;  // All sunit predecessors.
231    SmallVector<SDep, 4> Succs;  // All sunit successors.
232
233    typedef SmallVector<SDep, 4>::iterator pred_iterator;
234    typedef SmallVector<SDep, 4>::iterator succ_iterator;
235    typedef SmallVector<SDep, 4>::const_iterator const_pred_iterator;
236    typedef SmallVector<SDep, 4>::const_iterator const_succ_iterator;
237
238    unsigned NodeNum;                   // Entry # of node in the node vector.
239    unsigned NodeQueueId;               // Queue id of node.
240    unsigned short Latency;             // Node latency.
241    short NumPreds;                     // # of SDep::Data preds.
242    short NumSuccs;                     // # of SDep::Data sucss.
243    short NumPredsLeft;                 // # of preds not scheduled.
244    short NumSuccsLeft;                 // # of succs not scheduled.
245    bool isTwoAddress     : 1;          // Is a two-address instruction.
246    bool isCommutable     : 1;          // Is a commutable instruction.
247    bool hasPhysRegDefs   : 1;          // Has physreg defs that are being used.
248    bool isPending        : 1;          // True once pending.
249    bool isAvailable      : 1;          // True once available.
250    bool isScheduled      : 1;          // True once scheduled.
251    bool isScheduleHigh   : 1;          // True if preferable to schedule high.
252    bool isCloned         : 1;          // True if this node has been cloned.
253  private:
254    bool isDepthCurrent   : 1;          // True if Depth is current.
255    bool isHeightCurrent  : 1;          // True if Height is current.
256    unsigned Depth;                     // Node depth.
257    unsigned Height;                    // Node height.
258  public:
259    const TargetRegisterClass *CopyDstRC; // Is a special copy node if not null.
260    const TargetRegisterClass *CopySrcRC;
261
262    /// SUnit - Construct an SUnit for pre-regalloc scheduling to represent
263    /// an SDNode and any nodes flagged to it.
264    SUnit(SDNode *node, unsigned nodenum)
265      : Node(node), Instr(0), OrigNode(0), NodeNum(nodenum), NodeQueueId(0),
266        Latency(0), NumPreds(0), NumSuccs(0), NumPredsLeft(0), NumSuccsLeft(0),
267        isTwoAddress(false), isCommutable(false), hasPhysRegDefs(false),
268        isPending(false), isAvailable(false), isScheduled(false),
269        isScheduleHigh(false), isCloned(false),
270        isDepthCurrent(false), isHeightCurrent(false), Depth(0), Height(0),
271        CopyDstRC(NULL), CopySrcRC(NULL) {}
272
273    /// SUnit - Construct an SUnit for post-regalloc scheduling to represent
274    /// a MachineInstr.
275    SUnit(MachineInstr *instr, unsigned nodenum)
276      : Node(0), Instr(instr), OrigNode(0), NodeNum(nodenum), NodeQueueId(0),
277        Latency(0), NumPreds(0), NumSuccs(0), NumPredsLeft(0), NumSuccsLeft(0),
278        isTwoAddress(false), isCommutable(false), hasPhysRegDefs(false),
279        isPending(false), isAvailable(false), isScheduled(false),
280        isScheduleHigh(false), isCloned(false),
281        isDepthCurrent(false), isHeightCurrent(false), Depth(0), Height(0),
282        CopyDstRC(NULL), CopySrcRC(NULL) {}
283
284    /// SUnit - Construct a placeholder SUnit.
285    SUnit()
286      : Node(0), Instr(0), OrigNode(0), NodeNum(~0u), NodeQueueId(0),
287        Latency(0), NumPreds(0), NumSuccs(0), NumPredsLeft(0), NumSuccsLeft(0),
288        isTwoAddress(false), isCommutable(false), hasPhysRegDefs(false),
289        isPending(false), isAvailable(false), isScheduled(false),
290        isScheduleHigh(false), isCloned(false),
291        isDepthCurrent(false), isHeightCurrent(false), Depth(0), Height(0),
292        CopyDstRC(NULL), CopySrcRC(NULL) {}
293
294    /// setNode - Assign the representative SDNode for this SUnit.
295    /// This may be used during pre-regalloc scheduling.
296    void setNode(SDNode *N) {
297      assert(!Instr && "Setting SDNode of SUnit with MachineInstr!");
298      Node = N;
299    }
300
301    /// getNode - Return the representative SDNode for this SUnit.
302    /// This may be used during pre-regalloc scheduling.
303    SDNode *getNode() const {
304      assert(!Instr && "Reading SDNode of SUnit with MachineInstr!");
305      return Node;
306    }
307
308    /// setInstr - Assign the instruction for the SUnit.
309    /// This may be used during post-regalloc scheduling.
310    void setInstr(MachineInstr *MI) {
311      assert(!Node && "Setting MachineInstr of SUnit with SDNode!");
312      Instr = MI;
313    }
314
315    /// getInstr - Return the representative MachineInstr for this SUnit.
316    /// This may be used during post-regalloc scheduling.
317    MachineInstr *getInstr() const {
318      assert(!Node && "Reading MachineInstr of SUnit with SDNode!");
319      return Instr;
320    }
321
322    /// addPred - This adds the specified edge as a pred of the current node if
323    /// not already.  It also adds the current node as a successor of the
324    /// specified node.
325    void addPred(const SDep &D);
326
327    /// removePred - This removes the specified edge as a pred of the current
328    /// node if it exists.  It also removes the current node as a successor of
329    /// the specified node.
330    void removePred(const SDep &D);
331
332    /// getDepth - Return the depth of this node, which is the length of the
333    /// maximum path up to any node with has no predecessors.
334    unsigned getDepth() const {
335      if (!isDepthCurrent) const_cast<SUnit *>(this)->ComputeDepth();
336      return Depth;
337    }
338
339    /// getHeight - Return the height of this node, which is the length of the
340    /// maximum path down to any node with has no successors.
341    unsigned getHeight() const {
342      if (!isHeightCurrent) const_cast<SUnit *>(this)->ComputeHeight();
343      return Height;
344    }
345
346    /// setDepthToAtLeast - If NewDepth is greater than this node's depth
347    /// value, set it to be the new depth value. This also recursively
348    /// marks successor nodes dirty.
349    void setDepthToAtLeast(unsigned NewDepth);
350
351    /// setDepthToAtLeast - If NewDepth is greater than this node's depth
352    /// value, set it to be the new height value. This also recursively
353    /// marks predecessor nodes dirty.
354    void setHeightToAtLeast(unsigned NewHeight);
355
356    /// setDepthDirty - Set a flag in this node to indicate that its
357    /// stored Depth value will require recomputation the next time
358    /// getDepth() is called.
359    void setDepthDirty();
360
361    /// setHeightDirty - Set a flag in this node to indicate that its
362    /// stored Height value will require recomputation the next time
363    /// getHeight() is called.
364    void setHeightDirty();
365
366    /// isPred - Test if node N is a predecessor of this node.
367    bool isPred(SUnit *N) {
368      for (unsigned i = 0, e = (unsigned)Preds.size(); i != e; ++i)
369        if (Preds[i].getSUnit() == N)
370          return true;
371      return false;
372    }
373
374    /// isSucc - Test if node N is a successor of this node.
375    bool isSucc(SUnit *N) {
376      for (unsigned i = 0, e = (unsigned)Succs.size(); i != e; ++i)
377        if (Succs[i].getSUnit() == N)
378          return true;
379      return false;
380    }
381
382    void dump(const ScheduleDAG *G) const;
383    void dumpAll(const ScheduleDAG *G) const;
384    void print(raw_ostream &O, const ScheduleDAG *G) const;
385
386  private:
387    void ComputeDepth();
388    void ComputeHeight();
389  };
390
391  //===--------------------------------------------------------------------===//
392  /// SchedulingPriorityQueue - This interface is used to plug different
393  /// priorities computation algorithms into the list scheduler. It implements
394  /// the interface of a standard priority queue, where nodes are inserted in
395  /// arbitrary order and returned in priority order.  The computation of the
396  /// priority and the representation of the queue are totally up to the
397  /// implementation to decide.
398  ///
399  class SchedulingPriorityQueue {
400  public:
401    virtual ~SchedulingPriorityQueue() {}
402
403    virtual void initNodes(std::vector<SUnit> &SUnits) = 0;
404    virtual void addNode(const SUnit *SU) = 0;
405    virtual void updateNode(const SUnit *SU) = 0;
406    virtual void releaseState() = 0;
407
408    virtual unsigned size() const = 0;
409    virtual bool empty() const = 0;
410    virtual void push(SUnit *U) = 0;
411
412    virtual void push_all(const std::vector<SUnit *> &Nodes) = 0;
413    virtual SUnit *pop() = 0;
414
415    virtual void remove(SUnit *SU) = 0;
416
417    /// ScheduledNode - As each node is scheduled, this method is invoked.  This
418    /// allows the priority function to adjust the priority of related
419    /// unscheduled nodes, for example.
420    ///
421    virtual void ScheduledNode(SUnit *) {}
422
423    virtual void UnscheduledNode(SUnit *) {}
424  };
425
426  class ScheduleDAG {
427  public:
428    MachineBasicBlock *BB;                // The block in which to insert instructions.
429    MachineBasicBlock::iterator InsertPos;// The position to insert instructions.
430    const TargetMachine &TM;              // Target processor
431    const TargetInstrInfo *TII;           // Target instruction information
432    const TargetRegisterInfo *TRI;        // Target processor register info
433    const TargetLowering *TLI;            // Target lowering info
434    MachineFunction &MF;                  // Machine function
435    MachineRegisterInfo &MRI;             // Virtual/real register map
436    MachineConstantPool *ConstPool;       // Target constant pool
437    std::vector<SUnit*> Sequence;         // The schedule. Null SUnit*'s
438                                          // represent noop instructions.
439    std::vector<SUnit> SUnits;            // The scheduling units.
440    SUnit EntrySU;                        // Special node for the region entry.
441    SUnit ExitSU;                         // Special node for the region exit.
442
443    explicit ScheduleDAG(MachineFunction &mf);
444
445    virtual ~ScheduleDAG();
446
447    /// viewGraph - Pop up a GraphViz/gv window with the ScheduleDAG rendered
448    /// using 'dot'.
449    ///
450    void viewGraph();
451
452    /// EmitSchedule - Insert MachineInstrs into the MachineBasicBlock
453    /// according to the order specified in Sequence.
454    ///
455    virtual MachineBasicBlock *EmitSchedule() = 0;
456
457    void dumpSchedule() const;
458
459    virtual void dumpNode(const SUnit *SU) const = 0;
460
461    /// getGraphNodeLabel - Return a label for an SUnit node in a visualization
462    /// of the ScheduleDAG.
463    virtual std::string getGraphNodeLabel(const SUnit *SU) const = 0;
464
465    /// addCustomGraphFeatures - Add custom features for a visualization of
466    /// the ScheduleDAG.
467    virtual void addCustomGraphFeatures(GraphWriter<ScheduleDAG*> &) const {}
468
469#ifndef NDEBUG
470    /// VerifySchedule - Verify that all SUnits were scheduled and that
471    /// their state is consistent.
472    void VerifySchedule(bool isBottomUp);
473#endif
474
475  protected:
476    /// Run - perform scheduling.
477    ///
478    void Run(MachineBasicBlock *bb, MachineBasicBlock::iterator insertPos);
479
480    /// BuildSchedGraph - Build SUnits and set up their Preds and Succs
481    /// to form the scheduling dependency graph.
482    ///
483    virtual void BuildSchedGraph() = 0;
484
485    /// ComputeLatency - Compute node latency.
486    ///
487    virtual void ComputeLatency(SUnit *SU) = 0;
488
489    /// Schedule - Order nodes according to selected style, filling
490    /// in the Sequence member.
491    ///
492    virtual void Schedule() = 0;
493
494    /// ForceUnitLatencies - Return true if all scheduling edges should be given a
495    /// latency value of one.  The default is to return false; schedulers may
496    /// override this as needed.
497    virtual bool ForceUnitLatencies() const { return false; }
498
499    /// EmitNoop - Emit a noop instruction.
500    ///
501    void EmitNoop();
502
503    void AddMemOperand(MachineInstr *MI, const MachineMemOperand &MO);
504
505    void EmitPhysRegCopy(SUnit *SU, DenseMap<SUnit*, unsigned> &VRBaseMap);
506
507  private:
508    /// EmitLiveInCopy - Emit a copy for a live in physical register. If the
509    /// physical register has only a single copy use, then coalesced the copy
510    /// if possible.
511    void EmitLiveInCopy(MachineBasicBlock *MBB,
512                        MachineBasicBlock::iterator &InsertPos,
513                        unsigned VirtReg, unsigned PhysReg,
514                        const TargetRegisterClass *RC,
515                        DenseMap<MachineInstr*, unsigned> &CopyRegMap);
516
517    /// EmitLiveInCopies - If this is the first basic block in the function,
518    /// and if it has live ins that need to be copied into vregs, emit the
519    /// copies into the top of the block.
520    void EmitLiveInCopies(MachineBasicBlock *MBB);
521  };
522
523  class SUnitIterator : public forward_iterator<SUnit, ptrdiff_t> {
524    SUnit *Node;
525    unsigned Operand;
526
527    SUnitIterator(SUnit *N, unsigned Op) : Node(N), Operand(Op) {}
528  public:
529    bool operator==(const SUnitIterator& x) const {
530      return Operand == x.Operand;
531    }
532    bool operator!=(const SUnitIterator& x) const { return !operator==(x); }
533
534    const SUnitIterator &operator=(const SUnitIterator &I) {
535      assert(I.Node == Node && "Cannot assign iterators to two different nodes!");
536      Operand = I.Operand;
537      return *this;
538    }
539
540    pointer operator*() const {
541      return Node->Preds[Operand].getSUnit();
542    }
543    pointer operator->() const { return operator*(); }
544
545    SUnitIterator& operator++() {                // Preincrement
546      ++Operand;
547      return *this;
548    }
549    SUnitIterator operator++(int) { // Postincrement
550      SUnitIterator tmp = *this; ++*this; return tmp;
551    }
552
553    static SUnitIterator begin(SUnit *N) { return SUnitIterator(N, 0); }
554    static SUnitIterator end  (SUnit *N) {
555      return SUnitIterator(N, (unsigned)N->Preds.size());
556    }
557
558    unsigned getOperand() const { return Operand; }
559    const SUnit *getNode() const { return Node; }
560    /// isCtrlDep - Test if this is not an SDep::Data dependence.
561    bool isCtrlDep() const {
562      return getSDep().isCtrl();
563    }
564    bool isArtificialDep() const {
565      return getSDep().isArtificial();
566    }
567    const SDep &getSDep() const {
568      return Node->Preds[Operand];
569    }
570  };
571
572  template <> struct GraphTraits<SUnit*> {
573    typedef SUnit NodeType;
574    typedef SUnitIterator ChildIteratorType;
575    static inline NodeType *getEntryNode(SUnit *N) { return N; }
576    static inline ChildIteratorType child_begin(NodeType *N) {
577      return SUnitIterator::begin(N);
578    }
579    static inline ChildIteratorType child_end(NodeType *N) {
580      return SUnitIterator::end(N);
581    }
582  };
583
584  template <> struct GraphTraits<ScheduleDAG*> : public GraphTraits<SUnit*> {
585    typedef std::vector<SUnit>::iterator nodes_iterator;
586    static nodes_iterator nodes_begin(ScheduleDAG *G) {
587      return G->SUnits.begin();
588    }
589    static nodes_iterator nodes_end(ScheduleDAG *G) {
590      return G->SUnits.end();
591    }
592  };
593
594  /// ScheduleDAGTopologicalSort is a class that computes a topological
595  /// ordering for SUnits and provides methods for dynamically updating
596  /// the ordering as new edges are added.
597  ///
598  /// This allows a very fast implementation of IsReachable, for example.
599  ///
600  class ScheduleDAGTopologicalSort {
601    /// SUnits - A reference to the ScheduleDAG's SUnits.
602    std::vector<SUnit> &SUnits;
603
604    /// Index2Node - Maps topological index to the node number.
605    std::vector<int> Index2Node;
606    /// Node2Index - Maps the node number to its topological index.
607    std::vector<int> Node2Index;
608    /// Visited - a set of nodes visited during a DFS traversal.
609    BitVector Visited;
610
611    /// DFS - make a DFS traversal and mark all nodes affected by the
612    /// edge insertion. These nodes will later get new topological indexes
613    /// by means of the Shift method.
614    void DFS(const SUnit *SU, int UpperBound, bool& HasLoop);
615
616    /// Shift - reassign topological indexes for the nodes in the DAG
617    /// to preserve the topological ordering.
618    void Shift(BitVector& Visited, int LowerBound, int UpperBound);
619
620    /// Allocate - assign the topological index to the node n.
621    void Allocate(int n, int index);
622
623  public:
624    explicit ScheduleDAGTopologicalSort(std::vector<SUnit> &SUnits);
625
626    /// InitDAGTopologicalSorting - create the initial topological
627    /// ordering from the DAG to be scheduled.
628    void InitDAGTopologicalSorting();
629
630    /// IsReachable - Checks if SU is reachable from TargetSU.
631    bool IsReachable(const SUnit *SU, const SUnit *TargetSU);
632
633    /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU
634    /// will create a cycle.
635    bool WillCreateCycle(SUnit *SU, SUnit *TargetSU);
636
637    /// AddPred - Updates the topological ordering to accomodate an edge
638    /// to be added from SUnit X to SUnit Y.
639    void AddPred(SUnit *Y, SUnit *X);
640
641    /// RemovePred - Updates the topological ordering to accomodate an
642    /// an edge to be removed from the specified node N from the predecessors
643    /// of the current node M.
644    void RemovePred(SUnit *M, SUnit *N);
645
646    typedef std::vector<int>::iterator iterator;
647    typedef std::vector<int>::const_iterator const_iterator;
648    iterator begin() { return Index2Node.begin(); }
649    const_iterator begin() const { return Index2Node.begin(); }
650    iterator end() { return Index2Node.end(); }
651    const_iterator end() const { return Index2Node.end(); }
652
653    typedef std::vector<int>::reverse_iterator reverse_iterator;
654    typedef std::vector<int>::const_reverse_iterator const_reverse_iterator;
655    reverse_iterator rbegin() { return Index2Node.rbegin(); }
656    const_reverse_iterator rbegin() const { return Index2Node.rbegin(); }
657    reverse_iterator rend() { return Index2Node.rend(); }
658    const_reverse_iterator rend() const { return Index2Node.rend(); }
659  };
660}
661
662#endif
663