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