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