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