1 //===------- llvm/CodeGen/ScheduleDAG.h - Common Base Class------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This file implements the ScheduleDAG class, which is used as the common
11 // base class for SelectionDAG-based instruction scheduler.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CODEGEN_SCHEDULEDAG_H
16 #define LLVM_CODEGEN_SCHEDULEDAG_H
18 #include "llvm/CodeGen/SelectionDAG.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/GraphTraits.h"
21 #include "llvm/ADT/SmallSet.h"
26 class MachineConstantPool;
27 class MachineModuleInfo;
31 class SelectionDAGISel;
33 class TargetInstrInfo;
34 class TargetInstrDescriptor;
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
40 class HazardRecognizer {
42 virtual ~HazardRecognizer();
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.
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) {
61 /// EmitInstruction - This callback is invoked when an instruction is
62 /// emitted, to advance the hazard state.
63 virtual void EmitInstruction(SDNode *Node) {
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() {
73 /// EmitNoop - This callback is invoked when a noop was added to the
74 /// instruction stream.
75 virtual void EmitNoop() {
79 /// SDep - Scheduling dependency. It keeps track of dependent nodes,
80 /// cost of the depdenency, etc.
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) {}
90 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
91 /// a group of nodes flagged together.
93 SDNode *Node; // Representative node.
94 SmallVector<SDNode*,4> FlaggedNodes;// All nodes flagged to Node.
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.
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;
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.
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),
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)
138 Preds.push_back(SDep(N, isCtrl, PhyReg, Cost));
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)
148 Succs.push_back(SDep(N, isCtrl, PhyReg, Cost));
152 void dump(const SelectionDAG *G) const;
153 void dumpAll(const SelectionDAG *G) const;
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.
164 class SchedulingPriorityQueue {
166 virtual ~SchedulingPriorityQueue() {}
168 virtual void initNodes(DenseMap<SDNode*, SUnit*> &SUMap,
169 std::vector<SUnit> &SUnits) = 0;
170 virtual void releaseState() = 0;
172 virtual bool empty() const = 0;
173 virtual void push(SUnit *U) = 0;
175 virtual void push_all(const std::vector<SUnit *> &Nodes) = 0;
176 virtual SUnit *pop() = 0;
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) {}
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.
199 ScheduleDAG(SelectionDAG &dag, MachineBasicBlock *bb,
200 const TargetMachine &tm)
201 : DAG(dag), BB(bb), TM(tm) {}
203 virtual ~ScheduleDAG() {}
205 /// viewGraph - Pop up a GraphViz/gv window with the ScheduleDAG rendered
210 /// Run - perform scheduling.
212 MachineBasicBlock *Run();
214 /// isPassiveNode - Return true if the node is a non-scheduled leaf.
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;
228 /// NewSUnit - Creates a new SUnit and return a ptr to it.
230 SUnit *NewSUnit(SDNode *N) {
231 SUnits.push_back(SUnit(N, SUnits.size()));
232 return &SUnits.back();
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();
240 /// CalculateDepths, CalculateHeights - Calculate node depth / height.
242 void CalculateDepths();
243 void CalculateHeights();
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);
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);
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.
259 void EmitNode(SDNode *Node, DenseMap<SDOperand, unsigned> &VRBaseMap);
261 /// EmitNoop - Emit a noop instruction.
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);
270 void CreateVirtualRegisters(SDNode *Node, MachineInstr *MI,
271 const TargetInstrDescriptor &II,
272 DenseMap<SDOperand, unsigned> &VRBaseMap);
276 void dumpSchedule() const;
278 /// Schedule - Order nodes according to selected style.
280 virtual void Schedule() {}
283 /// EmitSubregNode - Generate machine code for subreg nodes.
285 void EmitSubregNode(SDNode *Node,
286 DenseMap<SDOperand, unsigned> &VRBaseMap);
288 void AddOperand(MachineInstr *MI, SDOperand Op, unsigned IIOpNum,
289 const TargetInstrDescriptor *II,
290 DenseMap<SDOperand, unsigned> &VRBaseMap);
293 /// createBFS_DAGScheduler - This creates a simple breadth first instruction
295 ScheduleDAG *createBFS_DAGScheduler(SelectionDAGISel *IS,
297 MachineBasicBlock *BB);
299 /// createSimpleDAGScheduler - This creates a simple two pass instruction
300 /// scheduler using instruction itinerary.
301 ScheduleDAG* createSimpleDAGScheduler(SelectionDAGISel *IS,
303 MachineBasicBlock *BB);
305 /// createNoItinsDAGScheduler - This creates a simple two pass instruction
306 /// scheduler without using instruction itinerary.
307 ScheduleDAG* createNoItinsDAGScheduler(SelectionDAGISel *IS,
309 MachineBasicBlock *BB);
311 /// createBURRListDAGScheduler - This creates a bottom up register usage
312 /// reduction list scheduler.
313 ScheduleDAG* createBURRListDAGScheduler(SelectionDAGISel *IS,
315 MachineBasicBlock *BB);
317 /// createTDRRListDAGScheduler - This creates a top down register usage
318 /// reduction list scheduler.
319 ScheduleDAG* createTDRRListDAGScheduler(SelectionDAGISel *IS,
321 MachineBasicBlock *BB);
323 /// createTDListDAGScheduler - This creates a top-down list scheduler with
324 /// a hazard recognizer.
325 ScheduleDAG* createTDListDAGScheduler(SelectionDAGISel *IS,
327 MachineBasicBlock *BB);
329 /// createDefaultScheduler - This creates an instruction scheduler appropriate
331 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
333 MachineBasicBlock *BB);
335 class SUnitIterator : public forward_iterator<SUnit, ptrdiff_t> {
339 SUnitIterator(SUnit *N, unsigned Op) : Node(N), Operand(Op) {}
341 bool operator==(const SUnitIterator& x) const {
342 return Operand == x.Operand;
344 bool operator!=(const SUnitIterator& x) const { return !operator==(x); }
346 const SUnitIterator &operator=(const SUnitIterator &I) {
347 assert(I.Node == Node && "Cannot assign iterators to two different nodes!");
352 pointer operator*() const {
353 return Node->Preds[Operand].Dep;
355 pointer operator->() const { return operator*(); }
357 SUnitIterator& operator++() { // Preincrement
361 SUnitIterator operator++(int) { // Postincrement
362 SUnitIterator tmp = *this; ++*this; return tmp;
365 static SUnitIterator begin(SUnit *N) { return SUnitIterator(N, 0); }
366 static SUnitIterator end (SUnit *N) {
367 return SUnitIterator(N, N->Preds.size());
370 unsigned getOperand() const { return Operand; }
371 const SUnit *getNode() const { return Node; }
372 bool isCtrlDep() const { return Node->Preds[Operand].isCtrl; }
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);
382 static inline ChildIteratorType child_end(NodeType *N) {
383 return SUnitIterator::end(N);
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();
392 static nodes_iterator nodes_end(ScheduleDAG *G) {
393 return G->SUnits.end();