1 //===------- llvm/CodeGen/ScheduleDAG.h - Common Base Class------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the ScheduleDAG class, which is used as the common
11 // base class for instruction schedulers.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CODEGEN_SCHEDULEDAG_H
16 #define LLVM_CODEGEN_SCHEDULEDAG_H
18 #include "llvm/CodeGen/MachineBasicBlock.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/BitVector.h"
21 #include "llvm/ADT/GraphTraits.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/PointerIntPair.h"
27 class MachineConstantPool;
28 class MachineFunction;
29 class MachineModuleInfo;
30 class MachineRegisterInfo;
32 class TargetRegisterInfo;
35 class TargetInstrInfo;
36 class TargetInstrDesc;
39 class TargetRegisterClass;
40 template<class Graph> class GraphWriter;
42 /// SDep - Scheduling dependency. This represents one direction of an
43 /// edge in the scheduling DAG.
46 /// Kind - These are the different kinds of scheduling dependencies.
48 Data, ///< Regular data dependence (aka true-dependence).
49 Anti, ///< A register anti-dependedence (aka WAR).
50 Output, ///< A register output-dependence (aka WAW).
51 Order ///< Any other ordering dependency.
55 /// Dep - A pointer to the depending/depended-on SUnit, and an enum
56 /// indicating the kind of the dependency.
57 PointerIntPair<SUnit *, 2, Kind> Dep;
59 /// Contents - A union discriminated by the dependence kind.
61 /// Reg - For Data, Anti, and Output dependencies, the associated
62 /// register. For Data dependencies that don't currently have a register
63 /// assigned, this is set to zero.
66 /// Order - Additional information about Order dependencies.
68 /// isNormalMemory - True if both sides of the dependence
69 /// access memory in non-volatile and fully modeled ways.
70 bool isNormalMemory : 1;
72 /// isMustAlias - True if both sides of the dependence are known to
73 /// access the same memory.
76 /// isArtificial - True if this is an artificial dependency, meaning
77 /// it is not necessary for program correctness, and may be safely
78 /// deleted if necessary.
79 bool isArtificial : 1;
83 /// Latency - The time associated with this edge. Often this is just
84 /// the value of the Latency field of the predecessor, however advanced
85 /// models may provide additional information about specific edges.
89 /// SDep - Construct a null SDep. This is only for use by container
90 /// classes which require default constructors. SUnits may not
91 /// have null SDep edges.
92 SDep() : Dep(0, Data) {}
94 /// SDep - Construct an SDep with the specified values.
95 SDep(SUnit *S, Kind kind, unsigned latency = 1, unsigned Reg = 0,
96 bool isNormalMemory = false, bool isMustAlias = false,
97 bool isArtificial = false)
98 : Dep(S, kind), Contents(), Latency(latency) {
103 "SDep::Anti and SDep::Output must use a non-zero Reg!");
106 assert(!isMustAlias && "isMustAlias only applies with SDep::Order!");
107 assert(!isArtificial && "isArtificial only applies with SDep::Order!");
111 assert(Reg == 0 && "Reg given for non-register dependence!");
112 Contents.Order.isNormalMemory = isNormalMemory;
113 Contents.Order.isMustAlias = isMustAlias;
114 Contents.Order.isArtificial = isArtificial;
119 bool operator==(const SDep &Other) const {
120 if (Dep != Other.Dep || Latency != Other.Latency) return false;
121 switch (Dep.getInt()) {
125 return Contents.Reg == Other.Contents.Reg;
127 return Contents.Order.isNormalMemory ==
128 Other.Contents.Order.isNormalMemory &&
129 Contents.Order.isMustAlias == Other.Contents.Order.isMustAlias &&
130 Contents.Order.isArtificial == Other.Contents.Order.isArtificial;
132 assert(0 && "Invalid dependency kind!");
136 bool operator!=(const SDep &Other) const {
137 return !operator==(Other);
140 /// getLatency - Return the latency value for this edge, which roughly
141 /// means the minimum number of cycles that must elapse between the
142 /// predecessor and the successor, given that they have this edge
144 unsigned getLatency() const {
148 //// getSUnit - Return the SUnit to which this edge points.
149 SUnit *getSUnit() const {
150 return Dep.getPointer();
153 //// setSUnit - Assign the SUnit to which this edge points.
154 void setSUnit(SUnit *SU) {
158 /// getKind - Return an enum value representing the kind of the dependence.
159 Kind getKind() const {
163 /// isCtrl - Shorthand for getKind() != SDep::Data.
164 bool isCtrl() const {
165 return getKind() != Data;
168 /// isNormalMemory - Test if this is an Order dependence between two
169 /// memory accesses where both sides of the dependence access memory
170 /// in non-volatile and fully modeled ways.
171 bool isNormalMemory() const {
172 return getKind() == Order && Contents.Order.isNormalMemory;
175 /// isMustAlias - Test if this is an Order dependence that is marked
176 /// as "must alias", meaning that the SUnits at either end of the edge
177 /// have a memory dependence on a known memory location.
178 bool isMustAlias() const {
179 return getKind() == Order && Contents.Order.isMustAlias;
182 /// isArtificial - Test if this is an Order dependence that is marked
183 /// as "artificial", meaning it isn't necessary for correctness.
184 bool isArtificial() const {
185 return getKind() == Order && Contents.Order.isArtificial;
188 /// isAssignedRegDep - Test if this is a Data dependence that is
189 /// associated with a register.
190 bool isAssignedRegDep() const {
191 return getKind() == Data && Contents.Reg != 0;
194 /// getReg - Return the register associated with this edge. This is
195 /// only valid on Data, Anti, and Output edges. On Data edges, this
196 /// value may be zero, meaning there is no associated register.
197 unsigned getReg() const {
198 assert((getKind() == Data || getKind() == Anti || getKind() == Output) &&
199 "getReg called on non-register dependence edge!");
203 /// setReg - Assign the associated register for this edge. This is
204 /// only valid on Data, Anti, and Output edges. On Anti and Output
205 /// edges, this value must not be zero. On Data edges, the value may
206 /// be zero, which would mean that no specific register is associated
208 void setReg(unsigned Reg) {
209 assert((getKind() == Data || getKind() == Anti || getKind() == Output) &&
210 "setReg called on non-register dependence edge!");
211 assert((getKind() != Anti || Reg != 0) &&
212 "SDep::Anti edge cannot use the zero register!");
213 assert((getKind() != Output || Reg != 0) &&
214 "SDep::Output edge cannot use the zero register!");
219 /// SUnit - Scheduling unit. This is a node in the scheduling DAG.
222 SDNode *Node; // Representative node.
223 MachineInstr *Instr; // Alternatively, a MachineInstr.
225 SUnit *OrigNode; // If not this, the node from which
226 // this node was cloned.
228 // Preds/Succs - The SUnits before/after us in the graph. The boolean value
229 // is true if the edge is a token chain edge, false if it is a value edge.
230 SmallVector<SDep, 4> Preds; // All sunit predecessors.
231 SmallVector<SDep, 4> Succs; // All sunit successors.
233 typedef SmallVector<SDep, 4>::iterator pred_iterator;
234 typedef SmallVector<SDep, 4>::iterator succ_iterator;
235 typedef SmallVector<SDep, 4>::const_iterator const_pred_iterator;
236 typedef SmallVector<SDep, 4>::const_iterator const_succ_iterator;
238 unsigned NodeNum; // Entry # of node in the node vector.
239 unsigned NodeQueueId; // Queue id of node.
240 unsigned short Latency; // Node latency.
241 short NumPreds; // # of SDep::Data preds.
242 short NumSuccs; // # of SDep::Data sucss.
243 short NumPredsLeft; // # of preds not scheduled.
244 short NumSuccsLeft; // # of succs not scheduled.
245 bool isTwoAddress : 1; // Is a two-address instruction.
246 bool isCommutable : 1; // Is a commutable instruction.
247 bool hasPhysRegDefs : 1; // Has physreg defs that are being used.
248 bool hasPhysRegClobbers : 1; // Has any physreg defs, used or not.
249 bool isPending : 1; // True once pending.
250 bool isAvailable : 1; // True once available.
251 bool isScheduled : 1; // True once scheduled.
252 bool isScheduleHigh : 1; // True if preferable to schedule high.
253 bool isCloned : 1; // True if this node has been cloned.
255 bool isDepthCurrent : 1; // True if Depth is current.
256 bool isHeightCurrent : 1; // True if Height is current.
257 unsigned Depth; // Node depth.
258 unsigned Height; // Node height.
260 const TargetRegisterClass *CopyDstRC; // Is a special copy node if not null.
261 const TargetRegisterClass *CopySrcRC;
263 /// SUnit - Construct an SUnit for pre-regalloc scheduling to represent
264 /// an SDNode and any nodes flagged to it.
265 SUnit(SDNode *node, unsigned nodenum)
266 : Node(node), Instr(0), OrigNode(0), NodeNum(nodenum), NodeQueueId(0),
267 Latency(0), NumPreds(0), NumSuccs(0), NumPredsLeft(0), NumSuccsLeft(0),
268 isTwoAddress(false), isCommutable(false), hasPhysRegDefs(false),
269 hasPhysRegClobbers(false),
270 isPending(false), isAvailable(false), isScheduled(false),
271 isScheduleHigh(false), isCloned(false),
272 isDepthCurrent(false), isHeightCurrent(false), Depth(0), Height(0),
273 CopyDstRC(NULL), CopySrcRC(NULL) {}
275 /// SUnit - Construct an SUnit for post-regalloc scheduling to represent
277 SUnit(MachineInstr *instr, unsigned nodenum)
278 : Node(0), Instr(instr), OrigNode(0), NodeNum(nodenum), NodeQueueId(0),
279 Latency(0), NumPreds(0), NumSuccs(0), NumPredsLeft(0), NumSuccsLeft(0),
280 isTwoAddress(false), isCommutable(false), hasPhysRegDefs(false),
281 hasPhysRegClobbers(false),
282 isPending(false), isAvailable(false), isScheduled(false),
283 isScheduleHigh(false), isCloned(false),
284 isDepthCurrent(false), isHeightCurrent(false), Depth(0), Height(0),
285 CopyDstRC(NULL), CopySrcRC(NULL) {}
287 /// SUnit - Construct a placeholder SUnit.
289 : Node(0), Instr(0), OrigNode(0), NodeNum(~0u), NodeQueueId(0),
290 Latency(0), NumPreds(0), NumSuccs(0), NumPredsLeft(0), NumSuccsLeft(0),
291 isTwoAddress(false), isCommutable(false), hasPhysRegDefs(false),
292 hasPhysRegClobbers(false),
293 isPending(false), isAvailable(false), isScheduled(false),
294 isScheduleHigh(false), isCloned(false),
295 isDepthCurrent(false), isHeightCurrent(false), Depth(0), Height(0),
296 CopyDstRC(NULL), CopySrcRC(NULL) {}
298 /// setNode - Assign the representative SDNode for this SUnit.
299 /// This may be used during pre-regalloc scheduling.
300 void setNode(SDNode *N) {
301 assert(!Instr && "Setting SDNode of SUnit with MachineInstr!");
305 /// getNode - Return the representative SDNode for this SUnit.
306 /// This may be used during pre-regalloc scheduling.
307 SDNode *getNode() const {
308 assert(!Instr && "Reading SDNode of SUnit with MachineInstr!");
312 /// setInstr - Assign the instruction for the SUnit.
313 /// This may be used during post-regalloc scheduling.
314 void setInstr(MachineInstr *MI) {
315 assert(!Node && "Setting MachineInstr of SUnit with SDNode!");
319 /// getInstr - Return the representative MachineInstr for this SUnit.
320 /// This may be used during post-regalloc scheduling.
321 MachineInstr *getInstr() const {
322 assert(!Node && "Reading MachineInstr of SUnit with SDNode!");
326 /// addPred - This adds the specified edge as a pred of the current node if
327 /// not already. It also adds the current node as a successor of the
329 void addPred(const SDep &D);
331 /// removePred - This removes the specified edge as a pred of the current
332 /// node if it exists. It also removes the current node as a successor of
333 /// the specified node.
334 void removePred(const SDep &D);
336 /// getDepth - Return the depth of this node, which is the length of the
337 /// maximum path up to any node with has no predecessors.
338 unsigned getDepth() const {
339 if (!isDepthCurrent) const_cast<SUnit *>(this)->ComputeDepth();
343 /// getHeight - Return the height of this node, which is the length of the
344 /// maximum path down to any node with has no successors.
345 unsigned getHeight() const {
346 if (!isHeightCurrent) const_cast<SUnit *>(this)->ComputeHeight();
350 /// setDepthToAtLeast - If NewDepth is greater than this node's depth
351 /// value, set it to be the new depth value. This also recursively
352 /// marks successor nodes dirty.
353 void setDepthToAtLeast(unsigned NewDepth);
355 /// setDepthToAtLeast - If NewDepth is greater than this node's depth
356 /// value, set it to be the new height value. This also recursively
357 /// marks predecessor nodes dirty.
358 void setHeightToAtLeast(unsigned NewHeight);
360 /// setDepthDirty - Set a flag in this node to indicate that its
361 /// stored Depth value will require recomputation the next time
362 /// getDepth() is called.
363 void setDepthDirty();
365 /// setHeightDirty - Set a flag in this node to indicate that its
366 /// stored Height value will require recomputation the next time
367 /// getHeight() is called.
368 void setHeightDirty();
370 /// isPred - Test if node N is a predecessor of this node.
371 bool isPred(SUnit *N) {
372 for (unsigned i = 0, e = (unsigned)Preds.size(); i != e; ++i)
373 if (Preds[i].getSUnit() == N)
378 /// isSucc - Test if node N is a successor of this node.
379 bool isSucc(SUnit *N) {
380 for (unsigned i = 0, e = (unsigned)Succs.size(); i != e; ++i)
381 if (Succs[i].getSUnit() == N)
386 void dump(const ScheduleDAG *G) const;
387 void dumpAll(const ScheduleDAG *G) const;
388 void print(raw_ostream &O, const ScheduleDAG *G) const;
392 void ComputeHeight();
395 //===--------------------------------------------------------------------===//
396 /// SchedulingPriorityQueue - This interface is used to plug different
397 /// priorities computation algorithms into the list scheduler. It implements
398 /// the interface of a standard priority queue, where nodes are inserted in
399 /// arbitrary order and returned in priority order. The computation of the
400 /// priority and the representation of the queue are totally up to the
401 /// implementation to decide.
403 class SchedulingPriorityQueue {
405 virtual ~SchedulingPriorityQueue() {}
407 virtual void initNodes(std::vector<SUnit> &SUnits) = 0;
408 virtual void addNode(const SUnit *SU) = 0;
409 virtual void updateNode(const SUnit *SU) = 0;
410 virtual void releaseState() = 0;
412 virtual unsigned size() const = 0;
413 virtual bool empty() const = 0;
414 virtual void push(SUnit *U) = 0;
416 virtual void push_all(const std::vector<SUnit *> &Nodes) = 0;
417 virtual SUnit *pop() = 0;
419 virtual void remove(SUnit *SU) = 0;
421 /// ScheduledNode - As each node is scheduled, this method is invoked. This
422 /// allows the priority function to adjust the priority of related
423 /// unscheduled nodes, for example.
425 virtual void ScheduledNode(SUnit *) {}
427 virtual void UnscheduledNode(SUnit *) {}
432 MachineBasicBlock *BB; // The block in which to insert instructions.
433 MachineBasicBlock::iterator InsertPos;// The position to insert instructions.
434 const TargetMachine &TM; // Target processor
435 const TargetInstrInfo *TII; // Target instruction information
436 const TargetRegisterInfo *TRI; // Target processor register info
437 const TargetLowering *TLI; // Target lowering info
438 MachineFunction &MF; // Machine function
439 MachineRegisterInfo &MRI; // Virtual/real register map
440 MachineConstantPool *ConstPool; // Target constant pool
441 std::vector<SUnit*> Sequence; // The schedule. Null SUnit*'s
442 // represent noop instructions.
443 std::vector<SUnit> SUnits; // The scheduling units.
444 SUnit EntrySU; // Special node for the region entry.
445 SUnit ExitSU; // Special node for the region exit.
447 explicit ScheduleDAG(MachineFunction &mf);
449 virtual ~ScheduleDAG();
451 /// viewGraph - Pop up a GraphViz/gv window with the ScheduleDAG rendered
456 /// EmitSchedule - Insert MachineInstrs into the MachineBasicBlock
457 /// according to the order specified in Sequence.
459 virtual MachineBasicBlock *EmitSchedule() = 0;
461 void dumpSchedule() const;
463 virtual void dumpNode(const SUnit *SU) const = 0;
465 /// getGraphNodeLabel - Return a label for an SUnit node in a visualization
466 /// of the ScheduleDAG.
467 virtual std::string getGraphNodeLabel(const SUnit *SU) const = 0;
469 /// addCustomGraphFeatures - Add custom features for a visualization of
471 virtual void addCustomGraphFeatures(GraphWriter<ScheduleDAG*> &) const {}
474 /// VerifySchedule - Verify that all SUnits were scheduled and that
475 /// their state is consistent.
476 void VerifySchedule(bool isBottomUp);
480 /// Run - perform scheduling.
482 void Run(MachineBasicBlock *bb, MachineBasicBlock::iterator insertPos);
484 /// BuildSchedGraph - Build SUnits and set up their Preds and Succs
485 /// to form the scheduling dependency graph.
487 virtual void BuildSchedGraph() = 0;
489 /// ComputeLatency - Compute node latency.
491 virtual void ComputeLatency(SUnit *SU) = 0;
493 /// Schedule - Order nodes according to selected style, filling
494 /// in the Sequence member.
496 virtual void Schedule() = 0;
498 /// ForceUnitLatencies - Return true if all scheduling edges should be given a
499 /// latency value of one. The default is to return false; schedulers may
500 /// override this as needed.
501 virtual bool ForceUnitLatencies() const { return false; }
503 /// EmitNoop - Emit a noop instruction.
507 void AddMemOperand(MachineInstr *MI, const MachineMemOperand &MO);
509 void EmitPhysRegCopy(SUnit *SU, DenseMap<SUnit*, unsigned> &VRBaseMap);
512 /// EmitLiveInCopy - Emit a copy for a live in physical register. If the
513 /// physical register has only a single copy use, then coalesced the copy
515 void EmitLiveInCopy(MachineBasicBlock *MBB,
516 MachineBasicBlock::iterator &InsertPos,
517 unsigned VirtReg, unsigned PhysReg,
518 const TargetRegisterClass *RC,
519 DenseMap<MachineInstr*, unsigned> &CopyRegMap);
521 /// EmitLiveInCopies - If this is the first basic block in the function,
522 /// and if it has live ins that need to be copied into vregs, emit the
523 /// copies into the top of the block.
524 void EmitLiveInCopies(MachineBasicBlock *MBB);
527 class SUnitIterator : public forward_iterator<SUnit, ptrdiff_t> {
531 SUnitIterator(SUnit *N, unsigned Op) : Node(N), Operand(Op) {}
533 bool operator==(const SUnitIterator& x) const {
534 return Operand == x.Operand;
536 bool operator!=(const SUnitIterator& x) const { return !operator==(x); }
538 const SUnitIterator &operator=(const SUnitIterator &I) {
539 assert(I.Node == Node && "Cannot assign iterators to two different nodes!");
544 pointer operator*() const {
545 return Node->Preds[Operand].getSUnit();
547 pointer operator->() const { return operator*(); }
549 SUnitIterator& operator++() { // Preincrement
553 SUnitIterator operator++(int) { // Postincrement
554 SUnitIterator tmp = *this; ++*this; return tmp;
557 static SUnitIterator begin(SUnit *N) { return SUnitIterator(N, 0); }
558 static SUnitIterator end (SUnit *N) {
559 return SUnitIterator(N, (unsigned)N->Preds.size());
562 unsigned getOperand() const { return Operand; }
563 const SUnit *getNode() const { return Node; }
564 /// isCtrlDep - Test if this is not an SDep::Data dependence.
565 bool isCtrlDep() const {
566 return getSDep().isCtrl();
568 bool isArtificialDep() const {
569 return getSDep().isArtificial();
571 const SDep &getSDep() const {
572 return Node->Preds[Operand];
576 template <> struct GraphTraits<SUnit*> {
577 typedef SUnit NodeType;
578 typedef SUnitIterator ChildIteratorType;
579 static inline NodeType *getEntryNode(SUnit *N) { return N; }
580 static inline ChildIteratorType child_begin(NodeType *N) {
581 return SUnitIterator::begin(N);
583 static inline ChildIteratorType child_end(NodeType *N) {
584 return SUnitIterator::end(N);
588 template <> struct GraphTraits<ScheduleDAG*> : public GraphTraits<SUnit*> {
589 typedef std::vector<SUnit>::iterator nodes_iterator;
590 static nodes_iterator nodes_begin(ScheduleDAG *G) {
591 return G->SUnits.begin();
593 static nodes_iterator nodes_end(ScheduleDAG *G) {
594 return G->SUnits.end();
598 /// ScheduleDAGTopologicalSort is a class that computes a topological
599 /// ordering for SUnits and provides methods for dynamically updating
600 /// the ordering as new edges are added.
602 /// This allows a very fast implementation of IsReachable, for example.
604 class ScheduleDAGTopologicalSort {
605 /// SUnits - A reference to the ScheduleDAG's SUnits.
606 std::vector<SUnit> &SUnits;
608 /// Index2Node - Maps topological index to the node number.
609 std::vector<int> Index2Node;
610 /// Node2Index - Maps the node number to its topological index.
611 std::vector<int> Node2Index;
612 /// Visited - a set of nodes visited during a DFS traversal.
615 /// DFS - make a DFS traversal and mark all nodes affected by the
616 /// edge insertion. These nodes will later get new topological indexes
617 /// by means of the Shift method.
618 void DFS(const SUnit *SU, int UpperBound, bool& HasLoop);
620 /// Shift - reassign topological indexes for the nodes in the DAG
621 /// to preserve the topological ordering.
622 void Shift(BitVector& Visited, int LowerBound, int UpperBound);
624 /// Allocate - assign the topological index to the node n.
625 void Allocate(int n, int index);
628 explicit ScheduleDAGTopologicalSort(std::vector<SUnit> &SUnits);
630 /// InitDAGTopologicalSorting - create the initial topological
631 /// ordering from the DAG to be scheduled.
632 void InitDAGTopologicalSorting();
634 /// IsReachable - Checks if SU is reachable from TargetSU.
635 bool IsReachable(const SUnit *SU, const SUnit *TargetSU);
637 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU
638 /// will create a cycle.
639 bool WillCreateCycle(SUnit *SU, SUnit *TargetSU);
641 /// AddPred - Updates the topological ordering to accomodate an edge
642 /// to be added from SUnit X to SUnit Y.
643 void AddPred(SUnit *Y, SUnit *X);
645 /// RemovePred - Updates the topological ordering to accomodate an
646 /// an edge to be removed from the specified node N from the predecessors
647 /// of the current node M.
648 void RemovePred(SUnit *M, SUnit *N);
650 typedef std::vector<int>::iterator iterator;
651 typedef std::vector<int>::const_iterator const_iterator;
652 iterator begin() { return Index2Node.begin(); }
653 const_iterator begin() const { return Index2Node.begin(); }
654 iterator end() { return Index2Node.end(); }
655 const_iterator end() const { return Index2Node.end(); }
657 typedef std::vector<int>::reverse_iterator reverse_iterator;
658 typedef std::vector<int>::const_reverse_iterator const_reverse_iterator;
659 reverse_iterator rbegin() { return Index2Node.rbegin(); }
660 const_reverse_iterator rbegin() const { return Index2Node.rbegin(); }
661 reverse_iterator rend() { return Index2Node.rend(); }
662 const_reverse_iterator rend() const { return Index2Node.rend(); }