Make the Node member of SUnit private, and add accessors.
[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 SelectionDAG-based instruction scheduler.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_CODEGEN_SCHEDULEDAG_H
16 #define LLVM_CODEGEN_SCHEDULEDAG_H
17
18 #include "llvm/CodeGen/MachineBasicBlock.h"
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/GraphTraits.h"
22 #include "llvm/ADT/SmallSet.h"
23
24 namespace llvm {
25   struct InstrStage;
26   struct SUnit;
27   class MachineConstantPool;
28   class MachineFunction;
29   class MachineModuleInfo;
30   class MachineRegisterInfo;
31   class MachineInstr;
32   class TargetRegisterInfo;
33   class SelectionDAG;
34   class SelectionDAGISel;
35   class TargetInstrInfo;
36   class TargetInstrDesc;
37   class TargetLowering;
38   class TargetMachine;
39   class TargetRegisterClass;
40
41   /// HazardRecognizer - This determines whether or not an instruction can be
42   /// issued this cycle, and whether or not a noop needs to be inserted to handle
43   /// the hazard.
44   class HazardRecognizer {
45   public:
46     virtual ~HazardRecognizer();
47     
48     enum HazardType {
49       NoHazard,      // This instruction can be emitted at this cycle.
50       Hazard,        // This instruction can't be emitted at this cycle.
51       NoopHazard     // This instruction can't be emitted, and needs noops.
52     };
53     
54     /// getHazardType - Return the hazard type of emitting this node.  There are
55     /// three possible results.  Either:
56     ///  * NoHazard: it is legal to issue this instruction on this cycle.
57     ///  * Hazard: issuing this instruction would stall the machine.  If some
58     ///     other instruction is available, issue it first.
59     ///  * NoopHazard: issuing this instruction would break the program.  If
60     ///     some other instruction can be issued, do so, otherwise issue a noop.
61     virtual HazardType getHazardType(SDNode *) {
62       return NoHazard;
63     }
64     
65     /// EmitInstruction - This callback is invoked when an instruction is
66     /// emitted, to advance the hazard state.
67     virtual void EmitInstruction(SDNode *) {}
68     
69     /// AdvanceCycle - This callback is invoked when no instructions can be
70     /// issued on this cycle without a hazard.  This should increment the
71     /// internal state of the hazard recognizer so that previously "Hazard"
72     /// instructions will now not be hazards.
73     virtual void AdvanceCycle() {}
74     
75     /// EmitNoop - This callback is invoked when a noop was added to the
76     /// instruction stream.
77     virtual void EmitNoop() {}
78   };
79
80   /// SDep - Scheduling dependency. It keeps track of dependent nodes,
81   /// cost of the depdenency, etc.
82   struct SDep {
83     SUnit    *Dep;           // Dependent - either a predecessor or a successor.
84     unsigned  Reg;           // If non-zero, this dep is a phy register dependency.
85     int       Cost;          // Cost of the dependency.
86     bool      isCtrl    : 1; // True iff it's a control dependency.
87     bool      isSpecial : 1; // True iff it's a special ctrl dep added during sched.
88     SDep(SUnit *d, unsigned r, int t, bool c, bool s)
89       : Dep(d), Reg(r), Cost(t), isCtrl(c), isSpecial(s) {}
90   };
91
92   /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
93   /// a group of nodes flagged together.
94   struct SUnit {
95   private:
96     SDNode *Node;                       // Representative node.
97   public:
98     SmallVector<SDNode*,4> FlaggedNodes;// All nodes flagged to Node.
99     SUnit *OrigNode;                    // If not this, the node from which
100                                         // this node was cloned.
101     
102     // Preds/Succs - The SUnits before/after us in the graph.  The boolean value
103     // is true if the edge is a token chain edge, false if it is a value edge. 
104     SmallVector<SDep, 4> Preds;  // All sunit predecessors.
105     SmallVector<SDep, 4> Succs;  // All sunit successors.
106
107     typedef SmallVector<SDep, 4>::iterator pred_iterator;
108     typedef SmallVector<SDep, 4>::iterator succ_iterator;
109     typedef SmallVector<SDep, 4>::const_iterator const_pred_iterator;
110     typedef SmallVector<SDep, 4>::const_iterator const_succ_iterator;
111     
112     unsigned NodeNum;                   // Entry # of node in the node vector.
113     unsigned NodeQueueId;               // Queue id of node.
114     unsigned short Latency;             // Node latency.
115     short NumPreds;                     // # of preds.
116     short NumSuccs;                     // # of sucss.
117     short NumPredsLeft;                 // # of preds not scheduled.
118     short NumSuccsLeft;                 // # of succs not scheduled.
119     bool isTwoAddress     : 1;          // Is a two-address instruction.
120     bool isCommutable     : 1;          // Is a commutable instruction.
121     bool hasPhysRegDefs   : 1;          // Has physreg defs that are being used.
122     bool isPending        : 1;          // True once pending.
123     bool isAvailable      : 1;          // True once available.
124     bool isScheduled      : 1;          // True once scheduled.
125     unsigned CycleBound;                // Upper/lower cycle to be scheduled at.
126     unsigned Cycle;                     // Once scheduled, the cycle of the op.
127     unsigned Depth;                     // Node depth;
128     unsigned Height;                    // Node height;
129     const TargetRegisterClass *CopyDstRC; // Is a special copy node if not null.
130     const TargetRegisterClass *CopySrcRC;
131     
132     SUnit(SDNode *node, unsigned nodenum)
133       : Node(node), OrigNode(0), NodeNum(nodenum), NodeQueueId(0), Latency(0),
134         NumPreds(0), NumSuccs(0), NumPredsLeft(0), NumSuccsLeft(0),
135         isTwoAddress(false), isCommutable(false), hasPhysRegDefs(false),
136         isPending(false), isAvailable(false), isScheduled(false),
137         CycleBound(0), Cycle(0), Depth(0), Height(0),
138         CopyDstRC(NULL), CopySrcRC(NULL) {}
139
140     /// setNode - Assign the representative SDNode for this SUnit.
141     void setNode(SDNode *N) { Node = N; }
142
143     /// getNode - Return the representative SDNode for this SUnit.
144     SDNode *getNode() const { return Node; }
145
146     /// addPred - This adds the specified node as a pred of the current node if
147     /// not already.  This returns true if this is a new pred.
148     bool addPred(SUnit *N, bool isCtrl, bool isSpecial,
149                  unsigned PhyReg = 0, int Cost = 1) {
150       for (unsigned i = 0, e = (unsigned)Preds.size(); i != e; ++i)
151         if (Preds[i].Dep == N &&
152             Preds[i].isCtrl == isCtrl && Preds[i].isSpecial == isSpecial)
153           return false;
154       Preds.push_back(SDep(N, PhyReg, Cost, isCtrl, isSpecial));
155       N->Succs.push_back(SDep(this, PhyReg, Cost, isCtrl, isSpecial));
156       if (!isCtrl) {
157         ++NumPreds;
158         ++N->NumSuccs;
159       }
160       if (!N->isScheduled)
161         ++NumPredsLeft;
162       if (!isScheduled)
163         ++N->NumSuccsLeft;
164       return true;
165     }
166
167     bool removePred(SUnit *N, bool isCtrl, bool isSpecial) {
168       for (SmallVector<SDep, 4>::iterator I = Preds.begin(), E = Preds.end();
169            I != E; ++I)
170         if (I->Dep == N && I->isCtrl == isCtrl && I->isSpecial == isSpecial) {
171           bool FoundSucc = false;
172           for (SmallVector<SDep, 4>::iterator II = N->Succs.begin(),
173                  EE = N->Succs.end(); II != EE; ++II)
174             if (II->Dep == this &&
175                 II->isCtrl == isCtrl && II->isSpecial == isSpecial) {
176               FoundSucc = true;
177               N->Succs.erase(II);
178               break;
179             }
180           assert(FoundSucc && "Mismatching preds / succs lists!");
181           Preds.erase(I);
182           if (!isCtrl) {
183             --NumPreds;
184             --N->NumSuccs;
185           }
186           if (!N->isScheduled)
187             --NumPredsLeft;
188           if (!isScheduled)
189             --N->NumSuccsLeft;
190           return true;
191         }
192       return false;
193     }
194
195     bool isPred(SUnit *N) {
196       for (unsigned i = 0, e = (unsigned)Preds.size(); i != e; ++i)
197         if (Preds[i].Dep == N)
198           return true;
199       return false;
200     }
201     
202     bool isSucc(SUnit *N) {
203       for (unsigned i = 0, e = (unsigned)Succs.size(); i != e; ++i)
204         if (Succs[i].Dep == N)
205           return true;
206       return false;
207     }
208     
209     void dump(const SelectionDAG *G) const;
210     void dumpAll(const SelectionDAG *G) const;
211   };
212
213   //===--------------------------------------------------------------------===//
214   /// SchedulingPriorityQueue - This interface is used to plug different
215   /// priorities computation algorithms into the list scheduler. It implements
216   /// the interface of a standard priority queue, where nodes are inserted in 
217   /// arbitrary order and returned in priority order.  The computation of the
218   /// priority and the representation of the queue are totally up to the
219   /// implementation to decide.
220   /// 
221   class SchedulingPriorityQueue {
222   public:
223     virtual ~SchedulingPriorityQueue() {}
224   
225     virtual void initNodes(std::vector<SUnit> &SUnits) = 0;
226     virtual void addNode(const SUnit *SU) = 0;
227     virtual void updateNode(const SUnit *SU) = 0;
228     virtual void releaseState() = 0;
229
230     virtual unsigned size() const = 0;
231     virtual bool empty() const = 0;
232     virtual void push(SUnit *U) = 0;
233   
234     virtual void push_all(const std::vector<SUnit *> &Nodes) = 0;
235     virtual SUnit *pop() = 0;
236
237     virtual void remove(SUnit *SU) = 0;
238
239     /// ScheduledNode - As each node is scheduled, this method is invoked.  This
240     /// allows the priority function to adjust the priority of related
241     /// unscheduled nodes, for example.
242     ///
243     virtual void ScheduledNode(SUnit *) {}
244
245     virtual void UnscheduledNode(SUnit *) {}
246   };
247
248   class ScheduleDAG {
249   public:
250     SelectionDAG *DAG;                    // DAG of the current basic block
251     MachineBasicBlock *BB;                // Current basic block
252     const TargetMachine &TM;              // Target processor
253     const TargetInstrInfo *TII;           // Target instruction information
254     const TargetRegisterInfo *TRI;        // Target processor register info
255     TargetLowering *TLI;                  // Target lowering info
256     MachineFunction *MF;                  // Machine function
257     MachineRegisterInfo &MRI;             // Virtual/real register map
258     MachineConstantPool *ConstPool;       // Target constant pool
259     std::vector<SUnit*> Sequence;         // The schedule. Null SUnit*'s
260                                           // represent noop instructions.
261     std::vector<SUnit> SUnits;            // The scheduling units.
262     SmallSet<SDNode*, 16> CommuteSet;     // Nodes that should be commuted.
263
264     ScheduleDAG(SelectionDAG *dag, MachineBasicBlock *bb,
265                 const TargetMachine &tm);
266
267     virtual ~ScheduleDAG() {}
268
269     /// viewGraph - Pop up a GraphViz/gv window with the ScheduleDAG rendered
270     /// using 'dot'.
271     ///
272     void viewGraph();
273   
274     /// Run - perform scheduling.
275     ///
276     void Run();
277
278     /// isPassiveNode - Return true if the node is a non-scheduled leaf.
279     ///
280     static bool isPassiveNode(SDNode *Node) {
281       if (isa<ConstantSDNode>(Node))       return true;
282       if (isa<ConstantFPSDNode>(Node))     return true;
283       if (isa<RegisterSDNode>(Node))       return true;
284       if (isa<GlobalAddressSDNode>(Node))  return true;
285       if (isa<BasicBlockSDNode>(Node))     return true;
286       if (isa<FrameIndexSDNode>(Node))     return true;
287       if (isa<ConstantPoolSDNode>(Node))   return true;
288       if (isa<JumpTableSDNode>(Node))      return true;
289       if (isa<ExternalSymbolSDNode>(Node)) return true;
290       if (isa<MemOperandSDNode>(Node))     return true;
291       if (Node->getOpcode() == ISD::EntryToken) return true;
292       return false;
293     }
294
295     /// NewSUnit - Creates a new SUnit and return a ptr to it.
296     ///
297     SUnit *NewSUnit(SDNode *N) {
298       SUnits.push_back(SUnit(N, (unsigned)SUnits.size()));
299       SUnits.back().OrigNode = &SUnits.back();
300       return &SUnits.back();
301     }
302
303     /// Clone - Creates a clone of the specified SUnit. It does not copy the
304     /// predecessors / successors info nor the temporary scheduling states.
305     SUnit *Clone(SUnit *N);
306     
307     /// BuildSchedUnits - Build SUnits from the selection dag that we are input.
308     /// This SUnit graph is similar to the SelectionDAG, but represents flagged
309     /// together nodes with a single SUnit.
310     void BuildSchedUnits();
311
312     /// ComputeLatency - Compute node latency.
313     ///
314     void ComputeLatency(SUnit *SU);
315
316     /// CalculateDepths, CalculateHeights - Calculate node depth / height.
317     ///
318     void CalculateDepths();
319     void CalculateHeights();
320
321     /// CountResults - The results of target nodes have register or immediate
322     /// operands first, then an optional chain, and optional flag operands
323     /// (which do not go into the machine instrs.)
324     static unsigned CountResults(SDNode *Node);
325
326     /// CountOperands - The inputs to target nodes have any actual inputs first,
327     /// followed by special operands that describe memory references, then an
328     /// optional chain operand, then flag operands.  Compute the number of
329     /// actual operands that will go into the resulting MachineInstr.
330     static unsigned CountOperands(SDNode *Node);
331
332     /// ComputeMemOperandsEnd - Find the index one past the last
333     /// MemOperandSDNode operand
334     static unsigned ComputeMemOperandsEnd(SDNode *Node);
335
336     /// EmitNode - Generate machine code for an node and needed dependencies.
337     /// VRBaseMap contains, for each already emitted node, the first virtual
338     /// register number for the results of the node.
339     ///
340     void EmitNode(SDNode *Node, bool IsClone,
341                   DenseMap<SDValue, unsigned> &VRBaseMap);
342     
343     /// EmitNoop - Emit a noop instruction.
344     ///
345     void EmitNoop();
346
347     MachineBasicBlock *EmitSchedule();
348
349     void dumpSchedule() const;
350
351     /// Schedule - Order nodes according to selected style, filling
352     /// in the Sequence member.
353     ///
354     virtual void Schedule() = 0;
355
356   private:
357     /// EmitSubregNode - Generate machine code for subreg nodes.
358     ///
359     void EmitSubregNode(SDNode *Node, 
360                         DenseMap<SDValue, unsigned> &VRBaseMap);
361
362     /// getVR - Return the virtual register corresponding to the specified result
363     /// of the specified node.
364     unsigned getVR(SDValue Op, DenseMap<SDValue, unsigned> &VRBaseMap);
365   
366     /// getDstOfCopyToRegUse - If the only use of the specified result number of
367     /// node is a CopyToReg, return its destination register. Return 0 otherwise.
368     unsigned getDstOfOnlyCopyToRegUse(SDNode *Node, unsigned ResNo) const;
369
370     void AddOperand(MachineInstr *MI, SDValue Op, unsigned IIOpNum,
371                     const TargetInstrDesc *II,
372                     DenseMap<SDValue, unsigned> &VRBaseMap);
373     void AddMemOperand(MachineInstr *MI, const MachineMemOperand &MO);
374
375     void EmitCrossRCCopy(SUnit *SU, DenseMap<SUnit*, unsigned> &VRBaseMap);
376
377     /// EmitCopyFromReg - Generate machine code for an CopyFromReg node or an
378     /// implicit physical register output.
379     void EmitCopyFromReg(SDNode *Node, unsigned ResNo, bool IsClone,
380                          unsigned SrcReg,
381                          DenseMap<SDValue, unsigned> &VRBaseMap);
382     
383     void CreateVirtualRegisters(SDNode *Node, MachineInstr *MI,
384                                 const TargetInstrDesc &II,
385                                 DenseMap<SDValue, unsigned> &VRBaseMap);
386
387     /// EmitLiveInCopy - Emit a copy for a live in physical register. If the
388     /// physical register has only a single copy use, then coalesced the copy
389     /// if possible.
390     void EmitLiveInCopy(MachineBasicBlock *MBB,
391                         MachineBasicBlock::iterator &InsertPos,
392                         unsigned VirtReg, unsigned PhysReg,
393                         const TargetRegisterClass *RC,
394                         DenseMap<MachineInstr*, unsigned> &CopyRegMap);
395
396     /// EmitLiveInCopies - If this is the first basic block in the function,
397     /// and if it has live ins that need to be copied into vregs, emit the
398     /// copies into the top of the block.
399     void EmitLiveInCopies(MachineBasicBlock *MBB);
400   };
401
402   /// createBURRListDAGScheduler - This creates a bottom up register usage
403   /// reduction list scheduler.
404   ScheduleDAG* createBURRListDAGScheduler(SelectionDAGISel *IS,
405                                           SelectionDAG *DAG,
406                                           const TargetMachine *TM,
407                                           MachineBasicBlock *BB,
408                                           bool Fast);
409   
410   /// createTDRRListDAGScheduler - This creates a top down register usage
411   /// reduction list scheduler.
412   ScheduleDAG* createTDRRListDAGScheduler(SelectionDAGISel *IS,
413                                           SelectionDAG *DAG,
414                                           const TargetMachine *TM,
415                                           MachineBasicBlock *BB,
416                                           bool Fast);
417   
418   /// createTDListDAGScheduler - This creates a top-down list scheduler with
419   /// a hazard recognizer.
420   ScheduleDAG* createTDListDAGScheduler(SelectionDAGISel *IS,
421                                         SelectionDAG *DAG,
422                                         const TargetMachine *TM,
423                                         MachineBasicBlock *BB,
424                                         bool Fast);
425                                         
426   /// createFastDAGScheduler - This creates a "fast" scheduler.
427   ///
428   ScheduleDAG *createFastDAGScheduler(SelectionDAGISel *IS,
429                                       SelectionDAG *DAG,
430                                       const TargetMachine *TM,
431                                       MachineBasicBlock *BB,
432                                       bool Fast);
433
434   /// createDefaultScheduler - This creates an instruction scheduler appropriate
435   /// for the target.
436   ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
437                                       SelectionDAG *DAG,
438                                       const TargetMachine *TM,
439                                       MachineBasicBlock *BB,
440                                       bool Fast);
441
442   class SUnitIterator : public forward_iterator<SUnit, ptrdiff_t> {
443     SUnit *Node;
444     unsigned Operand;
445
446     SUnitIterator(SUnit *N, unsigned Op) : Node(N), Operand(Op) {}
447   public:
448     bool operator==(const SUnitIterator& x) const {
449       return Operand == x.Operand;
450     }
451     bool operator!=(const SUnitIterator& x) const { return !operator==(x); }
452
453     const SUnitIterator &operator=(const SUnitIterator &I) {
454       assert(I.Node == Node && "Cannot assign iterators to two different nodes!");
455       Operand = I.Operand;
456       return *this;
457     }
458
459     pointer operator*() const {
460       return Node->Preds[Operand].Dep;
461     }
462     pointer operator->() const { return operator*(); }
463
464     SUnitIterator& operator++() {                // Preincrement
465       ++Operand;
466       return *this;
467     }
468     SUnitIterator operator++(int) { // Postincrement
469       SUnitIterator tmp = *this; ++*this; return tmp;
470     }
471
472     static SUnitIterator begin(SUnit *N) { return SUnitIterator(N, 0); }
473     static SUnitIterator end  (SUnit *N) {
474       return SUnitIterator(N, (unsigned)N->Preds.size());
475     }
476
477     unsigned getOperand() const { return Operand; }
478     const SUnit *getNode() const { return Node; }
479     bool isCtrlDep() const { return Node->Preds[Operand].isCtrl; }
480     bool isSpecialDep() const { return Node->Preds[Operand].isSpecial; }
481   };
482
483   template <> struct GraphTraits<SUnit*> {
484     typedef SUnit NodeType;
485     typedef SUnitIterator ChildIteratorType;
486     static inline NodeType *getEntryNode(SUnit *N) { return N; }
487     static inline ChildIteratorType child_begin(NodeType *N) {
488       return SUnitIterator::begin(N);
489     }
490     static inline ChildIteratorType child_end(NodeType *N) {
491       return SUnitIterator::end(N);
492     }
493   };
494
495   template <> struct GraphTraits<ScheduleDAG*> : public GraphTraits<SUnit*> {
496     typedef std::vector<SUnit>::iterator nodes_iterator;
497     static nodes_iterator nodes_begin(ScheduleDAG *G) {
498       return G->SUnits.begin();
499     }
500     static nodes_iterator nodes_end(ScheduleDAG *G) {
501       return G->SUnits.end();
502     }
503   };
504 }
505
506 #endif