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