ecdd51588c9c774ca42c3dbea79bf3c1482dee09
[oota-llvm.git] / lib / CodeGen / SelectionDAG / ScheduleDAGSimple.cpp
1 //===-- ScheduleDAGSimple.cpp - Implement a trivial DAG scheduler ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by James M. Laskey and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #define DEBUG_TYPE "sched"
17 #include "llvm/CodeGen/MachineFunction.h"
18 #include "llvm/CodeGen/ScheduleDAG.h"
19 #include "llvm/CodeGen/SchedulerRegistry.h"
20 #include "llvm/CodeGen/SelectionDAG.h"
21 #include "llvm/CodeGen/SSARegMap.h"
22 #include "llvm/Target/TargetData.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/Target/TargetInstrInfo.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/Visibility.h"
27 #include <algorithm>
28 #include <iostream>
29 using namespace llvm;
30
31
32 namespace {
33
34 static RegisterScheduler
35   bfsDAGScheduler("none", "  No scheduling: breadth first sequencing",
36                   createBFS_DAGScheduler);
37 static RegisterScheduler
38   simpleDAGScheduler("simple",
39                      "  Simple two pass scheduling: minimize critical path "
40                      "and maximize processor utilization",
41                       createSimpleDAGScheduler);
42 static RegisterScheduler
43   noitinDAGScheduler("simple-noitin",
44                      "  Simple two pass scheduling: Same as simple "
45                      "except using generic latency",
46                      createNoItinsDAGScheduler);
47                      
48 class NodeInfo;
49 typedef NodeInfo *NodeInfoPtr;
50 typedef std::vector<NodeInfoPtr>           NIVector;
51 typedef std::vector<NodeInfoPtr>::iterator NIIterator;
52
53 //===--------------------------------------------------------------------===//
54 ///
55 /// Node group -  This struct is used to manage flagged node groups.
56 ///
57 class NodeGroup {
58 public:
59   NodeGroup     *Next;
60 private:
61   NIVector      Members;                // Group member nodes
62   NodeInfo      *Dominator;             // Node with highest latency
63   unsigned      Latency;                // Total latency of the group
64   int           Pending;                // Number of visits pending before
65                                         // adding to order  
66
67 public:
68   // Ctor.
69   NodeGroup() : Next(NULL), Dominator(NULL), Pending(0) {}
70
71   // Accessors
72   inline void setDominator(NodeInfo *D) { Dominator = D; }
73   inline NodeInfo *getTop() { return Members.front(); }
74   inline NodeInfo *getBottom() { return Members.back(); }
75   inline NodeInfo *getDominator() { return Dominator; }
76   inline void setLatency(unsigned L) { Latency = L; }
77   inline unsigned getLatency() { return Latency; }
78   inline int getPending() const { return Pending; }
79   inline void setPending(int P)  { Pending = P; }
80   inline int addPending(int I)  { return Pending += I; }
81
82   // Pass thru
83   inline bool group_empty() { return Members.empty(); }
84   inline NIIterator group_begin() { return Members.begin(); }
85   inline NIIterator group_end() { return Members.end(); }
86   inline void group_push_back(const NodeInfoPtr &NI) {
87     Members.push_back(NI);
88   }
89   inline NIIterator group_insert(NIIterator Pos, const NodeInfoPtr &NI) {
90     return Members.insert(Pos, NI);
91   }
92   inline void group_insert(NIIterator Pos, NIIterator First,
93                            NIIterator Last) {
94     Members.insert(Pos, First, Last);
95   }
96
97   static void Add(NodeInfo *D, NodeInfo *U);
98 };
99
100 //===--------------------------------------------------------------------===//
101 ///
102 /// NodeInfo - This struct tracks information used to schedule the a node.
103 ///
104 class NodeInfo {
105 private:
106   int           Pending;                // Number of visits pending before
107                                         // adding to order
108 public:
109   SDNode        *Node;                  // DAG node
110   InstrStage    *StageBegin;            // First stage in itinerary
111   InstrStage    *StageEnd;              // Last+1 stage in itinerary
112   unsigned      Latency;                // Total cycles to complete instr
113   bool          IsCall : 1;             // Is function call
114   bool          IsLoad : 1;             // Is memory load
115   bool          IsStore : 1;            // Is memory store
116   unsigned      Slot;                   // Node's time slot
117   NodeGroup     *Group;                 // Grouping information
118 #ifndef NDEBUG
119   unsigned      Preorder;               // Index before scheduling
120 #endif
121
122   // Ctor.
123   NodeInfo(SDNode *N = NULL)
124     : Pending(0)
125     , Node(N)
126     , StageBegin(NULL)
127     , StageEnd(NULL)
128     , Latency(0)
129     , IsCall(false)
130     , Slot(0)
131     , Group(NULL)
132 #ifndef NDEBUG
133     , Preorder(0)
134 #endif
135   {}
136
137   // Accessors
138   inline bool isInGroup() const {
139     assert(!Group || !Group->group_empty() && "Group with no members");
140     return Group != NULL;
141   }
142   inline bool isGroupDominator() const {
143     return isInGroup() && Group->getDominator() == this;
144   }
145   inline int getPending() const {
146     return Group ? Group->getPending() : Pending;
147   }
148   inline void setPending(int P) {
149     if (Group) Group->setPending(P);
150     else       Pending = P;
151   }
152   inline int addPending(int I) {
153     if (Group) return Group->addPending(I);
154     else       return Pending += I;
155   }
156 };
157
158 //===--------------------------------------------------------------------===//
159 ///
160 /// NodeGroupIterator - Iterates over all the nodes indicated by the node
161 /// info. If the node is in a group then iterate over the members of the
162 /// group, otherwise just the node info.
163 ///
164 class NodeGroupIterator {
165 private:
166   NodeInfo   *NI;                       // Node info
167   NIIterator NGI;                       // Node group iterator
168   NIIterator NGE;                       // Node group iterator end
169
170 public:
171   // Ctor.
172   NodeGroupIterator(NodeInfo *N) : NI(N) {
173     // If the node is in a group then set up the group iterator.  Otherwise
174     // the group iterators will trip first time out.
175     if (N->isInGroup()) {
176       // get Group
177       NodeGroup *Group = NI->Group;
178       NGI = Group->group_begin();
179       NGE = Group->group_end();
180       // Prevent this node from being used (will be in members list
181       NI = NULL;
182     }
183   }
184
185   /// next - Return the next node info, otherwise NULL.
186   ///
187   NodeInfo *next() {
188     // If members list
189     if (NGI != NGE) return *NGI++;
190     // Use node as the result (may be NULL)
191     NodeInfo *Result = NI;
192     // Only use once
193     NI = NULL;
194     // Return node or NULL
195     return Result;
196   }
197 };
198 //===--------------------------------------------------------------------===//
199
200
201 //===--------------------------------------------------------------------===//
202 ///
203 /// NodeGroupOpIterator - Iterates over all the operands of a node.  If the
204 /// node is a member of a group, this iterates over all the operands of all
205 /// the members of the group.
206 ///
207 class NodeGroupOpIterator {
208 private:
209   NodeInfo            *NI;              // Node containing operands
210   NodeGroupIterator   GI;               // Node group iterator
211   SDNode::op_iterator OI;               // Operand iterator
212   SDNode::op_iterator OE;               // Operand iterator end
213
214   /// CheckNode - Test if node has more operands.  If not get the next node
215   /// skipping over nodes that have no operands.
216   void CheckNode() {
217     // Only if operands are exhausted first
218     while (OI == OE) {
219       // Get next node info
220       NodeInfo *NI = GI.next();
221       // Exit if nodes are exhausted
222       if (!NI) return;
223       // Get node itself
224       SDNode *Node = NI->Node;
225       // Set up the operand iterators
226       OI = Node->op_begin();
227       OE = Node->op_end();
228     }
229   }
230
231 public:
232   // Ctor.
233   NodeGroupOpIterator(NodeInfo *N)
234     : NI(N), GI(N), OI(SDNode::op_iterator()), OE(SDNode::op_iterator()) {}
235
236   /// isEnd - Returns true when not more operands are available.
237   ///
238   inline bool isEnd() { CheckNode(); return OI == OE; }
239
240   /// next - Returns the next available operand.
241   ///
242   inline SDOperand next() {
243     assert(OI != OE &&
244            "Not checking for end of NodeGroupOpIterator correctly");
245     return *OI++;
246   }
247 };
248
249
250 //===----------------------------------------------------------------------===//
251 ///
252 /// BitsIterator - Provides iteration through individual bits in a bit vector.
253 ///
254 template<class T>
255 class BitsIterator {
256 private:
257   T Bits;                               // Bits left to iterate through
258
259 public:
260   /// Ctor.
261   BitsIterator(T Initial) : Bits(Initial) {}
262   
263   /// Next - Returns the next bit set or zero if exhausted.
264   inline T Next() {
265     // Get the rightmost bit set
266     T Result = Bits & -Bits;
267     // Remove from rest
268     Bits &= ~Result;
269     // Return single bit or zero
270     return Result;
271   }
272 };
273   
274 //===----------------------------------------------------------------------===//
275
276
277 //===----------------------------------------------------------------------===//
278 ///
279 /// ResourceTally - Manages the use of resources over time intervals.  Each
280 /// item (slot) in the tally vector represents the resources used at a given
281 /// moment.  A bit set to 1 indicates that a resource is in use, otherwise
282 /// available.  An assumption is made that the tally is large enough to schedule 
283 /// all current instructions (asserts otherwise.)
284 ///
285 template<class T>
286 class ResourceTally {
287 private:
288   std::vector<T> Tally;                 // Resources used per slot
289   typedef typename std::vector<T>::iterator Iter;
290                                         // Tally iterator 
291   
292   /// SlotsAvailable - Returns true if all units are available.
293         ///
294   bool SlotsAvailable(Iter Begin, unsigned N, unsigned ResourceSet,
295                                               unsigned &Resource) {
296     assert(N && "Must check availability with N != 0");
297     // Determine end of interval
298     Iter End = Begin + N;
299     assert(End <= Tally.end() && "Tally is not large enough for schedule");
300     
301     // Iterate thru each resource
302     BitsIterator<T> Resources(ResourceSet & ~*Begin);
303     while (unsigned Res = Resources.Next()) {
304       // Check if resource is available for next N slots
305       Iter Interval = End;
306       do {
307         Interval--;
308         if (*Interval & Res) break;
309       } while (Interval != Begin);
310       
311       // If available for N
312       if (Interval == Begin) {
313         // Success
314         Resource = Res;
315         return true;
316       }
317     }
318     
319     // No luck
320     Resource = 0;
321     return false;
322   }
323         
324         /// RetrySlot - Finds a good candidate slot to retry search.
325   Iter RetrySlot(Iter Begin, unsigned N, unsigned ResourceSet) {
326     assert(N && "Must check availability with N != 0");
327     // Determine end of interval
328     Iter End = Begin + N;
329     assert(End <= Tally.end() && "Tally is not large enough for schedule");
330                 
331                 while (Begin != End--) {
332                         // Clear units in use
333                         ResourceSet &= ~*End;
334                         // If no units left then we should go no further 
335                         if (!ResourceSet) return End + 1;
336                 }
337                 // Made it all the way through
338                 return Begin;
339         }
340   
341   /// FindAndReserveStages - Return true if the stages can be completed. If
342   /// so mark as busy.
343   bool FindAndReserveStages(Iter Begin,
344                             InstrStage *Stage, InstrStage *StageEnd) {
345     // If at last stage then we're done
346     if (Stage == StageEnd) return true;
347     // Get number of cycles for current stage
348     unsigned N = Stage->Cycles;
349     // Check to see if N slots are available, if not fail
350     unsigned Resource;
351     if (!SlotsAvailable(Begin, N, Stage->Units, Resource)) return false;
352     // Check to see if remaining stages are available, if not fail
353     if (!FindAndReserveStages(Begin + N, Stage + 1, StageEnd)) return false;
354     // Reserve resource
355     Reserve(Begin, N, Resource);
356     // Success
357     return true;
358   }
359
360   /// Reserve - Mark busy (set) the specified N slots.
361   void Reserve(Iter Begin, unsigned N, unsigned Resource) {
362     // Determine end of interval
363     Iter End = Begin + N;
364     assert(End <= Tally.end() && "Tally is not large enough for schedule");
365  
366     // Set resource bit in each slot
367     for (; Begin < End; Begin++)
368       *Begin |= Resource;
369   }
370
371   /// FindSlots - Starting from Begin, locate consecutive slots where all stages
372   /// can be completed.  Returns the address of first slot.
373   Iter FindSlots(Iter Begin, InstrStage *StageBegin, InstrStage *StageEnd) {
374     // Track position      
375     Iter Cursor = Begin;
376     
377     // Try all possible slots forward
378     while (true) {
379       // Try at cursor, if successful return position.
380       if (FindAndReserveStages(Cursor, StageBegin, StageEnd)) return Cursor;
381       // Locate a better position
382                         Cursor = RetrySlot(Cursor + 1, StageBegin->Cycles, StageBegin->Units);
383     }
384   }
385   
386 public:
387   /// Initialize - Resize and zero the tally to the specified number of time
388   /// slots.
389   inline void Initialize(unsigned N) {
390     Tally.assign(N, 0);   // Initialize tally to all zeros.
391   }
392
393   // FindAndReserve - Locate an ideal slot for the specified stages and mark
394   // as busy.
395   unsigned FindAndReserve(unsigned Slot, InstrStage *StageBegin,
396                                          InstrStage *StageEnd) {
397                 // Where to begin 
398                 Iter Begin = Tally.begin() + Slot;
399                 // Find a free slot
400                 Iter Where = FindSlots(Begin, StageBegin, StageEnd);
401                 // Distance is slot number
402                 unsigned Final = Where - Tally.begin();
403     return Final;
404   }
405
406 };
407
408 //===----------------------------------------------------------------------===//
409 ///
410 /// ScheduleDAGSimple - Simple two pass scheduler.
411 ///
412 class VISIBILITY_HIDDEN ScheduleDAGSimple : public ScheduleDAG {
413 private:
414   bool NoSched;                         // Just do a BFS schedule, nothing fancy
415   bool NoItins;                         // Don't use itineraries?
416   ResourceTally<unsigned> Tally;        // Resource usage tally
417   unsigned NSlots;                      // Total latency
418   static const unsigned NotFound = ~0U; // Search marker
419
420   unsigned NodeCount;                   // Number of nodes in DAG
421   std::map<SDNode *, NodeInfo *> Map;   // Map nodes to info
422   bool HasGroups;                       // True if there are any groups
423   NodeInfo *Info;                       // Info for nodes being scheduled
424   NIVector Ordering;                    // Emit ordering of nodes
425   NodeGroup *HeadNG, *TailNG;           // Keep track of allocated NodeGroups
426   
427 public:
428
429   // Ctor.
430   ScheduleDAGSimple(bool noSched, bool noItins, SelectionDAG &dag,
431                     MachineBasicBlock *bb, const TargetMachine &tm)
432     : ScheduleDAG(dag, bb, tm), NoSched(noSched), NoItins(noItins), NSlots(0),
433     NodeCount(0), HasGroups(false), Info(NULL), HeadNG(NULL), TailNG(NULL) {
434     assert(&TII && "Target doesn't provide instr info?");
435     assert(&MRI && "Target doesn't provide register info?");
436   }
437
438   virtual ~ScheduleDAGSimple() {
439     if (Info)
440       delete[] Info;
441     
442     NodeGroup *NG = HeadNG;
443     while (NG) {
444       NodeGroup *NextSU = NG->Next;
445       delete NG;
446       NG = NextSU;
447     }
448   }
449
450   void Schedule();
451
452   /// getNI - Returns the node info for the specified node.
453   ///
454   NodeInfo *getNI(SDNode *Node) { return Map[Node]; }
455   
456 private:
457   static bool isDefiner(NodeInfo *A, NodeInfo *B);
458   void IncludeNode(NodeInfo *NI);
459   void VisitAll();
460   void GatherSchedulingInfo();
461   void FakeGroupDominators(); 
462   bool isStrongDependency(NodeInfo *A, NodeInfo *B);
463   bool isWeakDependency(NodeInfo *A, NodeInfo *B);
464   void ScheduleBackward();
465   void ScheduleForward();
466   
467   void AddToGroup(NodeInfo *D, NodeInfo *U);
468   /// PrepareNodeInfo - Set up the basic minimum node info for scheduling.
469   /// 
470   void PrepareNodeInfo();
471   
472   /// IdentifyGroups - Put flagged nodes into groups.
473   ///
474   void IdentifyGroups();
475   
476   /// print - Print ordering to specified output stream.
477   ///
478   void print(std::ostream &O) const;
479   
480   void dump(const char *tag) const;
481   
482   virtual void dump() const;
483   
484   /// EmitAll - Emit all nodes in schedule sorted order.
485   ///
486   void EmitAll();
487
488   /// printNI - Print node info.
489   ///
490   void printNI(std::ostream &O, NodeInfo *NI) const;
491   
492   /// printChanges - Hilight changes in order caused by scheduling.
493   ///
494   void printChanges(unsigned Index) const;
495 };
496
497 //===----------------------------------------------------------------------===//
498 /// Special case itineraries.
499 ///
500 enum {
501   CallLatency = 40,          // To push calls back in time
502
503   RSInteger   = 0xC0000000,  // Two integer units
504   RSFloat     = 0x30000000,  // Two float units
505   RSLoadStore = 0x0C000000,  // Two load store units
506   RSBranch    = 0x02000000   // One branch unit
507 };
508 static InstrStage CallStage  = { CallLatency, RSBranch };
509 static InstrStage LoadStage  = { 5, RSLoadStore };
510 static InstrStage StoreStage = { 2, RSLoadStore };
511 static InstrStage IntStage   = { 2, RSInteger };
512 static InstrStage FloatStage = { 3, RSFloat };
513 //===----------------------------------------------------------------------===//
514
515 } // namespace
516
517 //===----------------------------------------------------------------------===//
518
519 /// PrepareNodeInfo - Set up the basic minimum node info for scheduling.
520 /// 
521 void ScheduleDAGSimple::PrepareNodeInfo() {
522   // Allocate node information
523   Info = new NodeInfo[NodeCount];
524   
525   unsigned i = 0;
526   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
527        E = DAG.allnodes_end(); I != E; ++I, ++i) {
528     // Fast reference to node schedule info
529     NodeInfo* NI = &Info[i];
530     // Set up map
531     Map[I] = NI;
532     // Set node
533     NI->Node = I;
534     // Set pending visit count
535     NI->setPending(I->use_size());
536   }
537 }
538
539 /// IdentifyGroups - Put flagged nodes into groups.
540 ///
541 void ScheduleDAGSimple::IdentifyGroups() {
542   for (unsigned i = 0, N = NodeCount; i < N; i++) {
543     NodeInfo* NI = &Info[i];
544     SDNode *Node = NI->Node;
545     
546     // For each operand (in reverse to only look at flags)
547     for (unsigned N = Node->getNumOperands(); 0 < N--;) {
548       // Get operand
549       SDOperand Op = Node->getOperand(N);
550       // No more flags to walk
551       if (Op.getValueType() != MVT::Flag) break;
552       // Add to node group
553       AddToGroup(getNI(Op.Val), NI);
554       // Let everyone else know
555       HasGroups = true;
556     }
557   }
558 }
559
560 /// CountInternalUses - Returns the number of edges between the two nodes.
561 ///
562 static unsigned CountInternalUses(NodeInfo *D, NodeInfo *U) {
563   unsigned N = 0;
564   for (unsigned M = U->Node->getNumOperands(); 0 < M--;) {
565     SDOperand Op = U->Node->getOperand(M);
566     if (Op.Val == D->Node) N++;
567   }
568   
569   return N;
570 }
571
572 //===----------------------------------------------------------------------===//
573 /// Add - Adds a definer and user pair to a node group.
574 ///
575 void ScheduleDAGSimple::AddToGroup(NodeInfo *D, NodeInfo *U) {
576   // Get current groups
577   NodeGroup *DGroup = D->Group;
578   NodeGroup *UGroup = U->Group;
579   // If both are members of groups
580   if (DGroup && UGroup) {
581     // There may have been another edge connecting 
582     if (DGroup == UGroup) return;
583     // Add the pending users count
584     DGroup->addPending(UGroup->getPending());
585     // For each member of the users group
586     NodeGroupIterator UNGI(U);
587     while (NodeInfo *UNI = UNGI.next() ) {
588       // Change the group
589       UNI->Group = DGroup;
590       // For each member of the definers group
591       NodeGroupIterator DNGI(D);
592       while (NodeInfo *DNI = DNGI.next() ) {
593         // Remove internal edges
594         DGroup->addPending(-CountInternalUses(DNI, UNI));
595       }
596     }
597     // Merge the two lists
598     DGroup->group_insert(DGroup->group_end(),
599                          UGroup->group_begin(), UGroup->group_end());
600   } else if (DGroup) {
601     // Make user member of definers group
602     U->Group = DGroup;
603     // Add users uses to definers group pending
604     DGroup->addPending(U->Node->use_size());
605     // For each member of the definers group
606     NodeGroupIterator DNGI(D);
607     while (NodeInfo *DNI = DNGI.next() ) {
608       // Remove internal edges
609       DGroup->addPending(-CountInternalUses(DNI, U));
610     }
611     DGroup->group_push_back(U);
612   } else if (UGroup) {
613     // Make definer member of users group
614     D->Group = UGroup;
615     // Add definers uses to users group pending
616     UGroup->addPending(D->Node->use_size());
617     // For each member of the users group
618     NodeGroupIterator UNGI(U);
619     while (NodeInfo *UNI = UNGI.next() ) {
620       // Remove internal edges
621       UGroup->addPending(-CountInternalUses(D, UNI));
622     }
623     UGroup->group_insert(UGroup->group_begin(), D);
624   } else {
625     D->Group = U->Group = DGroup = new NodeGroup();
626     DGroup->addPending(D->Node->use_size() + U->Node->use_size() -
627                        CountInternalUses(D, U));
628     DGroup->group_push_back(D);
629     DGroup->group_push_back(U);
630     
631     if (HeadNG == NULL)
632       HeadNG = DGroup;
633     if (TailNG != NULL)
634       TailNG->Next = DGroup;
635     TailNG = DGroup;
636   }
637 }
638
639
640 /// print - Print ordering to specified output stream.
641 ///
642 void ScheduleDAGSimple::print(std::ostream &O) const {
643 #ifndef NDEBUG
644   O << "Ordering\n";
645   for (unsigned i = 0, N = Ordering.size(); i < N; i++) {
646     NodeInfo *NI = Ordering[i];
647     printNI(O, NI);
648     O << "\n";
649     if (NI->isGroupDominator()) {
650       NodeGroup *Group = NI->Group;
651       for (NIIterator NII = Group->group_begin(), E = Group->group_end();
652            NII != E; NII++) {
653         O << "    ";
654         printNI(O, *NII);
655         O << "\n";
656       }
657     }
658   }
659 #endif
660 }
661
662 void ScheduleDAGSimple::dump(const char *tag) const {
663   std::cerr << tag; dump();
664 }
665
666 void ScheduleDAGSimple::dump() const {
667   print(std::cerr);
668 }
669
670
671 /// EmitAll - Emit all nodes in schedule sorted order.
672 ///
673 void ScheduleDAGSimple::EmitAll() {
674   // If this is the first basic block in the function, and if it has live ins
675   // that need to be copied into vregs, emit the copies into the top of the
676   // block before emitting the code for the block.
677   MachineFunction &MF = DAG.getMachineFunction();
678   if (&MF.front() == BB && MF.livein_begin() != MF.livein_end()) {
679     for (MachineFunction::livein_iterator LI = MF.livein_begin(),
680          E = MF.livein_end(); LI != E; ++LI)
681       if (LI->second)
682         MRI->copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
683                           LI->first, RegMap->getRegClass(LI->second));
684   }
685   
686   std::map<SDNode*, unsigned> VRBaseMap;
687   
688   // For each node in the ordering
689   for (unsigned i = 0, N = Ordering.size(); i < N; i++) {
690     // Get the scheduling info
691     NodeInfo *NI = Ordering[i];
692     if (NI->isInGroup()) {
693       NodeGroupIterator NGI(Ordering[i]);
694       while (NodeInfo *NI = NGI.next()) EmitNode(NI->Node, VRBaseMap);
695     } else {
696       EmitNode(NI->Node, VRBaseMap);
697     }
698   }
699 }
700
701 /// isFlagDefiner - Returns true if the node defines a flag result.
702 static bool isFlagDefiner(SDNode *A) {
703   unsigned N = A->getNumValues();
704   return N && A->getValueType(N - 1) == MVT::Flag;
705 }
706
707 /// isFlagUser - Returns true if the node uses a flag result.
708 ///
709 static bool isFlagUser(SDNode *A) {
710   unsigned N = A->getNumOperands();
711   return N && A->getOperand(N - 1).getValueType() == MVT::Flag;
712 }
713
714 /// printNI - Print node info.
715 ///
716 void ScheduleDAGSimple::printNI(std::ostream &O, NodeInfo *NI) const {
717 #ifndef NDEBUG
718   SDNode *Node = NI->Node;
719   O << " "
720     << std::hex << Node << std::dec
721     << ", Lat=" << NI->Latency
722     << ", Slot=" << NI->Slot
723     << ", ARITY=(" << Node->getNumOperands() << ","
724     << Node->getNumValues() << ")"
725     << " " << Node->getOperationName(&DAG);
726   if (isFlagDefiner(Node)) O << "<#";
727   if (isFlagUser(Node)) O << ">#";
728 #endif
729 }
730
731 /// printChanges - Hilight changes in order caused by scheduling.
732 ///
733 void ScheduleDAGSimple::printChanges(unsigned Index) const {
734 #ifndef NDEBUG
735   // Get the ordered node count
736   unsigned N = Ordering.size();
737   // Determine if any changes
738   unsigned i = 0;
739   for (; i < N; i++) {
740     NodeInfo *NI = Ordering[i];
741     if (NI->Preorder != i) break;
742   }
743   
744   if (i < N) {
745     std::cerr << Index << ". New Ordering\n";
746     
747     for (i = 0; i < N; i++) {
748       NodeInfo *NI = Ordering[i];
749       std::cerr << "  " << NI->Preorder << ". ";
750       printNI(std::cerr, NI);
751       std::cerr << "\n";
752       if (NI->isGroupDominator()) {
753         NodeGroup *Group = NI->Group;
754         for (NIIterator NII = Group->group_begin(), E = Group->group_end();
755              NII != E; NII++) {
756           std::cerr << "          ";
757           printNI(std::cerr, *NII);
758           std::cerr << "\n";
759         }
760       }
761     }
762   } else {
763     std::cerr << Index << ". No Changes\n";
764   }
765 #endif
766 }
767
768 //===----------------------------------------------------------------------===//
769 /// isDefiner - Return true if node A is a definer for B.
770 ///
771 bool ScheduleDAGSimple::isDefiner(NodeInfo *A, NodeInfo *B) {
772   // While there are A nodes
773   NodeGroupIterator NII(A);
774   while (NodeInfo *NI = NII.next()) {
775     // Extract node
776     SDNode *Node = NI->Node;
777     // While there operands in nodes of B
778     NodeGroupOpIterator NGOI(B);
779     while (!NGOI.isEnd()) {
780       SDOperand Op = NGOI.next();
781       // If node from A defines a node in B
782       if (Node == Op.Val) return true;
783     }
784   }
785   return false;
786 }
787
788 /// IncludeNode - Add node to NodeInfo vector.
789 ///
790 void ScheduleDAGSimple::IncludeNode(NodeInfo *NI) {
791   // Get node
792   SDNode *Node = NI->Node;
793   // Ignore entry node
794   if (Node->getOpcode() == ISD::EntryToken) return;
795   // Check current count for node
796   int Count = NI->getPending();
797   // If the node is already in list
798   if (Count < 0) return;
799   // Decrement count to indicate a visit
800   Count--;
801   // If count has gone to zero then add node to list
802   if (!Count) {
803     // Add node
804     if (NI->isInGroup()) {
805       Ordering.push_back(NI->Group->getDominator());
806     } else {
807       Ordering.push_back(NI);
808     }
809     // indicate node has been added
810     Count--;
811   }
812   // Mark as visited with new count 
813   NI->setPending(Count);
814 }
815
816 /// GatherSchedulingInfo - Get latency and resource information about each node.
817 ///
818 void ScheduleDAGSimple::GatherSchedulingInfo() {
819   // Get instruction itineraries for the target
820   const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
821   
822   // For each node
823   for (unsigned i = 0, N = NodeCount; i < N; i++) {
824     // Get node info
825     NodeInfo* NI = &Info[i];
826     SDNode *Node = NI->Node;
827     
828     // If there are itineraries and it is a machine instruction
829     if (InstrItins.isEmpty() || NoItins) {
830       // If machine opcode
831       if (Node->isTargetOpcode()) {
832         // Get return type to guess which processing unit 
833         MVT::ValueType VT = Node->getValueType(0);
834         // Get machine opcode
835         MachineOpCode TOpc = Node->getTargetOpcode();
836         NI->IsCall = TII->isCall(TOpc);
837         NI->IsLoad = TII->isLoad(TOpc);
838         NI->IsStore = TII->isStore(TOpc);
839
840         if (TII->isLoad(TOpc))             NI->StageBegin = &LoadStage;
841         else if (TII->isStore(TOpc))       NI->StageBegin = &StoreStage;
842         else if (MVT::isInteger(VT))       NI->StageBegin = &IntStage;
843         else if (MVT::isFloatingPoint(VT)) NI->StageBegin = &FloatStage;
844         if (NI->StageBegin) NI->StageEnd = NI->StageBegin + 1;
845       }
846     } else if (Node->isTargetOpcode()) {
847       // get machine opcode
848       MachineOpCode TOpc = Node->getTargetOpcode();
849       // Check to see if it is a call
850       NI->IsCall = TII->isCall(TOpc);
851       // Get itinerary stages for instruction
852       unsigned II = TII->getSchedClass(TOpc);
853       NI->StageBegin = InstrItins.begin(II);
854       NI->StageEnd = InstrItins.end(II);
855     }
856     
857     // One slot for the instruction itself
858     NI->Latency = 1;
859     
860     // Add long latency for a call to push it back in time
861     if (NI->IsCall) NI->Latency += CallLatency;
862     
863     // Sum up all the latencies
864     for (InstrStage *Stage = NI->StageBegin, *E = NI->StageEnd;
865         Stage != E; Stage++) {
866       NI->Latency += Stage->Cycles;
867     }
868     
869     // Sum up all the latencies for max tally size
870     NSlots += NI->Latency;
871   }
872   
873   // Unify metrics if in a group
874   if (HasGroups) {
875     for (unsigned i = 0, N = NodeCount; i < N; i++) {
876       NodeInfo* NI = &Info[i];
877       
878       if (NI->isInGroup()) {
879         NodeGroup *Group = NI->Group;
880         
881         if (!Group->getDominator()) {
882           NIIterator NGI = Group->group_begin(), NGE = Group->group_end();
883           NodeInfo *Dominator = *NGI;
884           unsigned Latency = 0;
885           
886           for (NGI++; NGI != NGE; NGI++) {
887             NodeInfo* NGNI = *NGI;
888             Latency += NGNI->Latency;
889             if (Dominator->Latency < NGNI->Latency) Dominator = NGNI;
890           }
891           
892           Dominator->Latency = Latency;
893           Group->setDominator(Dominator);
894         }
895       }
896     }
897   }
898 }
899
900 /// VisitAll - Visit each node breadth-wise to produce an initial ordering.
901 /// Note that the ordering in the Nodes vector is reversed.
902 void ScheduleDAGSimple::VisitAll() {
903   // Add first element to list
904   NodeInfo *NI = getNI(DAG.getRoot().Val);
905   if (NI->isInGroup()) {
906     Ordering.push_back(NI->Group->getDominator());
907   } else {
908     Ordering.push_back(NI);
909   }
910
911   // Iterate through all nodes that have been added
912   for (unsigned i = 0; i < Ordering.size(); i++) { // note: size() varies
913     // Visit all operands
914     NodeGroupOpIterator NGI(Ordering[i]);
915     while (!NGI.isEnd()) {
916       // Get next operand
917       SDOperand Op = NGI.next();
918       // Get node
919       SDNode *Node = Op.Val;
920       // Ignore passive nodes
921       if (isPassiveNode(Node)) continue;
922       // Check out node
923       IncludeNode(getNI(Node));
924     }
925   }
926
927   // Add entry node last (IncludeNode filters entry nodes)
928   if (DAG.getEntryNode().Val != DAG.getRoot().Val)
929     Ordering.push_back(getNI(DAG.getEntryNode().Val));
930     
931   // Reverse the order
932   std::reverse(Ordering.begin(), Ordering.end());
933 }
934
935 /// FakeGroupDominators - Set dominators for non-scheduling.
936 /// 
937 void ScheduleDAGSimple::FakeGroupDominators() {
938   for (unsigned i = 0, N = NodeCount; i < N; i++) {
939     NodeInfo* NI = &Info[i];
940     
941     if (NI->isInGroup()) {
942       NodeGroup *Group = NI->Group;
943       
944       if (!Group->getDominator()) {
945         Group->setDominator(NI);
946       }
947     }
948   }
949 }
950
951 /// isStrongDependency - Return true if node A has results used by node B. 
952 /// I.E., B must wait for latency of A.
953 bool ScheduleDAGSimple::isStrongDependency(NodeInfo *A, NodeInfo *B) {
954   // If A defines for B then it's a strong dependency or
955   // if a load follows a store (may be dependent but why take a chance.)
956   return isDefiner(A, B) || (A->IsStore && B->IsLoad);
957 }
958
959 /// isWeakDependency Return true if node A produces a result that will
960 /// conflict with operands of B.  It is assumed that we have called
961 /// isStrongDependency prior.
962 bool ScheduleDAGSimple::isWeakDependency(NodeInfo *A, NodeInfo *B) {
963   // TODO check for conflicting real registers and aliases
964 #if 0 // FIXME - Since we are in SSA form and not checking register aliasing
965   return A->Node->getOpcode() == ISD::EntryToken || isStrongDependency(B, A);
966 #else
967   return A->Node->getOpcode() == ISD::EntryToken;
968 #endif
969 }
970
971 /// ScheduleBackward - Schedule instructions so that any long latency
972 /// instructions and the critical path get pushed back in time. Time is run in
973 /// reverse to allow code reuse of the Tally and eliminate the overhead of
974 /// biasing every slot indices against NSlots.
975 void ScheduleDAGSimple::ScheduleBackward() {
976   // Size and clear the resource tally
977   Tally.Initialize(NSlots);
978   // Get number of nodes to schedule
979   unsigned N = Ordering.size();
980   
981   // For each node being scheduled
982   for (unsigned i = N; 0 < i--;) {
983     NodeInfo *NI = Ordering[i];
984     // Track insertion
985     unsigned Slot = NotFound;
986     
987     // Compare against those previously scheduled nodes
988     unsigned j = i + 1;
989     for (; j < N; j++) {
990       // Get following instruction
991       NodeInfo *Other = Ordering[j];
992       
993       // Check dependency against previously inserted nodes
994       if (isStrongDependency(NI, Other)) {
995         Slot = Other->Slot + Other->Latency;
996         break;
997       } else if (isWeakDependency(NI, Other)) {
998         Slot = Other->Slot;
999         break;
1000       }
1001     }
1002     
1003     // If independent of others (or first entry)
1004     if (Slot == NotFound) Slot = 0;
1005     
1006 #if 0 // FIXME - measure later
1007     // Find a slot where the needed resources are available
1008     if (NI->StageBegin != NI->StageEnd)
1009       Slot = Tally.FindAndReserve(Slot, NI->StageBegin, NI->StageEnd);
1010 #endif
1011       
1012     // Set node slot
1013     NI->Slot = Slot;
1014     
1015     // Insert sort based on slot
1016     j = i + 1;
1017     for (; j < N; j++) {
1018       // Get following instruction
1019       NodeInfo *Other = Ordering[j];
1020       // Should we look further (remember slots are in reverse time)
1021       if (Slot >= Other->Slot) break;
1022       // Shuffle other into ordering
1023       Ordering[j - 1] = Other;
1024     }
1025     // Insert node in proper slot
1026     if (j != i + 1) Ordering[j - 1] = NI;
1027   }
1028 }
1029
1030 /// ScheduleForward - Schedule instructions to maximize packing.
1031 ///
1032 void ScheduleDAGSimple::ScheduleForward() {
1033   // Size and clear the resource tally
1034   Tally.Initialize(NSlots);
1035   // Get number of nodes to schedule
1036   unsigned N = Ordering.size();
1037   
1038   // For each node being scheduled
1039   for (unsigned i = 0; i < N; i++) {
1040     NodeInfo *NI = Ordering[i];
1041     // Track insertion
1042     unsigned Slot = NotFound;
1043     
1044     // Compare against those previously scheduled nodes
1045     unsigned j = i;
1046     for (; 0 < j--;) {
1047       // Get following instruction
1048       NodeInfo *Other = Ordering[j];
1049       
1050       // Check dependency against previously inserted nodes
1051       if (isStrongDependency(Other, NI)) {
1052         Slot = Other->Slot + Other->Latency;
1053         break;
1054       } else if (Other->IsCall || isWeakDependency(Other, NI)) {
1055         Slot = Other->Slot;
1056         break;
1057       }
1058     }
1059     
1060     // If independent of others (or first entry)
1061     if (Slot == NotFound) Slot = 0;
1062     
1063     // Find a slot where the needed resources are available
1064     if (NI->StageBegin != NI->StageEnd)
1065       Slot = Tally.FindAndReserve(Slot, NI->StageBegin, NI->StageEnd);
1066       
1067     // Set node slot
1068     NI->Slot = Slot;
1069     
1070     // Insert sort based on slot
1071     j = i;
1072     for (; 0 < j--;) {
1073       // Get prior instruction
1074       NodeInfo *Other = Ordering[j];
1075       // Should we look further
1076       if (Slot >= Other->Slot) break;
1077       // Shuffle other into ordering
1078       Ordering[j + 1] = Other;
1079     }
1080     // Insert node in proper slot
1081     if (j != i) Ordering[j + 1] = NI;
1082   }
1083 }
1084
1085 /// Schedule - Order nodes according to selected style.
1086 ///
1087 void ScheduleDAGSimple::Schedule() {
1088   // Number the nodes
1089   NodeCount = std::distance(DAG.allnodes_begin(), DAG.allnodes_end());
1090
1091   // Set up minimum info for scheduling
1092   PrepareNodeInfo();
1093   // Construct node groups for flagged nodes
1094   IdentifyGroups();
1095   
1096   // Test to see if scheduling should occur
1097   bool ShouldSchedule = NodeCount > 3 && !NoSched;
1098   // Don't waste time if is only entry and return
1099   if (ShouldSchedule) {
1100     // Get latency and resource requirements
1101     GatherSchedulingInfo();
1102   } else if (HasGroups) {
1103     // Make sure all the groups have dominators
1104     FakeGroupDominators();
1105   }
1106
1107   // Breadth first walk of DAG
1108   VisitAll();
1109
1110 #ifndef NDEBUG
1111   static unsigned Count = 0;
1112   Count++;
1113   for (unsigned i = 0, N = Ordering.size(); i < N; i++) {
1114     NodeInfo *NI = Ordering[i];
1115     NI->Preorder = i;
1116   }
1117 #endif  
1118   
1119   // Don't waste time if is only entry and return
1120   if (ShouldSchedule) {
1121     // Push back long instructions and critical path
1122     ScheduleBackward();
1123     
1124     // Pack instructions to maximize resource utilization
1125     ScheduleForward();
1126   }
1127   
1128   DEBUG(printChanges(Count));
1129   
1130   // Emit in scheduled order
1131   EmitAll();
1132 }
1133
1134
1135 /// createSimpleDAGScheduler - This creates a simple two pass instruction
1136 /// scheduler using instruction itinerary.
1137 llvm::ScheduleDAG* llvm::createSimpleDAGScheduler(SelectionDAGISel *IS,
1138                                                   SelectionDAG *DAG,
1139                                                   MachineBasicBlock *BB) {
1140   return new ScheduleDAGSimple(false, false, *DAG, BB, DAG->getTarget());
1141 }
1142
1143 /// createNoItinsDAGScheduler - This creates a simple two pass instruction
1144 /// scheduler without using instruction itinerary.
1145 llvm::ScheduleDAG* llvm::createNoItinsDAGScheduler(SelectionDAGISel *IS,
1146                                                    SelectionDAG *DAG,
1147                                                    MachineBasicBlock *BB) {
1148   return new ScheduleDAGSimple(false, true, *DAG, BB, DAG->getTarget());
1149 }
1150
1151 /// createBFS_DAGScheduler - This creates a simple breadth first instruction
1152 /// scheduler.
1153 llvm::ScheduleDAG* llvm::createBFS_DAGScheduler(SelectionDAGISel *IS,
1154                                                 SelectionDAG *DAG,
1155                                                 MachineBasicBlock *BB) {
1156   return new ScheduleDAGSimple(true, false, *DAG, BB,  DAG->getTarget());
1157 }