Use struct SDep instead of std::pair for SUnit pred and succ lists. First step
[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 was developed by Evan Cheng and is distributed under
6 // the University of Illinois Open Source 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/SelectionDAG.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/GraphTraits.h"
21 #include "llvm/ADT/SmallSet.h"
22
23 namespace llvm {
24   struct InstrStage;
25   struct SUnit;
26   class MachineConstantPool;
27   class MachineModuleInfo;
28   class MachineInstr;
29   class MRegisterInfo;
30   class SelectionDAG;
31   class SelectionDAGISel;
32   class SSARegMap;
33   class TargetInstrInfo;
34   class TargetInstrDescriptor;
35   class TargetMachine;
36
37   /// HazardRecognizer - This determines whether or not an instruction can be
38   /// issued this cycle, and whether or not a noop needs to be inserted to handle
39   /// the hazard.
40   class HazardRecognizer {
41   public:
42     virtual ~HazardRecognizer();
43     
44     enum HazardType {
45       NoHazard,      // This instruction can be emitted at this cycle.
46       Hazard,        // This instruction can't be emitted at this cycle.
47       NoopHazard     // This instruction can't be emitted, and needs noops.
48     };
49     
50     /// getHazardType - Return the hazard type of emitting this node.  There are
51     /// three possible results.  Either:
52     ///  * NoHazard: it is legal to issue this instruction on this cycle.
53     ///  * Hazard: issuing this instruction would stall the machine.  If some
54     ///     other instruction is available, issue it first.
55     ///  * NoopHazard: issuing this instruction would break the program.  If
56     ///     some other instruction can be issued, do so, otherwise issue a noop.
57     virtual HazardType getHazardType(SDNode *Node) {
58       return NoHazard;
59     }
60     
61     /// EmitInstruction - This callback is invoked when an instruction is
62     /// emitted, to advance the hazard state.
63     virtual void EmitInstruction(SDNode *Node) {
64     }
65     
66     /// AdvanceCycle - This callback is invoked when no instructions can be
67     /// issued on this cycle without a hazard.  This should increment the
68     /// internal state of the hazard recognizer so that previously "Hazard"
69     /// instructions will now not be hazards.
70     virtual void AdvanceCycle() {
71     }
72     
73     /// EmitNoop - This callback is invoked when a noop was added to the
74     /// instruction stream.
75     virtual void EmitNoop() {
76     }
77   };
78
79   /// SDep - Scheduling dependency. It keeps track of dependent nodes,
80   /// cost of the depdenency, etc.
81   struct SDep {
82     SUnit    *Dep;      // Dependent - either a predecessor or a successor.
83     bool      isCtrl;   // True iff it's a control dependency.
84     unsigned  PhyReg;   // If non-zero, this dep is a phy register dependency.
85     int       Cost;     // Cost of the dependency.
86     SDep(SUnit *d, bool c, unsigned r, int t)
87       : Dep(d), isCtrl(c), PhyReg(r), Cost(t) {}
88   };
89
90   /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
91   /// a group of nodes flagged together.
92   struct SUnit {
93     SDNode *Node;                       // Representative node.
94     SmallVector<SDNode*,4> FlaggedNodes;// All nodes flagged to Node.
95     
96     // Preds/Succs - The SUnits before/after us in the graph.  The boolean value
97     // is true if the edge is a token chain edge, false if it is a value edge. 
98     SmallVector<SDep, 4> Preds;  // All sunit predecessors.
99     SmallVector<SDep, 4> Succs;  // All sunit successors.
100
101     typedef SmallVector<SDep, 4>::iterator pred_iterator;
102     typedef SmallVector<SDep, 4>::iterator succ_iterator;
103     typedef SmallVector<SDep, 4>::const_iterator const_pred_iterator;
104     typedef SmallVector<SDep, 4>::const_iterator const_succ_iterator;
105     
106     short NumPreds;                     // # of preds.
107     short NumSuccs;                     // # of sucss.
108     short NumPredsLeft;                 // # of preds not scheduled.
109     short NumSuccsLeft;                 // # of succs not scheduled.
110     short NumChainPredsLeft;            // # of chain preds not scheduled.
111     short NumChainSuccsLeft;            // # of chain succs not scheduled.
112     bool isTwoAddress     : 1;          // Is a two-address instruction.
113     bool isCommutable     : 1;          // Is a commutable instruction.
114     bool isPending        : 1;          // True once pending.
115     bool isAvailable      : 1;          // True once available.
116     bool isScheduled      : 1;          // True once scheduled.
117     unsigned short Latency;             // Node latency.
118     unsigned CycleBound;                // Upper/lower cycle to be scheduled at.
119     unsigned Cycle;                     // Once scheduled, the cycle of the op.
120     unsigned Depth;                     // Node depth;
121     unsigned Height;                    // Node height;
122     unsigned NodeNum;                   // Entry # of node in the node vector.
123     
124     SUnit(SDNode *node, unsigned nodenum)
125       : Node(node), NumPreds(0), NumSuccs(0), NumPredsLeft(0), NumSuccsLeft(0),
126         NumChainPredsLeft(0), NumChainSuccsLeft(0),
127         isTwoAddress(false), isCommutable(false),
128         isPending(false), isAvailable(false), isScheduled(false),
129         Latency(0), CycleBound(0), Cycle(0), Depth(0), Height(0),
130         NodeNum(nodenum) {}
131     
132     /// addPred - This adds the specified node as a pred of the current node if
133     /// not already.  This returns true if this is a new pred.
134     bool addPred(SUnit *N, bool isCtrl, unsigned PhyReg = 0, int Cost = 1) {
135       for (unsigned i = 0, e = Preds.size(); i != e; ++i)
136         if (Preds[i].Dep == N && Preds[i].isCtrl == isCtrl)
137           return false;
138       Preds.push_back(SDep(N, isCtrl, PhyReg, Cost));
139       return true;
140     }
141
142     /// addSucc - This adds the specified node as a succ of the current node if
143     /// not already.  This returns true if this is a new succ.
144     bool addSucc(SUnit *N, bool isCtrl, unsigned PhyReg = 0, int Cost = 1) {
145       for (unsigned i = 0, e = Succs.size(); i != e; ++i)
146         if (Succs[i].Dep == N && Succs[i].isCtrl == isCtrl)
147           return false;
148       Succs.push_back(SDep(N, isCtrl, PhyReg, Cost));
149       return true;
150     }
151     
152     void dump(const SelectionDAG *G) const;
153     void dumpAll(const SelectionDAG *G) const;
154   };
155
156   //===--------------------------------------------------------------------===//
157   /// SchedulingPriorityQueue - This interface is used to plug different
158   /// priorities computation algorithms into the list scheduler. It implements
159   /// the interface of a standard priority queue, where nodes are inserted in 
160   /// arbitrary order and returned in priority order.  The computation of the
161   /// priority and the representation of the queue are totally up to the
162   /// implementation to decide.
163   /// 
164   class SchedulingPriorityQueue {
165   public:
166     virtual ~SchedulingPriorityQueue() {}
167   
168     virtual void initNodes(DenseMap<SDNode*, SUnit*> &SUMap,
169                            std::vector<SUnit> &SUnits) = 0;
170     virtual void releaseState() = 0;
171   
172     virtual bool empty() const = 0;
173     virtual void push(SUnit *U) = 0;
174   
175     virtual void push_all(const std::vector<SUnit *> &Nodes) = 0;
176     virtual SUnit *pop() = 0;
177
178     /// ScheduledNode - As each node is scheduled, this method is invoked.  This
179     /// allows the priority function to adjust the priority of node that have
180     /// already been emitted.
181     virtual void ScheduledNode(SUnit *Node) {}
182   };
183
184   class ScheduleDAG {
185   public:
186     SelectionDAG &DAG;                    // DAG of the current basic block
187     MachineBasicBlock *BB;                // Current basic block
188     const TargetMachine &TM;              // Target processor
189     const TargetInstrInfo *TII;           // Target instruction information
190     const MRegisterInfo *MRI;             // Target processor register info
191     SSARegMap *RegMap;                    // Virtual/real register map
192     MachineConstantPool *ConstPool;       // Target constant pool
193     std::vector<SUnit*> Sequence;         // The schedule. Null SUnit*'s
194                                           // represent noop instructions.
195     DenseMap<SDNode*, SUnit*> SUnitMap;   // SDNode to SUnit mapping (n -> 1).
196     std::vector<SUnit> SUnits;            // The scheduling units.
197     SmallSet<SDNode*, 16> CommuteSet;     // Nodes the should be commuted.
198
199     ScheduleDAG(SelectionDAG &dag, MachineBasicBlock *bb,
200                 const TargetMachine &tm)
201       : DAG(dag), BB(bb), TM(tm) {}
202
203     virtual ~ScheduleDAG() {}
204
205     /// viewGraph - Pop up a GraphViz/gv window with the ScheduleDAG rendered
206     /// using 'dot'.
207     ///
208     void viewGraph();
209   
210     /// Run - perform scheduling.
211     ///
212     MachineBasicBlock *Run();
213
214     /// isPassiveNode - Return true if the node is a non-scheduled leaf.
215     ///
216     static bool isPassiveNode(SDNode *Node) {
217       if (isa<ConstantSDNode>(Node))       return true;
218       if (isa<RegisterSDNode>(Node))       return true;
219       if (isa<GlobalAddressSDNode>(Node))  return true;
220       if (isa<BasicBlockSDNode>(Node))     return true;
221       if (isa<FrameIndexSDNode>(Node))     return true;
222       if (isa<ConstantPoolSDNode>(Node))   return true;
223       if (isa<JumpTableSDNode>(Node))      return true;
224       if (isa<ExternalSymbolSDNode>(Node)) return true;
225       return false;
226     }
227
228     /// NewSUnit - Creates a new SUnit and return a ptr to it.
229     ///
230     SUnit *NewSUnit(SDNode *N) {
231       SUnits.push_back(SUnit(N, SUnits.size()));
232       return &SUnits.back();
233     }
234
235     /// BuildSchedUnits - Build SUnits from the selection dag that we are input.
236     /// This SUnit graph is similar to the SelectionDAG, but represents flagged
237     /// together nodes with a single SUnit.
238     void BuildSchedUnits();
239
240     /// CalculateDepths, CalculateHeights - Calculate node depth / height.
241     ///
242     void CalculateDepths();
243     void CalculateHeights();
244
245     /// CountResults - The results of target nodes have register or immediate
246     /// operands first, then an optional chain, and optional flag operands
247     /// (which do not go into the machine instrs.)
248     static unsigned CountResults(SDNode *Node);
249
250     /// CountOperands  The inputs to target nodes have any actual inputs first,
251     /// followed by an optional chain operand, then flag operands.  Compute the
252     /// number of actual operands that  will go into the machine instr.
253     static unsigned CountOperands(SDNode *Node);
254
255     /// EmitNode - Generate machine code for an node and needed dependencies.
256     /// VRBaseMap contains, for each already emitted node, the first virtual
257     /// register number for the results of the node.
258     ///
259     void EmitNode(SDNode *Node, DenseMap<SDOperand, unsigned> &VRBaseMap);
260     
261     /// EmitNoop - Emit a noop instruction.
262     ///
263     void EmitNoop();
264
265     /// EmitCopyFromReg - Generate machine code for an CopyFromReg node or an
266     /// implicit physical register output.
267     void EmitCopyFromReg(SDNode *Node, unsigned ResNo, unsigned SrcReg,
268                          DenseMap<SDOperand, unsigned> &VRBaseMap);
269     
270     void CreateVirtualRegisters(SDNode *Node, MachineInstr *MI,
271                                 const TargetInstrDescriptor &II,
272                                 DenseMap<SDOperand, unsigned> &VRBaseMap);
273
274     void EmitSchedule();
275
276     void dumpSchedule() const;
277
278     /// Schedule - Order nodes according to selected style.
279     ///
280     virtual void Schedule() {}
281
282   private:
283     /// EmitSubregNode - Generate machine code for subreg nodes.
284     ///
285     void EmitSubregNode(SDNode *Node, 
286                         DenseMap<SDOperand, unsigned> &VRBaseMap);
287   
288     void AddOperand(MachineInstr *MI, SDOperand Op, unsigned IIOpNum,
289                     const TargetInstrDescriptor *II,
290                     DenseMap<SDOperand, unsigned> &VRBaseMap);
291   };
292
293   /// createBFS_DAGScheduler - This creates a simple breadth first instruction
294   /// scheduler.
295   ScheduleDAG *createBFS_DAGScheduler(SelectionDAGISel *IS,
296                                       SelectionDAG *DAG,
297                                       MachineBasicBlock *BB);
298   
299   /// createSimpleDAGScheduler - This creates a simple two pass instruction
300   /// scheduler using instruction itinerary.
301   ScheduleDAG* createSimpleDAGScheduler(SelectionDAGISel *IS,
302                                         SelectionDAG *DAG,
303                                         MachineBasicBlock *BB);
304
305   /// createNoItinsDAGScheduler - This creates a simple two pass instruction
306   /// scheduler without using instruction itinerary.
307   ScheduleDAG* createNoItinsDAGScheduler(SelectionDAGISel *IS,
308                                          SelectionDAG *DAG,
309                                          MachineBasicBlock *BB);
310
311   /// createBURRListDAGScheduler - This creates a bottom up register usage
312   /// reduction list scheduler.
313   ScheduleDAG* createBURRListDAGScheduler(SelectionDAGISel *IS,
314                                           SelectionDAG *DAG,
315                                           MachineBasicBlock *BB);
316   
317   /// createTDRRListDAGScheduler - This creates a top down register usage
318   /// reduction list scheduler.
319   ScheduleDAG* createTDRRListDAGScheduler(SelectionDAGISel *IS,
320                                           SelectionDAG *DAG,
321                                           MachineBasicBlock *BB);
322   
323   /// createTDListDAGScheduler - This creates a top-down list scheduler with
324   /// a hazard recognizer.
325   ScheduleDAG* createTDListDAGScheduler(SelectionDAGISel *IS,
326                                         SelectionDAG *DAG,
327                                         MachineBasicBlock *BB);
328                                         
329   /// createDefaultScheduler - This creates an instruction scheduler appropriate
330   /// for the target.
331   ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
332                                       SelectionDAG *DAG,
333                                       MachineBasicBlock *BB);
334
335   class SUnitIterator : public forward_iterator<SUnit, ptrdiff_t> {
336     SUnit *Node;
337     unsigned Operand;
338
339     SUnitIterator(SUnit *N, unsigned Op) : Node(N), Operand(Op) {}
340   public:
341     bool operator==(const SUnitIterator& x) const {
342       return Operand == x.Operand;
343     }
344     bool operator!=(const SUnitIterator& x) const { return !operator==(x); }
345
346     const SUnitIterator &operator=(const SUnitIterator &I) {
347       assert(I.Node == Node && "Cannot assign iterators to two different nodes!");
348       Operand = I.Operand;
349       return *this;
350     }
351
352     pointer operator*() const {
353       return Node->Preds[Operand].Dep;
354     }
355     pointer operator->() const { return operator*(); }
356
357     SUnitIterator& operator++() {                // Preincrement
358       ++Operand;
359       return *this;
360     }
361     SUnitIterator operator++(int) { // Postincrement
362       SUnitIterator tmp = *this; ++*this; return tmp;
363     }
364
365     static SUnitIterator begin(SUnit *N) { return SUnitIterator(N, 0); }
366     static SUnitIterator end  (SUnit *N) {
367       return SUnitIterator(N, N->Preds.size());
368     }
369
370     unsigned getOperand() const { return Operand; }
371     const SUnit *getNode() const { return Node; }
372     bool isCtrlDep() const { return Node->Preds[Operand].isCtrl; }
373   };
374
375   template <> struct GraphTraits<SUnit*> {
376     typedef SUnit NodeType;
377     typedef SUnitIterator ChildIteratorType;
378     static inline NodeType *getEntryNode(SUnit *N) { return N; }
379     static inline ChildIteratorType child_begin(NodeType *N) {
380       return SUnitIterator::begin(N);
381     }
382     static inline ChildIteratorType child_end(NodeType *N) {
383       return SUnitIterator::end(N);
384     }
385   };
386
387   template <> struct GraphTraits<ScheduleDAG*> : public GraphTraits<SUnit*> {
388     typedef std::vector<SUnit>::iterator nodes_iterator;
389     static nodes_iterator nodes_begin(ScheduleDAG *G) {
390       return G->SUnits.begin();
391     }
392     static nodes_iterator nodes_end(ScheduleDAG *G) {
393       return G->SUnits.end();
394     }
395   };
396 }
397
398 #endif