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