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