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 unsigned Reg; // If non-zero, this dep is a phy register dependency.
84 int Cost; // Cost of the dependency.
85 bool isCtrl : 1; // True iff it's a control dependency.
86 bool isSpecial : 1; // True iff it's a special ctrl dep added during sched.
87 SDep(SUnit *d, unsigned r, int t, bool c, bool s)
88 : Dep(d), Reg(r), Cost(t), isCtrl(c), isSpecial(s) {}
91 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
92 /// a group of nodes flagged together.
94 SDNode *Node; // Representative node.
95 SmallVector<SDNode*,4> FlaggedNodes;// All nodes flagged to Node.
96 unsigned InstanceNo; // Instance#. One SDNode can be multiple
97 // SUnit due to cloning.
99 // Preds/Succs - The SUnits before/after us in the graph. The boolean value
100 // is true if the edge is a token chain edge, false if it is a value edge.
101 SmallVector<SDep, 4> Preds; // All sunit predecessors.
102 SmallVector<SDep, 4> Succs; // All sunit successors.
104 typedef SmallVector<SDep, 4>::iterator pred_iterator;
105 typedef SmallVector<SDep, 4>::iterator succ_iterator;
106 typedef SmallVector<SDep, 4>::const_iterator const_pred_iterator;
107 typedef SmallVector<SDep, 4>::const_iterator const_succ_iterator;
109 unsigned NodeNum; // Entry # of node in the node vector.
110 unsigned short Latency; // Node latency.
111 short NumPreds; // # of preds.
112 short NumSuccs; // # of sucss.
113 short NumPredsLeft; // # of preds not scheduled.
114 short NumSuccsLeft; // # of succs not scheduled.
115 short NumChainPredsLeft; // # of chain preds not scheduled.
116 short NumChainSuccsLeft; // # of chain succs not scheduled.
117 bool isTwoAddress : 1; // Is a two-address instruction.
118 bool isCommutable : 1; // Is a commutable instruction.
119 bool hasImplicitDefs : 1; // Has implicit physical reg defs.
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;
128 SUnit(SDNode *node, unsigned nodenum)
129 : Node(node), InstanceNo(0), NodeNum(nodenum), Latency(0),
130 NumPreds(0), NumSuccs(0), NumPredsLeft(0), NumSuccsLeft(0),
131 NumChainPredsLeft(0), NumChainSuccsLeft(0),
132 isTwoAddress(false), isCommutable(false), hasImplicitDefs(false),
133 isPending(false), isAvailable(false), isScheduled(false),
134 CycleBound(0), Cycle(0), Depth(0), Height(0) {}
136 /// addPred - This adds the specified node as a pred of the current node if
137 /// not already. This returns true if this is a new pred.
138 bool addPred(SUnit *N, bool isCtrl, bool isSpecial,
139 unsigned PhyReg = 0, int Cost = 1) {
140 for (unsigned i = 0, e = Preds.size(); i != e; ++i)
141 if (Preds[i].Dep == N &&
142 Preds[i].isCtrl == isCtrl && Preds[i].isSpecial == isSpecial)
144 Preds.push_back(SDep(N, PhyReg, Cost, isCtrl, isSpecial));
145 N->Succs.push_back(SDep(this, PhyReg, Cost, isCtrl, isSpecial));
150 ++N->NumChainSuccsLeft;
162 bool removePred(SUnit *N, bool isCtrl, bool isSpecial) {
163 for (SmallVector<SDep, 4>::iterator I = Preds.begin(), E = Preds.end();
165 if (I->Dep == N && I->isCtrl == isCtrl && I->isSpecial == isSpecial) {
166 bool FoundSucc = false;
167 for (SmallVector<SDep, 4>::iterator II = N->Succs.begin(),
168 EE = N->Succs.end(); II != EE; ++II)
169 if (II->Dep == this &&
170 II->isCtrl == isCtrl && II->isSpecial == isSpecial) {
175 assert(FoundSucc && "Mismatching preds / succs lists!");
195 bool isPred(SUnit *N) {
196 for (unsigned i = 0, e = Preds.size(); i != e; ++i)
197 if (Preds[i].Dep == N)
202 bool isSucc(SUnit *N) {
203 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
204 if (Succs[i].Dep == N)
209 void dump(const SelectionDAG *G) const;
210 void dumpAll(const SelectionDAG *G) const;
213 //===--------------------------------------------------------------------===//
214 /// SchedulingPriorityQueue - This interface is used to plug different
215 /// priorities computation algorithms into the list scheduler. It implements
216 /// the interface of a standard priority queue, where nodes are inserted in
217 /// arbitrary order and returned in priority order. The computation of the
218 /// priority and the representation of the queue are totally up to the
219 /// implementation to decide.
221 class SchedulingPriorityQueue {
223 virtual ~SchedulingPriorityQueue() {}
225 virtual void initNodes(DenseMap<SDNode*, std::vector<SUnit*> > &SUMap,
226 std::vector<SUnit> &SUnits) = 0;
227 virtual void addNode(const SUnit *SU) = 0;
228 virtual void updateNode(const SUnit *SU) = 0;
229 virtual void releaseState() = 0;
231 virtual unsigned size() const = 0;
232 virtual bool empty() const = 0;
233 virtual void push(SUnit *U) = 0;
235 virtual void push_all(const std::vector<SUnit *> &Nodes) = 0;
236 virtual SUnit *pop() = 0;
238 virtual void remove(SUnit *SU) = 0;
240 /// ScheduledNode - As each node is scheduled, this method is invoked. This
241 /// allows the priority function to adjust the priority of node that have
242 /// already been emitted.
243 virtual void ScheduledNode(SUnit *Node) {}
245 virtual void UnscheduledNode(SUnit *Node) {}
250 SelectionDAG &DAG; // DAG of the current basic block
251 MachineBasicBlock *BB; // Current basic block
252 const TargetMachine &TM; // Target processor
253 const TargetInstrInfo *TII; // Target instruction information
254 const MRegisterInfo *MRI; // Target processor register info
255 SSARegMap *RegMap; // Virtual/real register map
256 MachineConstantPool *ConstPool; // Target constant pool
257 std::vector<SUnit*> Sequence; // The schedule. Null SUnit*'s
258 // represent noop instructions.
259 DenseMap<SDNode*, std::vector<SUnit*> > SUnitMap;
260 // SDNode to SUnit mapping (n -> n).
261 std::vector<SUnit> SUnits; // The scheduling units.
262 SmallSet<SDNode*, 16> CommuteSet; // Nodes the should be commuted.
264 ScheduleDAG(SelectionDAG &dag, MachineBasicBlock *bb,
265 const TargetMachine &tm)
266 : DAG(dag), BB(bb), TM(tm) {}
268 virtual ~ScheduleDAG() {}
270 /// viewGraph - Pop up a GraphViz/gv window with the ScheduleDAG rendered
275 /// Run - perform scheduling.
277 MachineBasicBlock *Run();
279 /// isPassiveNode - Return true if the node is a non-scheduled leaf.
281 static bool isPassiveNode(SDNode *Node) {
282 if (isa<ConstantSDNode>(Node)) return true;
283 if (isa<RegisterSDNode>(Node)) return true;
284 if (isa<GlobalAddressSDNode>(Node)) return true;
285 if (isa<BasicBlockSDNode>(Node)) return true;
286 if (isa<FrameIndexSDNode>(Node)) return true;
287 if (isa<ConstantPoolSDNode>(Node)) return true;
288 if (isa<JumpTableSDNode>(Node)) return true;
289 if (isa<ExternalSymbolSDNode>(Node)) return true;
293 /// NewSUnit - Creates a new SUnit and return a ptr to it.
295 SUnit *NewSUnit(SDNode *N) {
296 SUnits.push_back(SUnit(N, SUnits.size()));
297 return &SUnits.back();
300 /// Clone - Creates a clone of the specified SUnit. It does not copy the
301 /// predecessors / successors info nor the temporary scheduling states.
302 SUnit *Clone(SUnit *N);
304 /// BuildSchedUnits - Build SUnits from the selection dag that we are input.
305 /// This SUnit graph is similar to the SelectionDAG, but represents flagged
306 /// together nodes with a single SUnit.
307 void BuildSchedUnits();
309 /// CalculateDepths, CalculateHeights - Calculate node depth / height.
311 void CalculateDepths();
312 void CalculateHeights();
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);
319 /// CountOperands The inputs to target nodes have any actual inputs first,
320 /// followed by an optional chain operand, then flag operands. Compute the
321 /// number of actual operands that will go into the machine instr.
322 static unsigned CountOperands(SDNode *Node);
324 /// EmitNode - Generate machine code for an node and needed dependencies.
325 /// VRBaseMap contains, for each already emitted node, the first virtual
326 /// register number for the results of the node.
328 void EmitNode(SDNode *Node, unsigned InstNo,
329 DenseMap<SDOperand, unsigned> &VRBaseMap);
331 /// EmitNoop - Emit a noop instruction.
335 /// EmitCopyFromReg - Generate machine code for an CopyFromReg node or an
336 /// implicit physical register output.
337 void EmitCopyFromReg(SDNode *Node, unsigned ResNo, unsigned InstNo,
339 DenseMap<SDOperand, unsigned> &VRBaseMap);
341 void CreateVirtualRegisters(SDNode *Node, MachineInstr *MI,
342 const TargetInstrDescriptor &II,
343 DenseMap<SDOperand, unsigned> &VRBaseMap);
347 void dumpSchedule() const;
349 /// Schedule - Order nodes according to selected style.
351 virtual void Schedule() {}
354 /// EmitSubregNode - Generate machine code for subreg nodes.
356 void EmitSubregNode(SDNode *Node,
357 DenseMap<SDOperand, unsigned> &VRBaseMap);
359 void AddOperand(MachineInstr *MI, SDOperand Op, unsigned IIOpNum,
360 const TargetInstrDescriptor *II,
361 DenseMap<SDOperand, unsigned> &VRBaseMap);
364 /// createBFS_DAGScheduler - This creates a simple breadth first instruction
366 ScheduleDAG *createBFS_DAGScheduler(SelectionDAGISel *IS,
368 MachineBasicBlock *BB);
370 /// createSimpleDAGScheduler - This creates a simple two pass instruction
371 /// scheduler using instruction itinerary.
372 ScheduleDAG* createSimpleDAGScheduler(SelectionDAGISel *IS,
374 MachineBasicBlock *BB);
376 /// createNoItinsDAGScheduler - This creates a simple two pass instruction
377 /// scheduler without using instruction itinerary.
378 ScheduleDAG* createNoItinsDAGScheduler(SelectionDAGISel *IS,
380 MachineBasicBlock *BB);
382 /// createBURRListDAGScheduler - This creates a bottom up register usage
383 /// reduction list scheduler.
384 ScheduleDAG* createBURRListDAGScheduler(SelectionDAGISel *IS,
386 MachineBasicBlock *BB);
388 /// createTDRRListDAGScheduler - This creates a top down register usage
389 /// reduction list scheduler.
390 ScheduleDAG* createTDRRListDAGScheduler(SelectionDAGISel *IS,
392 MachineBasicBlock *BB);
394 /// createTDListDAGScheduler - This creates a top-down list scheduler with
395 /// a hazard recognizer.
396 ScheduleDAG* createTDListDAGScheduler(SelectionDAGISel *IS,
398 MachineBasicBlock *BB);
400 /// createDefaultScheduler - This creates an instruction scheduler appropriate
402 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
404 MachineBasicBlock *BB);
406 class SUnitIterator : public forward_iterator<SUnit, ptrdiff_t> {
410 SUnitIterator(SUnit *N, unsigned Op) : Node(N), Operand(Op) {}
412 bool operator==(const SUnitIterator& x) const {
413 return Operand == x.Operand;
415 bool operator!=(const SUnitIterator& x) const { return !operator==(x); }
417 const SUnitIterator &operator=(const SUnitIterator &I) {
418 assert(I.Node == Node && "Cannot assign iterators to two different nodes!");
423 pointer operator*() const {
424 return Node->Preds[Operand].Dep;
426 pointer operator->() const { return operator*(); }
428 SUnitIterator& operator++() { // Preincrement
432 SUnitIterator operator++(int) { // Postincrement
433 SUnitIterator tmp = *this; ++*this; return tmp;
436 static SUnitIterator begin(SUnit *N) { return SUnitIterator(N, 0); }
437 static SUnitIterator end (SUnit *N) {
438 return SUnitIterator(N, N->Preds.size());
441 unsigned getOperand() const { return Operand; }
442 const SUnit *getNode() const { return Node; }
443 bool isCtrlDep() const { return Node->Preds[Operand].isCtrl; }
446 template <> struct GraphTraits<SUnit*> {
447 typedef SUnit NodeType;
448 typedef SUnitIterator ChildIteratorType;
449 static inline NodeType *getEntryNode(SUnit *N) { return N; }
450 static inline ChildIteratorType child_begin(NodeType *N) {
451 return SUnitIterator::begin(N);
453 static inline ChildIteratorType child_end(NodeType *N) {
454 return SUnitIterator::end(N);
458 template <> struct GraphTraits<ScheduleDAG*> : public GraphTraits<SUnit*> {
459 typedef std::vector<SUnit>::iterator nodes_iterator;
460 static nodes_iterator nodes_begin(ScheduleDAG *G) {
461 return G->SUnits.begin();
463 static nodes_iterator nodes_end(ScheduleDAG *G) {
464 return G->SUnits.end();