1 //===-- ScheduleDAG.cpp - Implement a trivial DAG scheduler ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Chris Lattner and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements a simple two pass scheduler. The first pass attempts to push
11 // backward any lengthy instructions and critical paths. The second pass packs
12 // instructions into semi-optimal time slots.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "sched"
17 #include "llvm/CodeGen/MachineConstantPool.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 #include "llvm/CodeGen/SelectionDAGISel.h"
20 #include "llvm/CodeGen/SelectionDAG.h"
21 #include "llvm/CodeGen/SSARegMap.h"
22 #include "llvm/Target/TargetMachine.h"
23 #include "llvm/Target/TargetInstrInfo.h"
24 #include "llvm/Target/TargetLowering.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/Debug.h"
31 // Style of scheduling to use.
32 enum ScheduleChoices {
38 cl::opt<ScheduleChoices> ScheduleStyle("sched",
39 cl::desc("Choose scheduling style"),
40 cl::init(noScheduling),
42 clEnumValN(noScheduling, "none",
43 "Trivial emission with no analysis"),
44 clEnumValN(simpleScheduling, "simple",
45 "Minimize critical path and maximize processor utilization"),
51 ViewDAGs("view-sched-dags", cl::Hidden,
52 cl::desc("Pop up a window to show sched dags as they are processed"));
54 static const bool ViewDAGs = 0;
58 //===----------------------------------------------------------------------===//
60 /// BitsIterator - Provides iteration through individual bits in a bit vector.
65 T Bits; // Bits left to iterate through
69 BitsIterator(T Initial) : Bits(Initial) {}
71 /// Next - Returns the next bit set or zero if exhausted.
73 // Get the rightmost bit set
74 T Result = Bits & -Bits;
77 // Return single bit or zero
82 //===----------------------------------------------------------------------===//
85 //===----------------------------------------------------------------------===//
87 /// ResourceTally - Manages the use of resources over time intervals. Each
88 /// item (slot) in the tally vector represents the resources used at a given
89 /// moment. A bit set to 1 indicates that a resource is in use, otherwise
90 /// available. An assumption is made that the tally is large enough to schedule
91 /// all current instructions (asserts otherwise.)
96 std::vector<T> Tally; // Resources used per slot
97 typedef typename std::vector<T>::iterator Iter;
100 /// AllInUse - Test to see if all of the resources in the slot are busy (set.)
101 inline bool AllInUse(Iter Cursor, unsigned ResourceSet) {
102 return (*Cursor & ResourceSet) == ResourceSet;
105 /// Skip - Skip over slots that use all of the specified resource (all are
107 Iter Skip(Iter Cursor, unsigned ResourceSet) {
108 assert(ResourceSet && "At least one resource bit needs to bet set");
110 // Continue to the end
112 // Break out if one of the resource bits is not set
113 if (!AllInUse(Cursor, ResourceSet)) return Cursor;
116 assert(Cursor < Tally.end() && "Tally is not large enough for schedule");
120 /// FindSlots - Starting from Begin, locate N consecutive slots where at least
121 /// one of the resource bits is available. Returns the address of first slot.
122 Iter FindSlots(Iter Begin, unsigned N, unsigned ResourceSet,
123 unsigned &Resource) {
127 // Try all possible slots forward
130 Cursor = Skip(Cursor, ResourceSet);
131 // Determine end of interval
132 Iter End = Cursor + N;
133 assert(End <= Tally.end() && "Tally is not large enough for schedule");
135 // Iterate thru each resource
136 BitsIterator<T> Resources(ResourceSet & ~*Cursor);
137 while (unsigned Res = Resources.Next()) {
138 // Check if resource is available for next N slots
139 // Break out if resource is busy
140 Iter Interval = Cursor;
141 for (; Interval < End && !(*Interval & Res); Interval++) {}
143 // If available for interval, return where and which resource
144 if (Interval == End) {
148 // Otherwise, check if worth checking other resources
149 if (AllInUse(Interval, ResourceSet)) {
150 // Start looking beyond interval
159 /// Reserve - Mark busy (set) the specified N slots.
160 void Reserve(Iter Begin, unsigned N, unsigned Resource) {
161 // Determine end of interval
162 Iter End = Begin + N;
163 assert(End <= Tally.end() && "Tally is not large enough for schedule");
165 // Set resource bit in each slot
166 for (; Begin < End; Begin++)
171 /// Initialize - Resize and zero the tally to the specified number of time
173 inline void Initialize(unsigned N) {
174 Tally.assign(N, 0); // Initialize tally to all zeros.
177 // FindAndReserve - Locate and mark busy (set) N bits started at slot I, using
178 // ResourceSet for choices.
179 unsigned FindAndReserve(unsigned I, unsigned N, unsigned ResourceSet) {
180 // Which resource used
182 // Find slots for instruction.
183 Iter Where = FindSlots(Tally.begin() + I, N, ResourceSet, Resource);
185 Reserve(Where, N, Resource);
186 // Return time slot (index)
187 return Where - Tally.begin();
191 //===----------------------------------------------------------------------===//
194 //===----------------------------------------------------------------------===//
196 /// Node group - This struct is used to manage flagged node groups.
199 class NodeGroup : public std::vector<NodeInfo *> {
201 int Pending; // Number of visits pending before
206 NodeGroup() : Pending(0) {}
209 inline NodeInfo *getLeader() { return empty() ? NULL : front(); }
210 inline int getPending() const { return Pending; }
211 inline void setPending(int P) { Pending = P; }
212 inline int addPending(int I) { return Pending += I; }
214 static void Add(NodeInfo *D, NodeInfo *U);
215 static unsigned CountInternalUses(NodeInfo *D, NodeInfo *U);
217 //===----------------------------------------------------------------------===//
220 //===----------------------------------------------------------------------===//
222 /// NodeInfo - This struct tracks information used to schedule the a node.
226 int Pending; // Number of visits pending before
229 SDNode *Node; // DAG node
230 unsigned Latency; // Cycles to complete instruction
231 unsigned ResourceSet; // Bit vector of usable resources
232 unsigned Slot; // Node's time slot
233 NodeGroup *Group; // Grouping information
234 unsigned VRBase; // Virtual register base
237 NodeInfo(SDNode *N = NULL)
248 inline bool isInGroup() const {
249 assert(!Group || !Group->empty() && "Group with no members");
250 return Group != NULL;
252 inline bool isGroupLeader() const {
253 return isInGroup() && Group->getLeader() == this;
255 inline int getPending() const {
256 return Group ? Group->getPending() : Pending;
258 inline void setPending(int P) {
259 if (Group) Group->setPending(P);
262 inline int addPending(int I) {
263 if (Group) return Group->addPending(I);
264 else return Pending += I;
267 typedef std::vector<NodeInfo *>::iterator NIIterator;
268 //===----------------------------------------------------------------------===//
271 //===----------------------------------------------------------------------===//
273 /// NodeGroupIterator - Iterates over all the nodes indicated by the node info.
274 /// If the node is in a group then iterate over the members of the group,
275 /// otherwise just the node info.
277 class NodeGroupIterator {
279 NodeInfo *NI; // Node info
280 NIIterator NGI; // Node group iterator
281 NIIterator NGE; // Node group iterator end
285 NodeGroupIterator(NodeInfo *N) : NI(N) {
286 // If the node is in a group then set up the group iterator. Otherwise
287 // the group iterators will trip first time out.
288 if (N->isInGroup()) {
290 NodeGroup *Group = NI->Group;
291 NGI = Group->begin();
293 // Prevent this node from being used (will be in members list
298 /// next - Return the next node info, otherwise NULL.
302 if (NGI != NGE) return *NGI++;
303 // Use node as the result (may be NULL)
304 NodeInfo *Result = NI;
307 // Return node or NULL
311 //===----------------------------------------------------------------------===//
314 //===----------------------------------------------------------------------===//
316 /// NodeGroupOpIterator - Iterates over all the operands of a node. If the node
317 /// is a member of a group, this iterates over all the operands of all the
318 /// members of the group.
320 class NodeGroupOpIterator {
322 NodeInfo *NI; // Node containing operands
323 NodeGroupIterator GI; // Node group iterator
324 SDNode::op_iterator OI; // Operand iterator
325 SDNode::op_iterator OE; // Operand iterator end
327 /// CheckNode - Test if node has more operands. If not get the next node
328 /// skipping over nodes that have no operands.
330 // Only if operands are exhausted first
332 // Get next node info
333 NodeInfo *NI = GI.next();
334 // Exit if nodes are exhausted
337 SDNode *Node = NI->Node;
338 // Set up the operand iterators
339 OI = Node->op_begin();
346 NodeGroupOpIterator(NodeInfo *N) : NI(N), GI(N) {}
348 /// isEnd - Returns true when not more operands are available.
350 inline bool isEnd() { CheckNode(); return OI == OE; }
352 /// next - Returns the next available operand.
354 inline SDOperand next() {
355 assert(OI != OE && "Not checking for end of NodeGroupOpIterator correctly");
359 //===----------------------------------------------------------------------===//
362 //===----------------------------------------------------------------------===//
364 /// SimpleSched - Simple two pass scheduler.
368 // TODO - get ResourceSet from TII
370 RSInteger = 0x3, // Two integer units
371 RSFloat = 0xC, // Two float units
372 RSLoadStore = 0x30, // Two load store units
373 RSOther = 0 // Processing unit independent
376 MachineBasicBlock *BB; // Current basic block
377 SelectionDAG &DAG; // DAG of the current basic block
378 const TargetMachine &TM; // Target processor
379 const TargetInstrInfo &TII; // Target instruction information
380 const MRegisterInfo &MRI; // Target processor register information
381 SSARegMap *RegMap; // Virtual/real register map
382 MachineConstantPool *ConstPool; // Target constant pool
383 unsigned NodeCount; // Number of nodes in DAG
384 NodeInfo *Info; // Info for nodes being scheduled
385 std::map<SDNode *, NodeInfo *> Map; // Map nodes to info
386 std::vector<NodeInfo*> Ordering; // Emit ordering of nodes
387 ResourceTally<unsigned> Tally; // Resource usage tally
388 unsigned NSlots; // Total latency
389 static const unsigned NotFound = ~0U; // Search marker
394 SimpleSched(SelectionDAG &D, MachineBasicBlock *bb)
395 : BB(bb), DAG(D), TM(D.getTarget()), TII(*TM.getInstrInfo()),
396 MRI(*TM.getRegisterInfo()), RegMap(BB->getParent()->getSSARegMap()),
397 ConstPool(BB->getParent()->getConstantPool()),
399 assert(&TII && "Target doesn't provide instr info?");
400 assert(&MRI && "Target doesn't provide register info?");
403 // Run - perform scheduling.
404 MachineBasicBlock *Run() {
410 /// getNI - Returns the node info for the specified node.
412 inline NodeInfo *getNI(SDNode *Node) { return Map[Node]; }
414 /// getVR - Returns the virtual register number of the node.
416 inline unsigned getVR(SDOperand Op) {
417 NodeInfo *NI = getNI(Op.Val);
418 assert(NI->VRBase != 0 && "Node emitted out of order - late");
419 return NI->VRBase + Op.ResNo;
422 static bool isFlagDefiner(SDNode *A);
423 static bool isFlagUser(SDNode *A);
424 static bool isDefiner(NodeInfo *A, NodeInfo *B);
425 static bool isPassiveNode(SDNode *Node);
426 void IncludeNode(NodeInfo *NI);
429 void IdentifyGroups();
430 void GatherSchedulingInfo();
431 void PrepareNodeInfo();
432 bool isStrongDependency(NodeInfo *A, NodeInfo *B);
433 bool isWeakDependency(NodeInfo *A, NodeInfo *B);
434 void ScheduleBackward();
435 void ScheduleForward();
437 void EmitNode(NodeInfo *NI);
438 static unsigned CountResults(SDNode *Node);
439 static unsigned CountOperands(SDNode *Node);
440 unsigned CreateVirtualRegisters(MachineInstr *MI,
442 const TargetInstrDescriptor &II);
443 unsigned EmitDAG(SDOperand A);
445 void printSI(std::ostream &O, NodeInfo *NI) const;
446 void print(std::ostream &O) const;
447 inline void dump(const char *tag) const { std::cerr << tag; dump(); }
450 //===----------------------------------------------------------------------===//
454 //===----------------------------------------------------------------------===//
457 //===----------------------------------------------------------------------===//
458 /// Add - Adds a definer and user pair to a node group.
460 void NodeGroup::Add(NodeInfo *D, NodeInfo *U) {
461 // Get current groups
462 NodeGroup *DGroup = D->Group;
463 NodeGroup *UGroup = U->Group;
464 // If both are members of groups
465 if (DGroup && UGroup) {
466 // There may have been another edge connecting
467 if (DGroup == UGroup) return;
468 // Add the pending users count
469 DGroup->addPending(UGroup->getPending());
470 // For each member of the users group
471 NodeGroupIterator UNGI(U);
472 while (NodeInfo *UNI = UNGI.next() ) {
475 // For each member of the definers group
476 NodeGroupIterator DNGI(D);
477 while (NodeInfo *DNI = DNGI.next() ) {
478 // Remove internal edges
479 DGroup->addPending(-CountInternalUses(DNI, UNI));
482 // Merge the two lists
483 DGroup->insert(DGroup->end(), UGroup->begin(), UGroup->end());
485 // Make user member of definers group
487 // Add users uses to definers group pending
488 DGroup->addPending(U->Node->use_size());
489 // For each member of the definers group
490 NodeGroupIterator DNGI(D);
491 while (NodeInfo *DNI = DNGI.next() ) {
492 // Remove internal edges
493 DGroup->addPending(-CountInternalUses(DNI, U));
495 DGroup->push_back(U);
497 // Make definer member of users group
499 // Add definers uses to users group pending
500 UGroup->addPending(D->Node->use_size());
501 // For each member of the users group
502 NodeGroupIterator UNGI(U);
503 while (NodeInfo *UNI = UNGI.next() ) {
504 // Remove internal edges
505 UGroup->addPending(-CountInternalUses(D, UNI));
507 UGroup->insert(UGroup->begin(), D);
509 D->Group = U->Group = DGroup = new NodeGroup();
510 DGroup->addPending(D->Node->use_size() + U->Node->use_size() -
511 CountInternalUses(D, U));
512 DGroup->push_back(D);
513 DGroup->push_back(U);
517 /// CountInternalUses - Returns the number of edges between the two nodes.
519 unsigned NodeGroup::CountInternalUses(NodeInfo *D, NodeInfo *U) {
521 for (SDNode:: use_iterator UI = D->Node->use_begin(),
522 E = D->Node->use_end(); UI != E; UI++) {
523 if (*UI == U->Node) N++;
527 //===----------------------------------------------------------------------===//
530 //===----------------------------------------------------------------------===//
531 /// isFlagDefiner - Returns true if the node defines a flag result.
532 bool SimpleSched::isFlagDefiner(SDNode *A) {
533 unsigned N = A->getNumValues();
534 return N && A->getValueType(N - 1) == MVT::Flag;
537 /// isFlagUser - Returns true if the node uses a flag result.
539 bool SimpleSched::isFlagUser(SDNode *A) {
540 unsigned N = A->getNumOperands();
541 return N && A->getOperand(N - 1).getValueType() == MVT::Flag;
544 /// isDefiner - Return true if node A is a definer for B.
546 bool SimpleSched::isDefiner(NodeInfo *A, NodeInfo *B) {
547 // While there are A nodes
548 NodeGroupIterator NII(A);
549 while (NodeInfo *NI = NII.next()) {
551 SDNode *Node = NI->Node;
552 // While there operands in nodes of B
553 NodeGroupOpIterator NGOI(B);
554 while (!NGOI.isEnd()) {
555 SDOperand Op = NGOI.next();
556 // If node from A defines a node in B
557 if (Node == Op.Val) return true;
563 /// isPassiveNode - Return true if the node is a non-scheduled leaf.
565 bool SimpleSched::isPassiveNode(SDNode *Node) {
566 if (isa<ConstantSDNode>(Node)) return true;
567 if (isa<RegisterSDNode>(Node)) return true;
568 if (isa<GlobalAddressSDNode>(Node)) return true;
569 if (isa<BasicBlockSDNode>(Node)) return true;
570 if (isa<FrameIndexSDNode>(Node)) return true;
571 if (isa<ConstantPoolSDNode>(Node)) return true;
572 if (isa<ExternalSymbolSDNode>(Node)) return true;
576 /// IncludeNode - Add node to NodeInfo vector.
578 void SimpleSched::IncludeNode(NodeInfo *NI) {
580 SDNode *Node = NI->Node;
582 if (Node->getOpcode() == ISD::EntryToken) return;
583 // Check current count for node
584 int Count = NI->getPending();
585 // If the node is already in list
586 if (Count < 0) return;
587 // Decrement count to indicate a visit
589 // If count has gone to zero then add node to list
592 if (NI->isInGroup()) {
593 Ordering.push_back(NI->Group->getLeader());
595 Ordering.push_back(NI);
597 // indicate node has been added
600 // Mark as visited with new count
601 NI->setPending(Count);
604 /// VisitAll - Visit each node breadth-wise to produce an initial ordering.
605 /// Note that the ordering in the Nodes vector is reversed.
606 void SimpleSched::VisitAll() {
607 // Add first element to list
608 Ordering.push_back(getNI(DAG.getRoot().Val));
610 // Iterate through all nodes that have been added
611 for (unsigned i = 0; i < Ordering.size(); i++) { // note: size() varies
612 // Visit all operands
613 NodeGroupOpIterator NGI(Ordering[i]);
614 while (!NGI.isEnd()) {
616 SDOperand Op = NGI.next();
618 SDNode *Node = Op.Val;
619 // Ignore passive nodes
620 if (isPassiveNode(Node)) continue;
622 IncludeNode(getNI(Node));
626 // Add entry node last (IncludeNode filters entry nodes)
627 if (DAG.getEntryNode().Val != DAG.getRoot().Val)
628 Ordering.push_back(getNI(DAG.getEntryNode().Val));
630 // FIXME - Reverse the order
631 for (unsigned i = 0, N = Ordering.size(), Half = N >> 1; i < Half; i++) {
632 unsigned j = N - i - 1;
633 NodeInfo *tmp = Ordering[i];
634 Ordering[i] = Ordering[j];
639 /// IdentifyGroups - Put flagged nodes into groups.
641 void SimpleSched::IdentifyGroups() {
642 for (unsigned i = 0, N = NodeCount; i < N; i++) {
643 NodeInfo* NI = &Info[i];
644 SDNode *Node = NI->Node;
646 // For each operand (in reverse to only look at flags)
647 for (unsigned N = Node->getNumOperands(); 0 < N--;) {
649 SDOperand Op = Node->getOperand(N);
650 // No more flags to walk
651 if (Op.getValueType() != MVT::Flag) break;
653 NodeGroup::Add(getNI(Op.Val), NI);
658 /// GatherSchedulingInfo - Get latency and resource information about each node.
660 void SimpleSched::GatherSchedulingInfo() {
661 for (unsigned i = 0, N = NodeCount; i < N; i++) {
662 NodeInfo* NI = &Info[i];
663 SDNode *Node = NI->Node;
665 MVT::ValueType VT = Node->getValueType(0);
667 if (Node->isTargetOpcode()) {
668 MachineOpCode TOpc = Node->getTargetOpcode();
669 // FIXME: This is an ugly (but temporary!) hack to test the scheduler
670 // before we have real target info.
671 // FIXME NI->Latency = std::max(1, TII.maxLatency(TOpc));
672 // FIXME NI->ResourceSet = TII.resources(TOpc);
673 if (TII.isCall(TOpc)) {
674 NI->ResourceSet = RSInteger;
676 } else if (TII.isLoad(TOpc)) {
677 NI->ResourceSet = RSLoadStore;
679 } else if (TII.isStore(TOpc)) {
680 NI->ResourceSet = RSLoadStore;
682 } else if (MVT::isInteger(VT)) {
683 NI->ResourceSet = RSInteger;
685 } else if (MVT::isFloatingPoint(VT)) {
686 NI->ResourceSet = RSFloat;
689 NI->ResourceSet = RSOther;
693 if (MVT::isInteger(VT)) {
694 NI->ResourceSet = RSInteger;
696 } else if (MVT::isFloatingPoint(VT)) {
697 NI->ResourceSet = RSFloat;
700 NI->ResourceSet = RSOther;
705 // Add one slot for the instruction itself
708 // Sum up all the latencies for max tally size
709 NSlots += NI->Latency;
713 /// PrepareNodeInfo - Set up the basic minimum node info for scheduling.
715 void SimpleSched::PrepareNodeInfo() {
716 // Allocate node information
717 Info = new NodeInfo[NodeCount];
718 // Get base of all nodes table
719 SelectionDAG::allnodes_iterator AllNodes = DAG.allnodes_begin();
721 // For each node being scheduled
722 for (unsigned i = 0, N = NodeCount; i < N; i++) {
723 // Get next node from DAG all nodes table
724 SDNode *Node = AllNodes[i];
725 // Fast reference to node schedule info
726 NodeInfo* NI = &Info[i];
731 // Set pending visit count
732 NI->setPending(Node->use_size());
736 /// isStrongDependency - Return true if node A has results used by node B.
737 /// I.E., B must wait for latency of A.
738 bool SimpleSched::isStrongDependency(NodeInfo *A, NodeInfo *B) {
739 // If A defines for B then it's a strong dependency
740 return isDefiner(A, B);
743 /// isWeakDependency Return true if node A produces a result that will
744 /// conflict with operands of B.
745 bool SimpleSched::isWeakDependency(NodeInfo *A, NodeInfo *B) {
746 // TODO check for conflicting real registers and aliases
747 #if 0 // FIXME - Since we are in SSA form and not checking register aliasing
748 return A->Node->getOpcode() == ISD::EntryToken || isStrongDependency(B, A);
750 return A->Node->getOpcode() == ISD::EntryToken;
754 /// ScheduleBackward - Schedule instructions so that any long latency
755 /// instructions and the critical path get pushed back in time. Time is run in
756 /// reverse to allow code reuse of the Tally and eliminate the overhead of
757 /// biasing every slot indices against NSlots.
758 void SimpleSched::ScheduleBackward() {
759 // Size and clear the resource tally
760 Tally.Initialize(NSlots);
761 // Get number of nodes to schedule
762 unsigned N = Ordering.size();
764 // For each node being scheduled
765 for (unsigned i = N; 0 < i--;) {
766 NodeInfo *NI = Ordering[i];
768 unsigned Slot = NotFound;
770 // Compare against those previously scheduled nodes
773 // Get following instruction
774 NodeInfo *Other = Ordering[j];
776 // Check dependency against previously inserted nodes
777 if (isStrongDependency(NI, Other)) {
778 Slot = Other->Slot + Other->Latency;
780 } else if (isWeakDependency(NI, Other)) {
786 // If independent of others (or first entry)
787 if (Slot == NotFound) Slot = 0;
789 // Find a slot where the needed resources are available
791 Slot = Tally.FindAndReserve(Slot, NI->Latency, NI->ResourceSet);
796 // Insert sort based on slot
799 // Get following instruction
800 NodeInfo *Other = Ordering[j];
801 // Should we look further
802 if (Slot >= Other->Slot) break;
803 // Shuffle other into ordering
804 Ordering[j - 1] = Other;
806 // Insert node in proper slot
807 if (j != i + 1) Ordering[j - 1] = NI;
811 /// ScheduleForward - Schedule instructions to maximize packing.
813 void SimpleSched::ScheduleForward() {
814 // Size and clear the resource tally
815 Tally.Initialize(NSlots);
816 // Get number of nodes to schedule
817 unsigned N = Ordering.size();
819 // For each node being scheduled
820 for (unsigned i = 0; i < N; i++) {
821 NodeInfo *NI = Ordering[i];
823 unsigned Slot = NotFound;
825 // Compare against those previously scheduled nodes
828 // Get following instruction
829 NodeInfo *Other = Ordering[j];
831 // Check dependency against previously inserted nodes
832 if (isStrongDependency(Other, NI)) {
833 Slot = Other->Slot + Other->Latency;
835 } else if (isWeakDependency(Other, NI)) {
841 // If independent of others (or first entry)
842 if (Slot == NotFound) Slot = 0;
844 // Find a slot where the needed resources are available
846 Slot = Tally.FindAndReserve(Slot, NI->Latency, NI->ResourceSet);
851 // Insert sort based on slot
854 // Get following instruction
855 NodeInfo *Other = Ordering[j];
856 // Should we look further
857 if (Slot >= Other->Slot) break;
858 // Shuffle other into ordering
859 Ordering[j + 1] = Other;
861 // Insert node in proper slot
862 if (j != i) Ordering[j + 1] = NI;
866 /// EmitAll - Emit all nodes in schedule sorted order.
868 void SimpleSched::EmitAll() {
869 // For each node in the ordering
870 for (unsigned i = 0, N = Ordering.size(); i < N; i++) {
871 // Get the scheduling info
872 NodeInfo *NI = Ordering[i];
874 // Iterate through nodes
875 NodeGroupIterator NGI(Ordering[i]);
876 while (NodeInfo *NI = NGI.next()) EmitNode(NI);
878 if (NI->isInGroup()) {
879 if (NI->isGroupLeader()) {
880 NodeGroupIterator NGI(Ordering[i]);
881 while (NodeInfo *NI = NGI.next()) EmitNode(NI);
890 /// CountResults - The results of target nodes have register or immediate
891 /// operands first, then an optional chain, and optional flag operands (which do
892 /// not go into the machine instrs.)
893 unsigned SimpleSched::CountResults(SDNode *Node) {
894 unsigned N = Node->getNumValues();
895 while (N && Node->getValueType(N - 1) == MVT::Flag)
897 if (N && Node->getValueType(N - 1) == MVT::Other)
898 --N; // Skip over chain result.
902 /// CountOperands The inputs to target nodes have any actual inputs first,
903 /// followed by an optional chain operand, then flag operands. Compute the
904 /// number of actual operands that will go into the machine instr.
905 unsigned SimpleSched::CountOperands(SDNode *Node) {
906 unsigned N = Node->getNumOperands();
907 while (N && Node->getOperand(N - 1).getValueType() == MVT::Flag)
909 if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
910 --N; // Ignore chain if it exists.
914 /// CreateVirtualRegisters - Add result register values for things that are
915 /// defined by this instruction.
916 unsigned SimpleSched::CreateVirtualRegisters(MachineInstr *MI,
918 const TargetInstrDescriptor &II) {
919 // Create the result registers for this node and add the result regs to
920 // the machine instruction.
921 const TargetOperandInfo *OpInfo = II.OpInfo;
922 unsigned ResultReg = RegMap->createVirtualRegister(OpInfo[0].RegClass);
923 MI->addRegOperand(ResultReg, MachineOperand::Def);
924 for (unsigned i = 1; i != NumResults; ++i) {
925 assert(OpInfo[i].RegClass && "Isn't a register operand!");
926 MI->addRegOperand(RegMap->createVirtualRegister(OpInfo[i].RegClass),
927 MachineOperand::Def);
932 /// EmitNode - Generate machine code for an node and needed dependencies.
934 void SimpleSched::EmitNode(NodeInfo *NI) {
935 unsigned VRBase = 0; // First virtual register for node
936 SDNode *Node = NI->Node;
938 // If machine instruction
939 if (Node->isTargetOpcode()) {
940 unsigned Opc = Node->getTargetOpcode();
941 const TargetInstrDescriptor &II = TII.get(Opc);
943 unsigned NumResults = CountResults(Node);
944 unsigned NodeOperands = CountOperands(Node);
945 unsigned NumMIOperands = NodeOperands + NumResults;
947 assert((unsigned(II.numOperands) == NumMIOperands || II.numOperands == -1)&&
948 "#operands for dag node doesn't match .td file!");
951 // Create the new machine instruction.
952 MachineInstr *MI = new MachineInstr(Opc, NumMIOperands, true, true);
954 // Add result register values for things that are defined by this
956 if (NumResults) VRBase = CreateVirtualRegisters(MI, NumResults, II);
958 // Emit all of the actual operands of this instruction, adding them to the
959 // instruction as appropriate.
960 for (unsigned i = 0; i != NodeOperands; ++i) {
961 if (Node->getOperand(i).isTargetOpcode()) {
962 // Note that this case is redundant with the final else block, but we
963 // include it because it is the most common and it makes the logic
965 assert(Node->getOperand(i).getValueType() != MVT::Other &&
966 Node->getOperand(i).getValueType() != MVT::Flag &&
967 "Chain and flag operands should occur at end of operand list!");
969 // Get/emit the operand.
970 unsigned VReg = getVR(Node->getOperand(i));
971 MI->addRegOperand(VReg, MachineOperand::Use);
973 // Verify that it is right.
974 assert(MRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
975 assert(II.OpInfo[i+NumResults].RegClass &&
976 "Don't have operand info for this instruction!");
977 assert(RegMap->getRegClass(VReg) == II.OpInfo[i+NumResults].RegClass &&
978 "Register class of operand and regclass of use don't agree!");
979 } else if (ConstantSDNode *C =
980 dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
981 MI->addZeroExtImm64Operand(C->getValue());
982 } else if (RegisterSDNode*R =
983 dyn_cast<RegisterSDNode>(Node->getOperand(i))) {
984 MI->addRegOperand(R->getReg(), MachineOperand::Use);
985 } else if (GlobalAddressSDNode *TGA =
986 dyn_cast<GlobalAddressSDNode>(Node->getOperand(i))) {
987 MI->addGlobalAddressOperand(TGA->getGlobal(), false, 0);
988 } else if (BasicBlockSDNode *BB =
989 dyn_cast<BasicBlockSDNode>(Node->getOperand(i))) {
990 MI->addMachineBasicBlockOperand(BB->getBasicBlock());
991 } else if (FrameIndexSDNode *FI =
992 dyn_cast<FrameIndexSDNode>(Node->getOperand(i))) {
993 MI->addFrameIndexOperand(FI->getIndex());
994 } else if (ConstantPoolSDNode *CP =
995 dyn_cast<ConstantPoolSDNode>(Node->getOperand(i))) {
996 unsigned Idx = ConstPool->getConstantPoolIndex(CP->get());
997 MI->addConstantPoolIndexOperand(Idx);
998 } else if (ExternalSymbolSDNode *ES =
999 dyn_cast<ExternalSymbolSDNode>(Node->getOperand(i))) {
1000 MI->addExternalSymbolOperand(ES->getSymbol(), false);
1002 assert(Node->getOperand(i).getValueType() != MVT::Other &&
1003 Node->getOperand(i).getValueType() != MVT::Flag &&
1004 "Chain and flag operands should occur at end of operand list!");
1005 unsigned VReg = getVR(Node->getOperand(i));
1006 MI->addRegOperand(VReg, MachineOperand::Use);
1008 // Verify that it is right.
1009 assert(MRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
1010 assert(II.OpInfo[i+NumResults].RegClass &&
1011 "Don't have operand info for this instruction!");
1012 assert(RegMap->getRegClass(VReg) == II.OpInfo[i+NumResults].RegClass &&
1013 "Register class of operand and regclass of use don't agree!");
1017 // Now that we have emitted all operands, emit this instruction itself.
1018 if ((II.Flags & M_USES_CUSTOM_DAG_SCHED_INSERTION) == 0) {
1019 BB->insert(BB->end(), MI);
1021 // Insert this instruction into the end of the basic block, potentially
1022 // taking some custom action.
1023 BB = DAG.getTargetLoweringInfo().InsertAtEndOfBasicBlock(MI, BB);
1026 switch (Node->getOpcode()) {
1029 assert(0 && "This target-independent node should have been selected!");
1030 case ISD::EntryToken: // fall thru
1031 case ISD::TokenFactor:
1033 case ISD::CopyToReg: {
1034 unsigned Val = getVR(Node->getOperand(2));
1035 MRI.copyRegToReg(*BB, BB->end(),
1036 cast<RegisterSDNode>(Node->getOperand(1))->getReg(), Val,
1037 RegMap->getRegClass(Val));
1040 case ISD::CopyFromReg: {
1041 unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
1043 // Figure out the register class to create for the destreg.
1044 const TargetRegisterClass *TRC = 0;
1045 if (MRegisterInfo::isVirtualRegister(SrcReg)) {
1046 TRC = RegMap->getRegClass(SrcReg);
1048 // Pick the register class of the right type that contains this physreg.
1049 for (MRegisterInfo::regclass_iterator I = MRI.regclass_begin(),
1050 E = MRI.regclass_end(); I != E; ++I)
1051 if ((*I)->getType() == Node->getValueType(0) &&
1052 (*I)->contains(SrcReg)) {
1056 assert(TRC && "Couldn't find register class for reg copy!");
1059 // Create the reg, emit the copy.
1060 VRBase = RegMap->createVirtualRegister(TRC);
1061 MRI.copyRegToReg(*BB, BB->end(), VRBase, SrcReg, TRC);
1067 assert(NI->VRBase == 0 && "Node emitted out of order - early");
1068 NI->VRBase = VRBase;
1071 /// Schedule - Order nodes according to selected style.
1073 void SimpleSched::Schedule() {
1075 NodeCount = DAG.allnodes_size();
1076 // Set up minimum info for scheduling.
1078 // Construct node groups for flagged nodes
1080 // Breadth first walk of DAG
1083 // Don't waste time if is only entry and return
1084 if (ScheduleStyle != noScheduling && NodeCount > 3) {
1085 // Get latency and resource requirements
1086 GatherSchedulingInfo();
1087 DEBUG(dump("Pre-"));
1088 // Push back long instructions and critical path
1090 DEBUG(dump("Mid-"));
1091 // Pack instructions to maximize resource utilization
1095 DEBUG(dump("Post-"));
1096 // Emit in scheduled order
1100 /// printSI - Print schedule info.
1102 void SimpleSched::printSI(std::ostream &O, NodeInfo *NI) const {
1104 using namespace std;
1105 SDNode *Node = NI->Node;
1108 << ", RS=" << NI->ResourceSet
1109 << ", Lat=" << NI->Latency
1110 << ", Slot=" << NI->Slot
1111 << ", ARITY=(" << Node->getNumOperands() << ","
1112 << Node->getNumValues() << ")"
1113 << " " << Node->getOperationName(&DAG);
1114 if (isFlagDefiner(Node)) O << "<#";
1115 if (isFlagUser(Node)) O << ">#";
1119 /// print - Print ordering to specified output stream.
1121 void SimpleSched::print(std::ostream &O) const {
1123 using namespace std;
1125 for (unsigned i = 0, N = Ordering.size(); i < N; i++) {
1126 NodeInfo *NI = Ordering[i];
1129 if (NI->isGroupLeader()) {
1130 NodeGroup *Group = NI->Group;
1131 for (NIIterator NII = Group->begin(), E = Group->end();
1142 /// dump - Print ordering to std::cerr.
1144 void SimpleSched::dump() const {
1147 //===----------------------------------------------------------------------===//
1150 //===----------------------------------------------------------------------===//
1151 /// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
1152 /// target node in the graph.
1153 void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &SD) {
1154 if (ViewDAGs) SD.viewGraph();
1155 BB = SimpleSched(SD, BB).Run();