Get rid of the EdgeMapping map. Instead, just check for BasicBlock
[oota-llvm.git] / include / llvm / CodeGen / ScheduleDAG.h
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
25 namespace llvm {
26   class AliasAnalysis;
27   class SUnit;
28   class MachineConstantPool;
29   class MachineFunction;
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     /// setLatency - Set the latency for this edge.
149     void setLatency(unsigned Lat) {
150       Latency = Lat;
151     }
152
153     //// getSUnit - Return the SUnit to which this edge points.
154     SUnit *getSUnit() const {
155       return Dep.getPointer();
156     }
157
158     //// setSUnit - Assign the SUnit to which this edge points.
159     void setSUnit(SUnit *SU) {
160       Dep.setPointer(SU);
161     }
162
163     /// getKind - Return an enum value representing the kind of the dependence.
164     Kind getKind() const {
165       return Dep.getInt();
166     }
167
168     /// isCtrl - Shorthand for getKind() != SDep::Data.
169     bool isCtrl() const {
170       return getKind() != Data;
171     }
172
173     /// isNormalMemory - Test if this is an Order dependence between two
174     /// memory accesses where both sides of the dependence access memory
175     /// in non-volatile and fully modeled ways.
176     bool isNormalMemory() const {
177       return getKind() == Order && Contents.Order.isNormalMemory;
178     }
179
180     /// isMustAlias - Test if this is an Order dependence that is marked
181     /// as "must alias", meaning that the SUnits at either end of the edge
182     /// have a memory dependence on a known memory location.
183     bool isMustAlias() const {
184       return getKind() == Order && Contents.Order.isMustAlias;
185     }
186
187     /// isArtificial - Test if this is an Order dependence that is marked
188     /// as "artificial", meaning it isn't necessary for correctness.
189     bool isArtificial() const {
190       return getKind() == Order && Contents.Order.isArtificial;
191     }
192
193     /// isAssignedRegDep - Test if this is a Data dependence that is
194     /// associated with a register.
195     bool isAssignedRegDep() const {
196       return getKind() == Data && Contents.Reg != 0;
197     }
198
199     /// getReg - Return the register associated with this edge. This is
200     /// only valid on Data, Anti, and Output edges. On Data edges, this
201     /// value may be zero, meaning there is no associated register.
202     unsigned getReg() const {
203       assert((getKind() == Data || getKind() == Anti || getKind() == Output) &&
204              "getReg called on non-register dependence edge!");
205       return Contents.Reg;
206     }
207
208     /// setReg - Assign the associated register for this edge. This is
209     /// only valid on Data, Anti, and Output edges. On Anti and Output
210     /// edges, this value must not be zero. On Data edges, the value may
211     /// be zero, which would mean that no specific register is associated
212     /// with this edge.
213     void setReg(unsigned Reg) {
214       assert((getKind() == Data || getKind() == Anti || getKind() == Output) &&
215              "setReg called on non-register dependence edge!");
216       assert((getKind() != Anti || Reg != 0) &&
217              "SDep::Anti edge cannot use the zero register!");
218       assert((getKind() != Output || Reg != 0) &&
219              "SDep::Output edge cannot use the zero register!");
220       Contents.Reg = Reg;
221     }
222   };
223
224   /// SUnit - Scheduling unit. This is a node in the scheduling DAG.
225   class SUnit {
226   private:
227     SDNode *Node;                       // Representative node.
228     MachineInstr *Instr;                // Alternatively, a MachineInstr.
229     MachineInstr *DbgInstr;             // A dbg_value referencing this.
230   public:
231     SUnit *OrigNode;                    // If not this, the node from which
232                                         // this node was cloned.
233     
234     // Preds/Succs - The SUnits before/after us in the graph.  The boolean value
235     // is true if the edge is a token chain edge, false if it is a value edge. 
236     SmallVector<SDep, 4> Preds;  // All sunit predecessors.
237     SmallVector<SDep, 4> Succs;  // All sunit successors.
238
239     typedef SmallVector<SDep, 4>::iterator pred_iterator;
240     typedef SmallVector<SDep, 4>::iterator succ_iterator;
241     typedef SmallVector<SDep, 4>::const_iterator const_pred_iterator;
242     typedef SmallVector<SDep, 4>::const_iterator const_succ_iterator;
243     
244     unsigned NodeNum;                   // Entry # of node in the node vector.
245     unsigned NodeQueueId;               // Queue id of node.
246     unsigned short Latency;             // Node latency.
247     unsigned NumPreds;                  // # of SDep::Data preds.
248     unsigned NumSuccs;                  // # of SDep::Data sucss.
249     unsigned NumPredsLeft;              // # of preds not scheduled.
250     unsigned NumSuccsLeft;              // # of succs not scheduled.
251     bool isTwoAddress     : 1;          // Is a two-address instruction.
252     bool isCommutable     : 1;          // Is a commutable instruction.
253     bool hasPhysRegDefs   : 1;          // Has physreg defs that are being used.
254     bool hasPhysRegClobbers : 1;        // Has any physreg defs, used or not.
255     bool isPending        : 1;          // True once pending.
256     bool isAvailable      : 1;          // True once available.
257     bool isScheduled      : 1;          // True once scheduled.
258     bool isScheduleHigh   : 1;          // True if preferable to schedule high.
259     bool isCloned         : 1;          // True if this node has been cloned.
260   private:
261     bool isDepthCurrent   : 1;          // True if Depth is current.
262     bool isHeightCurrent  : 1;          // True if Height is current.
263     unsigned Depth;                     // Node depth.
264     unsigned Height;                    // Node height.
265   public:
266     const TargetRegisterClass *CopyDstRC; // Is a special copy node if not null.
267     const TargetRegisterClass *CopySrcRC;
268     
269     /// SUnit - Construct an SUnit for pre-regalloc scheduling to represent
270     /// an SDNode and any nodes flagged to it.
271     SUnit(SDNode *node, unsigned nodenum)
272       : Node(node), Instr(0), DbgInstr(0), OrigNode(0), NodeNum(nodenum),
273         NodeQueueId(0),  Latency(0), NumPreds(0), NumSuccs(0), NumPredsLeft(0),
274         NumSuccsLeft(0), isTwoAddress(false), isCommutable(false),
275         hasPhysRegDefs(false), hasPhysRegClobbers(false),
276         isPending(false), isAvailable(false), isScheduled(false),
277         isScheduleHigh(false), isCloned(false),
278         isDepthCurrent(false), isHeightCurrent(false), Depth(0), Height(0),
279         CopyDstRC(NULL), CopySrcRC(NULL) {}
280
281     /// SUnit - Construct an SUnit for post-regalloc scheduling to represent
282     /// a MachineInstr.
283     SUnit(MachineInstr *instr, unsigned nodenum)
284       : Node(0), Instr(instr), DbgInstr(0), OrigNode(0), NodeNum(nodenum),
285         NodeQueueId(0), Latency(0), NumPreds(0), NumSuccs(0), NumPredsLeft(0),
286         NumSuccsLeft(0), isTwoAddress(false), isCommutable(false),
287         hasPhysRegDefs(false), hasPhysRegClobbers(false),
288         isPending(false), isAvailable(false), isScheduled(false),
289         isScheduleHigh(false), isCloned(false),
290         isDepthCurrent(false), isHeightCurrent(false), Depth(0), Height(0),
291         CopyDstRC(NULL), CopySrcRC(NULL) {}
292
293     /// SUnit - Construct a placeholder SUnit.
294     SUnit()
295       : Node(0), Instr(0), DbgInstr(0), OrigNode(0), NodeNum(~0u),
296         NodeQueueId(0), Latency(0), NumPreds(0), NumSuccs(0), NumPredsLeft(0),
297         NumSuccsLeft(0), isTwoAddress(false), isCommutable(false),
298         hasPhysRegDefs(false), hasPhysRegClobbers(false),
299         isPending(false), isAvailable(false), isScheduled(false),
300         isScheduleHigh(false), isCloned(false),
301         isDepthCurrent(false), isHeightCurrent(false), Depth(0), Height(0),
302         CopyDstRC(NULL), CopySrcRC(NULL) {}
303
304     /// setNode - Assign the representative SDNode for this SUnit.
305     /// This may be used during pre-regalloc scheduling.
306     void setNode(SDNode *N) {
307       assert(!Instr && "Setting SDNode of SUnit with MachineInstr!");
308       Node = N;
309     }
310
311     /// getNode - Return the representative SDNode for this SUnit.
312     /// This may be used during pre-regalloc scheduling.
313     SDNode *getNode() const {
314       assert(!Instr && "Reading SDNode of SUnit with MachineInstr!");
315       return Node;
316     }
317
318     /// setInstr - Assign the instruction for the SUnit.
319     /// This may be used during post-regalloc scheduling.
320     void setInstr(MachineInstr *MI) {
321       assert(!Node && "Setting MachineInstr of SUnit with SDNode!");
322       Instr = MI;
323     }
324
325     /// getInstr - Return the representative MachineInstr for this SUnit.
326     /// This may be used during post-regalloc scheduling.
327     MachineInstr *getInstr() const {
328       assert(!Node && "Reading MachineInstr of SUnit with SDNode!");
329       return Instr;
330     }
331
332     /// setDbgInstr - Assign the debug instruction for the SUnit.
333     /// This may be used during post-regalloc scheduling.
334     void setDbgInstr(MachineInstr *MI) {
335       assert(!Node && "Setting debug MachineInstr of SUnit with SDNode!");
336       DbgInstr = MI;
337     }
338
339     /// getDbgInstr - Return the debug MachineInstr for this SUnit.
340     /// This may be used during post-regalloc scheduling.
341     MachineInstr *getDbgInstr() const {
342       assert(!Node && "Reading debug MachineInstr of SUnit with SDNode!");
343       return DbgInstr;
344     }
345
346     /// addPred - This adds the specified edge as a pred of the current node if
347     /// not already.  It also adds the current node as a successor of the
348     /// specified node.
349     void addPred(const SDep &D);
350
351     /// removePred - This removes the specified edge as a pred of the current
352     /// node if it exists.  It also removes the current node as a successor of
353     /// the specified node.
354     void removePred(const SDep &D);
355
356     /// getDepth - Return the depth of this node, which is the length of the
357     /// maximum path up to any node with has no predecessors.
358     unsigned getDepth() const {
359       if (!isDepthCurrent) 
360         const_cast<SUnit *>(this)->ComputeDepth();
361       return Depth;
362     }
363
364     /// getHeight - Return the height of this node, which is the length of the
365     /// maximum path down to any node with has no successors.
366     unsigned getHeight() const {
367       if (!isHeightCurrent) 
368         const_cast<SUnit *>(this)->ComputeHeight();
369       return Height;
370     }
371
372     /// setDepthToAtLeast - If NewDepth is greater than this node's
373     /// depth value, set it to be the new depth value. This also
374     /// recursively marks successor nodes dirty.
375     void setDepthToAtLeast(unsigned NewDepth);
376
377     /// setDepthToAtLeast - If NewDepth is greater than this node's
378     /// depth value, set it to be the new height value. This also
379     /// recursively marks predecessor nodes dirty.
380     void setHeightToAtLeast(unsigned NewHeight);
381
382     /// setDepthDirty - Set a flag in this node to indicate that its
383     /// stored Depth value will require recomputation the next time
384     /// getDepth() is called.
385     void setDepthDirty();
386
387     /// setHeightDirty - Set a flag in this node to indicate that its
388     /// stored Height value will require recomputation the next time
389     /// getHeight() is called.
390     void setHeightDirty();
391
392     /// isPred - Test if node N is a predecessor of this node.
393     bool isPred(SUnit *N) {
394       for (unsigned i = 0, e = (unsigned)Preds.size(); i != e; ++i)
395         if (Preds[i].getSUnit() == N)
396           return true;
397       return false;
398     }
399     
400     /// isSucc - Test if node N is a successor of this node.
401     bool isSucc(SUnit *N) {
402       for (unsigned i = 0, e = (unsigned)Succs.size(); i != e; ++i)
403         if (Succs[i].getSUnit() == N)
404           return true;
405       return false;
406     }
407     
408     void dump(const ScheduleDAG *G) const;
409     void dumpAll(const ScheduleDAG *G) const;
410     void print(raw_ostream &O, const ScheduleDAG *G) const;
411
412   private:
413     void ComputeDepth();
414     void ComputeHeight();
415   };
416
417   //===--------------------------------------------------------------------===//
418   /// SchedulingPriorityQueue - This interface is used to plug different
419   /// priorities computation algorithms into the list scheduler. It implements
420   /// the interface of a standard priority queue, where nodes are inserted in 
421   /// arbitrary order and returned in priority order.  The computation of the
422   /// priority and the representation of the queue are totally up to the
423   /// implementation to decide.
424   /// 
425   class SchedulingPriorityQueue {
426   public:
427     virtual ~SchedulingPriorityQueue() {}
428   
429     virtual void initNodes(std::vector<SUnit> &SUnits) = 0;
430     virtual void addNode(const SUnit *SU) = 0;
431     virtual void updateNode(const SUnit *SU) = 0;
432     virtual void releaseState() = 0;
433
434     virtual unsigned size() const = 0;
435     virtual bool empty() const = 0;
436     virtual void push(SUnit *U) = 0;
437   
438     virtual void push_all(const std::vector<SUnit *> &Nodes) = 0;
439     virtual SUnit *pop() = 0;
440
441     virtual void remove(SUnit *SU) = 0;
442
443     /// ScheduledNode - As each node is scheduled, this method is invoked.  This
444     /// allows the priority function to adjust the priority of related
445     /// unscheduled nodes, for example.
446     ///
447     virtual void ScheduledNode(SUnit *) {}
448
449     virtual void UnscheduledNode(SUnit *) {}
450   };
451
452   class ScheduleDAG {
453   public:
454     MachineBasicBlock *BB;          // The block in which to insert instructions
455     MachineBasicBlock::iterator InsertPos;// The position to insert instructions
456     const TargetMachine &TM;              // Target processor
457     const TargetInstrInfo *TII;           // Target instruction information
458     const TargetRegisterInfo *TRI;        // Target processor register info
459     const TargetLowering *TLI;            // Target lowering info
460     MachineFunction &MF;                  // Machine function
461     MachineRegisterInfo &MRI;             // Virtual/real register map
462     std::vector<SUnit*> Sequence;         // The schedule. Null SUnit*'s
463                                           // represent noop instructions.
464     std::vector<SUnit> SUnits;            // The scheduling units.
465     SUnit EntrySU;                        // Special node for the region entry.
466     SUnit ExitSU;                         // Special node for the region exit.
467
468     explicit ScheduleDAG(MachineFunction &mf);
469
470     virtual ~ScheduleDAG();
471
472     /// viewGraph - Pop up a GraphViz/gv window with the ScheduleDAG rendered
473     /// using 'dot'.
474     ///
475     void viewGraph();
476   
477     /// EmitSchedule - Insert MachineInstrs into the MachineBasicBlock
478     /// according to the order specified in Sequence.
479     ///
480     virtual MachineBasicBlock *EmitSchedule() = 0;
481
482     void dumpSchedule() const;
483
484     virtual void dumpNode(const SUnit *SU) const = 0;
485
486     /// getGraphNodeLabel - Return a label for an SUnit node in a visualization
487     /// of the ScheduleDAG.
488     virtual std::string getGraphNodeLabel(const SUnit *SU) const = 0;
489
490     /// addCustomGraphFeatures - Add custom features for a visualization of
491     /// the ScheduleDAG.
492     virtual void addCustomGraphFeatures(GraphWriter<ScheduleDAG*> &) const {}
493
494 #ifndef NDEBUG
495     /// VerifySchedule - Verify that all SUnits were scheduled and that
496     /// their state is consistent.
497     void VerifySchedule(bool isBottomUp);
498 #endif
499
500   protected:
501     /// Run - perform scheduling.
502     ///
503     void Run(MachineBasicBlock *bb, MachineBasicBlock::iterator insertPos);
504
505     /// BuildSchedGraph - Build SUnits and set up their Preds and Succs
506     /// to form the scheduling dependency graph.
507     ///
508     virtual void BuildSchedGraph(AliasAnalysis *AA) = 0;
509
510     /// ComputeLatency - Compute node latency.
511     ///
512     virtual void ComputeLatency(SUnit *SU) = 0;
513
514     /// ComputeOperandLatency - Override dependence edge latency using
515     /// operand use/def information
516     ///
517     virtual void ComputeOperandLatency(SUnit *, SUnit *,
518                                        SDep&) const { }
519
520     /// Schedule - Order nodes according to selected style, filling
521     /// in the Sequence member.
522     ///
523     virtual void Schedule() = 0;
524
525     /// ForceUnitLatencies - Return true if all scheduling edges should be given
526     /// a latency value of one.  The default is to return false; schedulers may
527     /// override this as needed.
528     virtual bool ForceUnitLatencies() const { return false; }
529
530     /// EmitNoop - Emit a noop instruction.
531     ///
532     void EmitNoop();
533
534     void EmitPhysRegCopy(SUnit *SU, DenseMap<SUnit*, unsigned> &VRBaseMap);
535   };
536
537   class SUnitIterator : public std::iterator<std::forward_iterator_tag,
538                                              SUnit, ptrdiff_t> {
539     SUnit *Node;
540     unsigned Operand;
541
542     SUnitIterator(SUnit *N, unsigned Op) : Node(N), Operand(Op) {}
543   public:
544     bool operator==(const SUnitIterator& x) const {
545       return Operand == x.Operand;
546     }
547     bool operator!=(const SUnitIterator& x) const { return !operator==(x); }
548
549     const SUnitIterator &operator=(const SUnitIterator &I) {
550       assert(I.Node==Node && "Cannot assign iterators to two different nodes!");
551       Operand = I.Operand;
552       return *this;
553     }
554
555     pointer operator*() const {
556       return Node->Preds[Operand].getSUnit();
557     }
558     pointer operator->() const { return operator*(); }
559
560     SUnitIterator& operator++() {                // Preincrement
561       ++Operand;
562       return *this;
563     }
564     SUnitIterator operator++(int) { // Postincrement
565       SUnitIterator tmp = *this; ++*this; return tmp;
566     }
567
568     static SUnitIterator begin(SUnit *N) { return SUnitIterator(N, 0); }
569     static SUnitIterator end  (SUnit *N) {
570       return SUnitIterator(N, (unsigned)N->Preds.size());
571     }
572
573     unsigned getOperand() const { return Operand; }
574     const SUnit *getNode() const { return Node; }
575     /// isCtrlDep - Test if this is not an SDep::Data dependence.
576     bool isCtrlDep() const {
577       return getSDep().isCtrl();
578     }
579     bool isArtificialDep() const {
580       return getSDep().isArtificial();
581     }
582     const SDep &getSDep() const {
583       return Node->Preds[Operand];
584     }
585   };
586
587   template <> struct GraphTraits<SUnit*> {
588     typedef SUnit NodeType;
589     typedef SUnitIterator ChildIteratorType;
590     static inline NodeType *getEntryNode(SUnit *N) { return N; }
591     static inline ChildIteratorType child_begin(NodeType *N) {
592       return SUnitIterator::begin(N);
593     }
594     static inline ChildIteratorType child_end(NodeType *N) {
595       return SUnitIterator::end(N);
596     }
597   };
598
599   template <> struct GraphTraits<ScheduleDAG*> : public GraphTraits<SUnit*> {
600     typedef std::vector<SUnit>::iterator nodes_iterator;
601     static nodes_iterator nodes_begin(ScheduleDAG *G) {
602       return G->SUnits.begin();
603     }
604     static nodes_iterator nodes_end(ScheduleDAG *G) {
605       return G->SUnits.end();
606     }
607   };
608
609   /// ScheduleDAGTopologicalSort is a class that computes a topological
610   /// ordering for SUnits and provides methods for dynamically updating
611   /// the ordering as new edges are added.
612   ///
613   /// This allows a very fast implementation of IsReachable, for example.
614   ///
615   class ScheduleDAGTopologicalSort {
616     /// SUnits - A reference to the ScheduleDAG's SUnits.
617     std::vector<SUnit> &SUnits;
618
619     /// Index2Node - Maps topological index to the node number.
620     std::vector<int> Index2Node;
621     /// Node2Index - Maps the node number to its topological index.
622     std::vector<int> Node2Index;
623     /// Visited - a set of nodes visited during a DFS traversal.
624     BitVector Visited;
625
626     /// DFS - make a DFS traversal and mark all nodes affected by the 
627     /// edge insertion. These nodes will later get new topological indexes
628     /// by means of the Shift method.
629     void DFS(const SUnit *SU, int UpperBound, bool& HasLoop);
630
631     /// Shift - reassign topological indexes for the nodes in the DAG
632     /// to preserve the topological ordering.
633     void Shift(BitVector& Visited, int LowerBound, int UpperBound);
634
635     /// Allocate - assign the topological index to the node n.
636     void Allocate(int n, int index);
637
638   public:
639     explicit ScheduleDAGTopologicalSort(std::vector<SUnit> &SUnits);
640
641     /// InitDAGTopologicalSorting - create the initial topological 
642     /// ordering from the DAG to be scheduled.
643     void InitDAGTopologicalSorting();
644
645     /// IsReachable - Checks if SU is reachable from TargetSU.
646     bool IsReachable(const SUnit *SU, const SUnit *TargetSU);
647
648     /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU
649     /// will create a cycle.
650     bool WillCreateCycle(SUnit *SU, SUnit *TargetSU);
651
652     /// AddPred - Updates the topological ordering to accomodate an edge
653     /// to be added from SUnit X to SUnit Y.
654     void AddPred(SUnit *Y, SUnit *X);
655
656     /// RemovePred - Updates the topological ordering to accomodate an
657     /// an edge to be removed from the specified node N from the predecessors
658     /// of the current node M.
659     void RemovePred(SUnit *M, SUnit *N);
660
661     typedef std::vector<int>::iterator iterator;
662     typedef std::vector<int>::const_iterator const_iterator;
663     iterator begin() { return Index2Node.begin(); }
664     const_iterator begin() const { return Index2Node.begin(); }
665     iterator end() { return Index2Node.end(); }
666     const_iterator end() const { return Index2Node.end(); }
667
668     typedef std::vector<int>::reverse_iterator reverse_iterator;
669     typedef std::vector<int>::const_reverse_iterator const_reverse_iterator;
670     reverse_iterator rbegin() { return Index2Node.rbegin(); }
671     const_reverse_iterator rbegin() const { return Index2Node.rbegin(); }
672     reverse_iterator rend() { return Index2Node.rend(); }
673     const_reverse_iterator rend() const { return Index2Node.rend(); }
674   };
675 }
676
677 #endif