7f29b8c70b107d192a19b99a64ecc07ca1a20d86
[oota-llvm.git] / lib / Target / SparcV9 / InstrSched / InstrScheduling.cpp
1 //===- InstrScheduling.cpp - Generic Instruction Scheduling support -------===//
2 //
3 // This file implements the llvm/CodeGen/InstrScheduling.h interface, along with
4 // generic support routines for instruction scheduling.
5 //
6 //===----------------------------------------------------------------------===//
7
8 #include "llvm/CodeGen/InstrScheduling.h"
9 #include "llvm/CodeGen/MachineInstr.h"
10 #include "llvm/CodeGen/MachineCodeForInstruction.h"
11 #include "llvm/CodeGen/MachineCodeForMethod.h"
12 #include "llvm/Analysis/LiveVar/MethodLiveVarInfo.h" // FIXME: Remove when AnalysisUsage sets can be symbolic!
13 #include "llvm/Target/TargetMachine.h"
14 #include "llvm/BasicBlock.h"
15 #include "llvm/Instruction.h"
16 #include "SchedPriorities.h"
17 #include <ext/hash_set>
18 #include <algorithm>
19 #include <iterator>
20 #include <iostream>
21 using std::cerr;
22 using std::vector;
23
24 //************************* External Data Types *****************************/
25
26 cl::Enum<enum SchedDebugLevel_t> SchedDebugLevel("dsched", cl::NoFlags,
27   "enable instruction scheduling debugging information",
28   clEnumValN(Sched_NoDebugInfo,      "n", "disable debug output"),
29   clEnumValN(Sched_Disable,        "off", "disable instruction scheduling"),
30   clEnumValN(Sched_PrintMachineCode, "y", "print machine code after scheduling"),
31   clEnumValN(Sched_PrintSchedTrace,  "t", "print trace of scheduling actions"),
32   clEnumValN(Sched_PrintSchedGraphs, "g", "print scheduling graphs"), 0);
33
34
35 //************************* Internal Data Types *****************************/
36
37 class InstrSchedule;
38 class SchedulingManager;
39
40
41 //----------------------------------------------------------------------
42 // class InstrGroup:
43 // 
44 // Represents a group of instructions scheduled to be issued
45 // in a single cycle.
46 //----------------------------------------------------------------------
47
48 class InstrGroup: public NonCopyable {
49 public:
50   inline const SchedGraphNode* operator[](unsigned int slotNum) const {
51     assert(slotNum  < group.size());
52     return group[slotNum];
53   }
54   
55 private:
56   friend class InstrSchedule;
57   
58   inline void   addInstr(const SchedGraphNode* node, unsigned int slotNum) {
59     assert(slotNum < group.size());
60     group[slotNum] = node;
61   }
62   
63   /*ctor*/      InstrGroup(unsigned int nslots)
64     : group(nslots, NULL) {}
65   
66   /*ctor*/      InstrGroup();           // disable: DO NOT IMPLEMENT
67   
68 private:
69   vector<const SchedGraphNode*> group;
70 };
71
72
73 //----------------------------------------------------------------------
74 // class ScheduleIterator:
75 // 
76 // Iterates over the machine instructions in the for a single basic block.
77 // The schedule is represented by an InstrSchedule object.
78 //----------------------------------------------------------------------
79
80 template<class _NodeType>
81 class ScheduleIterator: public std::forward_iterator<_NodeType, ptrdiff_t> {
82 private:
83   unsigned cycleNum;
84   unsigned slotNum;
85   const InstrSchedule& S;
86 public:
87   typedef ScheduleIterator<_NodeType> _Self;
88   
89   /*ctor*/ inline ScheduleIterator(const InstrSchedule& _schedule,
90                                    unsigned _cycleNum,
91                                    unsigned _slotNum)
92     : cycleNum(_cycleNum), slotNum(_slotNum), S(_schedule) {
93     skipToNextInstr(); 
94   }
95   
96   /*ctor*/ inline ScheduleIterator(const _Self& x)
97     : cycleNum(x.cycleNum), slotNum(x.slotNum), S(x.S) {}
98   
99   inline bool operator==(const _Self& x) const {
100     return (slotNum == x.slotNum && cycleNum== x.cycleNum && &S==&x.S);
101   }
102   
103   inline bool operator!=(const _Self& x) const { return !operator==(x); }
104   
105   inline _NodeType* operator*() const {
106     assert(cycleNum < S.groups.size());
107     return (*S.groups[cycleNum])[slotNum];
108   }
109   inline _NodeType* operator->() const { return operator*(); }
110   
111          _Self& operator++();                           // Preincrement
112   inline _Self operator++(int) {                        // Postincrement
113     _Self tmp(*this); ++*this; return tmp; 
114   }
115   
116   static _Self begin(const InstrSchedule& _schedule);
117   static _Self end(  const InstrSchedule& _schedule);
118   
119 private:
120   inline _Self& operator=(const _Self& x); // DISABLE -- DO NOT IMPLEMENT
121   void  skipToNextInstr();
122 };
123
124
125 //----------------------------------------------------------------------
126 // class InstrSchedule:
127 // 
128 // Represents the schedule of machine instructions for a single basic block.
129 //----------------------------------------------------------------------
130
131 class InstrSchedule: public NonCopyable {
132 private:
133   const unsigned int nslots;
134   unsigned int numInstr;
135   vector<InstrGroup*> groups;           // indexed by cycle number
136   vector<cycles_t> startTime;           // indexed by node id
137   
138 public: // iterators
139   typedef ScheduleIterator<SchedGraphNode> iterator;
140   typedef ScheduleIterator<const SchedGraphNode> const_iterator;
141   
142         iterator begin();
143   const_iterator begin() const;
144         iterator end();
145   const_iterator end()   const;
146   
147 public: // constructors and destructor
148   /*ctor*/              InstrSchedule   (unsigned int _nslots,
149                                          unsigned int _numNodes);
150   /*dtor*/              ~InstrSchedule  ();
151   
152 public: // accessor functions to query chosen schedule
153   const SchedGraphNode* getInstr        (unsigned int slotNum,
154                                          cycles_t c) const {
155     const InstrGroup* igroup = this->getIGroup(c);
156     return (igroup == NULL)? NULL : (*igroup)[slotNum];
157   }
158   
159   inline InstrGroup*    getIGroup       (cycles_t c) {
160     if ((unsigned)c >= groups.size())
161       groups.resize(c+1);
162     if (groups[c] == NULL)
163       groups[c] = new InstrGroup(nslots);
164     return groups[c];
165   }
166   
167   inline const InstrGroup* getIGroup    (cycles_t c) const {
168     assert((unsigned)c < groups.size());
169     return groups[c];
170   }
171   
172   inline cycles_t       getStartTime    (unsigned int nodeId) const {
173     assert(nodeId < startTime.size());
174     return startTime[nodeId];
175   }
176   
177   unsigned int          getNumInstructions() const {
178     return numInstr;
179   }
180   
181   inline void           scheduleInstr   (const SchedGraphNode* node,
182                                          unsigned int slotNum,
183                                          cycles_t cycle) {
184     InstrGroup* igroup = this->getIGroup(cycle);
185     assert((*igroup)[slotNum] == NULL &&  "Slot already filled?");
186     igroup->addInstr(node, slotNum);
187     assert(node->getNodeId() < startTime.size());
188     startTime[node->getNodeId()] = cycle;
189     ++numInstr;
190   }
191   
192 private:
193   friend class iterator;
194   friend class const_iterator;
195   /*ctor*/      InstrSchedule   ();     // Disable: DO NOT IMPLEMENT.
196 };
197
198
199 /*ctor*/
200 InstrSchedule::InstrSchedule(unsigned int _nslots, unsigned int _numNodes)
201   : nslots(_nslots),
202     numInstr(0),
203     groups(2 * _numNodes / _nslots),            // 2 x lower-bound for #cycles
204     startTime(_numNodes, (cycles_t) -1)         // set all to -1
205 {
206 }
207
208
209 /*dtor*/
210 InstrSchedule::~InstrSchedule()
211 {
212   for (unsigned c=0, NC=groups.size(); c < NC; c++)
213     if (groups[c] != NULL)
214       delete groups[c];                 // delete InstrGroup objects
215 }
216
217
218 template<class _NodeType>
219 inline 
220 void
221 ScheduleIterator<_NodeType>::skipToNextInstr()
222 {
223   while(cycleNum < S.groups.size() && S.groups[cycleNum] == NULL)
224     ++cycleNum;                 // skip cycles with no instructions
225   
226   while (cycleNum < S.groups.size() &&
227          (*S.groups[cycleNum])[slotNum] == NULL)
228     {
229       ++slotNum;
230       if (slotNum == S.nslots)
231         {
232           ++cycleNum;
233           slotNum = 0;
234           while(cycleNum < S.groups.size() && S.groups[cycleNum] == NULL)
235             ++cycleNum;                 // skip cycles with no instructions
236         }
237     }
238 }
239
240 template<class _NodeType>
241 inline 
242 ScheduleIterator<_NodeType>&
243 ScheduleIterator<_NodeType>::operator++()       // Preincrement
244 {
245   ++slotNum;
246   if (slotNum == S.nslots)
247     {
248       ++cycleNum;
249       slotNum = 0;
250     }
251   skipToNextInstr(); 
252   return *this;
253 }
254
255 template<class _NodeType>
256 ScheduleIterator<_NodeType>
257 ScheduleIterator<_NodeType>::begin(const InstrSchedule& _schedule)
258 {
259   return _Self(_schedule, 0, 0);
260 }
261
262 template<class _NodeType>
263 ScheduleIterator<_NodeType>
264 ScheduleIterator<_NodeType>::end(const InstrSchedule& _schedule)
265 {
266   return _Self(_schedule, _schedule.groups.size(), 0);
267 }
268
269 InstrSchedule::iterator
270 InstrSchedule::begin()
271 {
272   return iterator::begin(*this);
273 }
274
275 InstrSchedule::const_iterator
276 InstrSchedule::begin() const
277 {
278   return const_iterator::begin(*this);
279 }
280
281 InstrSchedule::iterator
282 InstrSchedule::end()
283 {
284   return iterator::end(*this);
285 }
286
287 InstrSchedule::const_iterator
288 InstrSchedule::end() const
289 {
290   return const_iterator::end(  *this);
291 }
292
293
294 //----------------------------------------------------------------------
295 // class DelaySlotInfo:
296 // 
297 // Record information about delay slots for a single branch instruction.
298 // Delay slots are simply indexed by slot number 1 ... numDelaySlots
299 //----------------------------------------------------------------------
300
301 class DelaySlotInfo: public NonCopyable {
302 private:
303   const SchedGraphNode* brNode;
304   unsigned int ndelays;
305   vector<const SchedGraphNode*> delayNodeVec;
306   cycles_t delayedNodeCycle;
307   unsigned int delayedNodeSlotNum;
308   
309 public:
310   /*ctor*/      DelaySlotInfo           (const SchedGraphNode* _brNode,
311                                          unsigned _ndelays)
312     : brNode(_brNode), ndelays(_ndelays),
313       delayedNodeCycle(0), delayedNodeSlotNum(0) {}
314   
315   inline unsigned getNumDelays  () {
316     return ndelays;
317   }
318   
319   inline const vector<const SchedGraphNode*>& getDelayNodeVec() {
320     return delayNodeVec;
321   }
322   
323   inline void   addDelayNode            (const SchedGraphNode* node) {
324     delayNodeVec.push_back(node);
325     assert(delayNodeVec.size() <= ndelays && "Too many delay slot instrs!");
326   }
327   
328   inline void   recordChosenSlot        (cycles_t cycle, unsigned slotNum) {
329     delayedNodeCycle = cycle;
330     delayedNodeSlotNum = slotNum;
331   }
332   
333   unsigned      scheduleDelayedNode     (SchedulingManager& S);
334 };
335
336
337 //----------------------------------------------------------------------
338 // class SchedulingManager:
339 // 
340 // Represents the schedule of machine instructions for a single basic block.
341 //----------------------------------------------------------------------
342
343 class SchedulingManager: public NonCopyable {
344 public: // publicly accessible data members
345   const unsigned int nslots;
346   const MachineSchedInfo& schedInfo;
347   SchedPriorities& schedPrio;
348   InstrSchedule isched;
349   
350 private:
351   unsigned int totalInstrCount;
352   cycles_t curTime;
353   cycles_t nextEarliestIssueTime;               // next cycle we can issue
354   vector<std::hash_set<const SchedGraphNode*> > choicesForSlot; // indexed by slot#
355   vector<const SchedGraphNode*> choiceVec;      // indexed by node ptr
356   vector<int> numInClass;                       // indexed by sched class
357   vector<cycles_t> nextEarliestStartTime;       // indexed by opCode
358   std::hash_map<const SchedGraphNode*, DelaySlotInfo*> delaySlotInfoForBranches;
359                                                 // indexed by branch node ptr 
360   
361 public:
362   SchedulingManager(const TargetMachine& _target, const SchedGraph* graph,
363                     SchedPriorities& schedPrio);
364   ~SchedulingManager() {
365     for (std::hash_map<const SchedGraphNode*,
366            DelaySlotInfo*>::iterator I = delaySlotInfoForBranches.begin(),
367            E = delaySlotInfoForBranches.end(); I != E; ++I)
368       delete I->second;
369   }
370   
371   //----------------------------------------------------------------------
372   // Simplify access to the machine instruction info
373   //----------------------------------------------------------------------
374   
375   inline const MachineInstrInfo& getInstrInfo   () const {
376     return schedInfo.getInstrInfo();
377   }
378   
379   //----------------------------------------------------------------------
380   // Interface for checking and updating the current time
381   //----------------------------------------------------------------------
382   
383   inline cycles_t       getTime                 () const {
384     return curTime;
385   }
386   
387   inline cycles_t       getEarliestIssueTime() const {
388     return nextEarliestIssueTime;
389   }
390   
391   inline cycles_t       getEarliestStartTimeForOp(MachineOpCode opCode) const {
392     assert(opCode < (int) nextEarliestStartTime.size());
393     return nextEarliestStartTime[opCode];
394   }
395   
396   // Update current time to specified cycle
397   inline void   updateTime              (cycles_t c) {
398     curTime = c;
399     schedPrio.updateTime(c);
400   }
401   
402   //----------------------------------------------------------------------
403   // Functions to manage the choices for the current cycle including:
404   // -- a vector of choices by priority (choiceVec)
405   // -- vectors of the choices for each instruction slot (choicesForSlot[])
406   // -- number of choices in each sched class, used to check issue conflicts
407   //    between choices for a single cycle
408   //----------------------------------------------------------------------
409   
410   inline unsigned int getNumChoices     () const {
411     return choiceVec.size();
412   }
413   
414   inline unsigned getNumChoicesInClass  (const InstrSchedClass& sc) const {
415     assert(sc < (int) numInClass.size() && "Invalid op code or sched class!");
416     return numInClass[sc];
417   }
418   
419   inline const SchedGraphNode* getChoice(unsigned int i) const {
420     // assert(i < choiceVec.size());    don't check here.
421     return choiceVec[i];
422   }
423   
424   inline std::hash_set<const SchedGraphNode*>& getChoicesForSlot(unsigned slotNum) {
425     assert(slotNum < nslots);
426     return choicesForSlot[slotNum];
427   }
428   
429   inline void   addChoice               (const SchedGraphNode* node) {
430     // Append the instruction to the vector of choices for current cycle.
431     // Increment numInClass[c] for the sched class to which the instr belongs.
432     choiceVec.push_back(node);
433     const InstrSchedClass& sc = schedInfo.getSchedClass(node->getOpCode());
434     assert(sc < (int) numInClass.size());
435     numInClass[sc]++;
436   }
437   
438   inline void   addChoiceToSlot         (unsigned int slotNum,
439                                          const SchedGraphNode* node) {
440     // Add the instruction to the choice set for the specified slot
441     assert(slotNum < nslots);
442     choicesForSlot[slotNum].insert(node);
443   }
444   
445   inline void   resetChoices            () {
446     choiceVec.clear();
447     for (unsigned int s=0; s < nslots; s++)
448       choicesForSlot[s].clear();
449     for (unsigned int c=0; c < numInClass.size(); c++)
450       numInClass[c] = 0;
451   }
452   
453   //----------------------------------------------------------------------
454   // Code to query and manage the partial instruction schedule so far
455   //----------------------------------------------------------------------
456   
457   inline unsigned int   getNumScheduled () const {
458     return isched.getNumInstructions();
459   }
460   
461   inline unsigned int   getNumUnscheduled() const {
462     return totalInstrCount - isched.getNumInstructions();
463   }
464   
465   inline bool           isScheduled     (const SchedGraphNode* node) const {
466     return (isched.getStartTime(node->getNodeId()) >= 0);
467   }
468   
469   inline void   scheduleInstr           (const SchedGraphNode* node,
470                                          unsigned int slotNum,
471                                          cycles_t cycle)
472   {
473     assert(! isScheduled(node) && "Instruction already scheduled?");
474     
475     // add the instruction to the schedule
476     isched.scheduleInstr(node, slotNum, cycle);
477     
478     // update the earliest start times of all nodes that conflict with `node'
479     // and the next-earliest time anything can issue if `node' causes bubbles
480     updateEarliestStartTimes(node, cycle);
481     
482     // remove the instruction from the choice sets for all slots
483     for (unsigned s=0; s < nslots; s++)
484       choicesForSlot[s].erase(node);
485     
486     // and decrement the instr count for the sched class to which it belongs
487     const InstrSchedClass& sc = schedInfo.getSchedClass(node->getOpCode());
488     assert(sc < (int) numInClass.size());
489     numInClass[sc]--;
490   }
491
492   //----------------------------------------------------------------------
493   // Create and retrieve delay slot info for delayed instructions
494   //----------------------------------------------------------------------
495   
496   inline DelaySlotInfo* getDelaySlotInfoForInstr(const SchedGraphNode* bn,
497                                                  bool createIfMissing=false)
498   {
499     std::hash_map<const SchedGraphNode*, DelaySlotInfo*>::const_iterator
500       I = delaySlotInfoForBranches.find(bn);
501     if (I != delaySlotInfoForBranches.end())
502       return I->second;
503
504     if (!createIfMissing) return 0;
505
506     DelaySlotInfo *dinfo =
507       new DelaySlotInfo(bn, getInstrInfo().getNumDelaySlots(bn->getOpCode()));
508     return delaySlotInfoForBranches[bn] = dinfo;
509   }
510   
511 private:
512   SchedulingManager();     // DISABLED: DO NOT IMPLEMENT
513   void updateEarliestStartTimes(const SchedGraphNode* node, cycles_t schedTime);
514 };
515
516
517 /*ctor*/
518 SchedulingManager::SchedulingManager(const TargetMachine& target,
519                                      const SchedGraph* graph,
520                                      SchedPriorities& _schedPrio)
521   : nslots(target.getSchedInfo().getMaxNumIssueTotal()),
522     schedInfo(target.getSchedInfo()),
523     schedPrio(_schedPrio),
524     isched(nslots, graph->getNumNodes()),
525     totalInstrCount(graph->getNumNodes() - 2),
526     nextEarliestIssueTime(0),
527     choicesForSlot(nslots),
528     numInClass(target.getSchedInfo().getNumSchedClasses(), 0),  // set all to 0
529     nextEarliestStartTime(target.getInstrInfo().getNumRealOpCodes(),
530                           (cycles_t) 0)                         // set all to 0
531 {
532   updateTime(0);
533   
534   // Note that an upper bound on #choices for each slot is = nslots since
535   // we use this vector to hold a feasible set of instructions, and more
536   // would be infeasible. Reserve that much memory since it is probably small.
537   for (unsigned int i=0; i < nslots; i++)
538     choicesForSlot[i].resize(nslots);
539 }
540
541
542 void
543 SchedulingManager::updateEarliestStartTimes(const SchedGraphNode* node,
544                                             cycles_t schedTime)
545 {
546   if (schedInfo.numBubblesAfter(node->getOpCode()) > 0)
547     { // Update next earliest time before which *nothing* can issue.
548       nextEarliestIssueTime = std::max(nextEarliestIssueTime,
549                   curTime + 1 + schedInfo.numBubblesAfter(node->getOpCode()));
550     }
551   
552   const vector<MachineOpCode>*
553     conflictVec = schedInfo.getConflictList(node->getOpCode());
554   
555   if (conflictVec != NULL)
556     for (unsigned i=0; i < conflictVec->size(); i++)
557       {
558         MachineOpCode toOp = (*conflictVec)[i];
559         cycles_t est = schedTime + schedInfo.getMinIssueGap(node->getOpCode(),
560                                                             toOp);
561         assert(toOp < (int) nextEarliestStartTime.size());
562         if (nextEarliestStartTime[toOp] < est)
563           nextEarliestStartTime[toOp] = est;
564       }
565 }
566
567 //************************* Internal Functions *****************************/
568
569
570 static void
571 AssignInstructionsToSlots(class SchedulingManager& S, unsigned maxIssue)
572 {
573   // find the slot to start from, in the current cycle
574   unsigned int startSlot = 0;
575   cycles_t curTime = S.getTime();
576   
577   assert(maxIssue > 0 && maxIssue <= S.nslots - startSlot);
578   
579   // If only one instruction can be issued, do so.
580   if (maxIssue == 1)
581     for (unsigned s=startSlot; s < S.nslots; s++)
582       if (S.getChoicesForSlot(s).size() > 0)
583         {// found the one instruction
584           S.scheduleInstr(*S.getChoicesForSlot(s).begin(), s, curTime);
585           return;
586         }
587   
588   // Otherwise, choose from the choices for each slot
589   // 
590   InstrGroup* igroup = S.isched.getIGroup(S.getTime());
591   assert(igroup != NULL && "Group creation failed?");
592   
593   // Find a slot that has only a single choice, and take it.
594   // If all slots have 0 or multiple choices, pick the first slot with
595   // choices and use its last instruction (just to avoid shifting the vector).
596   unsigned numIssued;
597   for (numIssued = 0; numIssued < maxIssue; numIssued++)
598     {
599       int chosenSlot = -1;
600       for (unsigned s=startSlot; s < S.nslots; s++)
601         if ((*igroup)[s] == NULL && S.getChoicesForSlot(s).size() == 1)
602           {
603             chosenSlot = (int) s;
604             break;
605           }
606       
607       if (chosenSlot == -1)
608         for (unsigned s=startSlot; s < S.nslots; s++)
609           if ((*igroup)[s] == NULL && S.getChoicesForSlot(s).size() > 0)
610             {
611               chosenSlot = (int) s;
612               break;
613             }
614       
615       if (chosenSlot != -1)
616         { // Insert the chosen instr in the chosen slot and
617           // erase it from all slots.
618           const SchedGraphNode* node= *S.getChoicesForSlot(chosenSlot).begin();
619           S.scheduleInstr(node, chosenSlot, curTime);
620         }
621     }
622   
623   assert(numIssued > 0 && "Should not happen when maxIssue > 0!");
624 }
625
626
627 // 
628 // For now, just assume we are scheduling within a single basic block.
629 // Get the machine instruction vector for the basic block and clear it,
630 // then append instructions in scheduled order.
631 // Also, re-insert the dummy PHI instructions that were at the beginning
632 // of the basic block, since they are not part of the schedule.
633 //   
634 static void
635 RecordSchedule(const BasicBlock* bb, const SchedulingManager& S)
636 {
637   MachineCodeForBasicBlock& mvec = bb->getMachineInstrVec();
638   const MachineInstrInfo& mii = S.schedInfo.getInstrInfo();
639   
640 #ifndef NDEBUG
641   // Lets make sure we didn't lose any instructions, except possibly
642   // some NOPs from delay slots.  Also, PHIs are not included in the schedule.
643   unsigned numInstr = 0;
644   for (MachineCodeForBasicBlock::iterator I=mvec.begin(); I != mvec.end(); ++I)
645     if (! mii.isNop((*I)->getOpCode()) &&
646         ! mii.isDummyPhiInstr((*I)->getOpCode()))
647       ++numInstr;
648   assert(S.isched.getNumInstructions() >= numInstr &&
649          "Lost some non-NOP instructions during scheduling!");
650 #endif
651   
652   if (S.isched.getNumInstructions() == 0)
653     return;                             // empty basic block!
654   
655   // First find the dummy instructions at the start of the basic block
656   MachineCodeForBasicBlock::iterator I = mvec.begin();
657   for ( ; I != mvec.end(); ++I)
658     if (! mii.isDummyPhiInstr((*I)->getOpCode()))
659       break;
660   
661   // Erase all except the dummy PHI instructions from mvec, and
662   // pre-allocate create space for the ones we will put back in.
663   mvec.erase(I, mvec.end());
664   mvec.reserve(mvec.size() + S.isched.getNumInstructions());
665   
666   InstrSchedule::const_iterator NIend = S.isched.end();
667   for (InstrSchedule::const_iterator NI = S.isched.begin(); NI != NIend; ++NI)
668     mvec.push_back(const_cast<MachineInstr*>((*NI)->getMachineInstr()));
669 }
670
671
672
673 static void
674 MarkSuccessorsReady(SchedulingManager& S, const SchedGraphNode* node)
675 {
676   // Check if any successors are now ready that were not already marked
677   // ready before, and that have not yet been scheduled.
678   // 
679   for (sg_succ_const_iterator SI = succ_begin(node); SI !=succ_end(node); ++SI)
680     if (! (*SI)->isDummyNode()
681         && ! S.isScheduled(*SI)
682         && ! S.schedPrio.nodeIsReady(*SI))
683       {// successor not scheduled and not marked ready; check *its* preds.
684         
685         bool succIsReady = true;
686         for (sg_pred_const_iterator P=pred_begin(*SI); P != pred_end(*SI); ++P)
687           if (! (*P)->isDummyNode()
688               && ! S.isScheduled(*P))
689             {
690               succIsReady = false;
691               break;
692             }
693         
694         if (succIsReady)        // add the successor to the ready list
695           S.schedPrio.insertReady(*SI);
696       }
697 }
698
699
700 // Choose up to `nslots' FEASIBLE instructions and assign each
701 // instruction to all possible slots that do not violate feasibility.
702 // FEASIBLE means it should be guaranteed that the set
703 // of chosen instructions can be issued in a single group.
704 // 
705 // Return value:
706 //      maxIssue : total number of feasible instructions
707 //      S.choicesForSlot[i=0..nslots] : set of instructions feasible in slot i
708 // 
709 static unsigned
710 FindSlotChoices(SchedulingManager& S,
711                 DelaySlotInfo*& getDelaySlotInfo)
712 {
713   // initialize result vectors to empty
714   S.resetChoices();
715   
716   // find the slot to start from, in the current cycle
717   unsigned int startSlot = 0;
718   InstrGroup* igroup = S.isched.getIGroup(S.getTime());
719   for (int s = S.nslots - 1; s >= 0; s--)
720     if ((*igroup)[s] != NULL)
721       {
722         startSlot = s+1;
723         break;
724       }
725   
726   // Make sure we pick at most one instruction that would break the group.
727   // Also, if we do pick one, remember which it was.
728   unsigned int indexForBreakingNode = S.nslots;
729   unsigned int indexForDelayedInstr = S.nslots;
730   DelaySlotInfo* delaySlotInfo = NULL;
731
732   getDelaySlotInfo = NULL;
733   
734   // Choose instructions in order of priority.
735   // Add choices to the choice vector in the SchedulingManager class as
736   // we choose them so that subsequent choices will be correctly tested
737   // for feasibility, w.r.t. higher priority choices for the same cycle.
738   // 
739   while (S.getNumChoices() < S.nslots - startSlot)
740     {
741       const SchedGraphNode* nextNode=S.schedPrio.getNextHighest(S,S.getTime());
742       if (nextNode == NULL)
743         break;                  // no more instructions for this cycle
744       
745       if (S.getInstrInfo().getNumDelaySlots(nextNode->getOpCode()) > 0)
746         {
747           delaySlotInfo = S.getDelaySlotInfoForInstr(nextNode);
748           if (delaySlotInfo != NULL)
749             {
750               if (indexForBreakingNode < S.nslots)
751                 // cannot issue a delayed instr in the same cycle as one
752                 // that breaks the issue group or as another delayed instr
753                 nextNode = NULL;
754               else
755                 indexForDelayedInstr = S.getNumChoices();
756             }
757         }
758       else if (S.schedInfo.breaksIssueGroup(nextNode->getOpCode()))
759         {
760           if (indexForBreakingNode < S.nslots)
761             // have a breaking instruction already so throw this one away
762             nextNode = NULL;
763           else
764             indexForBreakingNode = S.getNumChoices();
765         }
766       
767       if (nextNode != NULL)
768         {
769           S.addChoice(nextNode);
770       
771           if (S.schedInfo.isSingleIssue(nextNode->getOpCode()))
772             {
773               assert(S.getNumChoices() == 1 &&
774                      "Prioritizer returned invalid instr for this cycle!");
775               break;
776             }
777         }
778           
779       if (indexForDelayedInstr < S.nslots)
780         break;                  // leave the rest for delay slots
781     }
782   
783   assert(S.getNumChoices() <= S.nslots);
784   assert(! (indexForDelayedInstr < S.nslots &&
785             indexForBreakingNode < S.nslots) && "Cannot have both in a cycle");
786   
787   // Assign each chosen instruction to all possible slots for that instr.
788   // But if only one instruction was chosen, put it only in the first
789   // feasible slot; no more analysis will be needed.
790   // 
791   if (indexForDelayedInstr >= S.nslots && 
792       indexForBreakingNode >= S.nslots)
793     { // No instructions that break the issue group or that have delay slots.
794       // This is the common case, so handle it separately for efficiency.
795       
796       if (S.getNumChoices() == 1)
797         {
798           MachineOpCode opCode = S.getChoice(0)->getOpCode();
799           unsigned int s;
800           for (s=startSlot; s < S.nslots; s++)
801             if (S.schedInfo.instrCanUseSlot(opCode, s))
802               break;
803           assert(s < S.nslots && "No feasible slot for this opCode?");
804           S.addChoiceToSlot(s, S.getChoice(0));
805         }
806       else
807         {
808           for (unsigned i=0; i < S.getNumChoices(); i++)
809             {
810               MachineOpCode opCode = S.getChoice(i)->getOpCode();
811               for (unsigned int s=startSlot; s < S.nslots; s++)
812                 if (S.schedInfo.instrCanUseSlot(opCode, s))
813                   S.addChoiceToSlot(s, S.getChoice(i));
814             }
815         }
816     }
817   else if (indexForDelayedInstr < S.nslots)
818     {
819       // There is an instruction that needs delay slots.
820       // Try to assign that instruction to a higher slot than any other
821       // instructions in the group, so that its delay slots can go
822       // right after it.
823       //  
824
825       assert(indexForDelayedInstr == S.getNumChoices() - 1 &&
826              "Instruction with delay slots should be last choice!");
827       assert(delaySlotInfo != NULL && "No delay slot info for instr?");
828       
829       const SchedGraphNode* delayedNode = S.getChoice(indexForDelayedInstr);
830       MachineOpCode delayOpCode = delayedNode->getOpCode();
831       unsigned ndelays= S.getInstrInfo().getNumDelaySlots(delayOpCode);
832       
833       unsigned delayedNodeSlot = S.nslots;
834       int highestSlotUsed;
835       
836       // Find the last possible slot for the delayed instruction that leaves
837       // at least `d' slots vacant after it (d = #delay slots)
838       for (int s = S.nslots-ndelays-1; s >= (int) startSlot; s--)
839         if (S.schedInfo.instrCanUseSlot(delayOpCode, s))
840           {
841             delayedNodeSlot = s;
842             break;
843           }
844       
845       highestSlotUsed = -1;
846       for (unsigned i=0; i < S.getNumChoices() - 1; i++)
847         {
848           // Try to assign every other instruction to a lower numbered
849           // slot than delayedNodeSlot.
850           MachineOpCode opCode =S.getChoice(i)->getOpCode();
851           bool noSlotFound = true;
852           unsigned int s;
853           for (s=startSlot; s < delayedNodeSlot; s++)
854             if (S.schedInfo.instrCanUseSlot(opCode, s))
855               {
856                 S.addChoiceToSlot(s, S.getChoice(i));
857                 noSlotFound = false;
858               }
859           
860           // No slot before `delayedNodeSlot' was found for this opCode
861           // Use a later slot, and allow some delay slots to fall in
862           // the next cycle.
863           if (noSlotFound)
864             for ( ; s < S.nslots; s++)
865               if (S.schedInfo.instrCanUseSlot(opCode, s))
866                 {
867                   S.addChoiceToSlot(s, S.getChoice(i));
868                   break;
869                 }
870           
871           assert(s < S.nslots && "No feasible slot for instruction?");
872           
873           highestSlotUsed = std::max(highestSlotUsed, (int) s);
874         }
875       
876       assert(highestSlotUsed <= (int) S.nslots-1 && "Invalid slot used?");
877       
878       // We will put the delayed node in the first slot after the
879       // highest slot used.  But we just mark that for now, and
880       // schedule it separately because we want to schedule the delay
881       // slots for the node at the same time.
882       cycles_t dcycle = S.getTime();
883       unsigned int dslot = highestSlotUsed + 1;
884       if (dslot == S.nslots)
885         {
886           dslot = 0;
887           ++dcycle;
888         }
889       delaySlotInfo->recordChosenSlot(dcycle, dslot);
890       getDelaySlotInfo = delaySlotInfo;
891     }
892   else
893     { // There is an instruction that breaks the issue group.
894       // For such an instruction, assign to the last possible slot in
895       // the current group, and then don't assign any other instructions
896       // to later slots.
897       assert(indexForBreakingNode < S.nslots);
898       const SchedGraphNode* breakingNode=S.getChoice(indexForBreakingNode);
899       unsigned breakingSlot = INT_MAX;
900       unsigned int nslotsToUse = S.nslots;
901           
902       // Find the last possible slot for this instruction.
903       for (int s = S.nslots-1; s >= (int) startSlot; s--)
904         if (S.schedInfo.instrCanUseSlot(breakingNode->getOpCode(), s))
905           {
906             breakingSlot = s;
907             break;
908           }
909       assert(breakingSlot < S.nslots &&
910              "No feasible slot for `breakingNode'?");
911       
912       // Higher priority instructions than the one that breaks the group:
913       // These can be assigned to all slots, but will be assigned only
914       // to earlier slots if possible.
915       for (unsigned i=0;
916            i < S.getNumChoices() && i < indexForBreakingNode; i++)
917         {
918           MachineOpCode opCode =S.getChoice(i)->getOpCode();
919           
920           // If a higher priority instruction cannot be assigned to
921           // any earlier slots, don't schedule the breaking instruction.
922           // 
923           bool foundLowerSlot = false;
924           nslotsToUse = S.nslots;           // May be modified in the loop
925           for (unsigned int s=startSlot; s < nslotsToUse; s++)
926             if (S.schedInfo.instrCanUseSlot(opCode, s))
927               {
928                 if (breakingSlot < S.nslots && s < breakingSlot)
929                   {
930                     foundLowerSlot = true;
931                     nslotsToUse = breakingSlot; // RESETS LOOP UPPER BOUND!
932                   }
933                     
934                 S.addChoiceToSlot(s, S.getChoice(i));
935               }
936               
937           if (!foundLowerSlot)
938             breakingSlot = INT_MAX;             // disable breaking instr
939         }
940       
941       // Assign the breaking instruction (if any) to a single slot
942       // Otherwise, just ignore the instruction.  It will simply be
943       // scheduled in a later cycle.
944       if (breakingSlot < S.nslots)
945         {
946           S.addChoiceToSlot(breakingSlot, breakingNode);
947           nslotsToUse = breakingSlot;
948         }
949       else
950         nslotsToUse = S.nslots;
951           
952       // For lower priority instructions than the one that breaks the
953       // group, only assign them to slots lower than the breaking slot.
954       // Otherwise, just ignore the instruction.
955       for (unsigned i=indexForBreakingNode+1; i < S.getNumChoices(); i++)
956         {
957           MachineOpCode opCode = S.getChoice(i)->getOpCode();
958           for (unsigned int s=startSlot; s < nslotsToUse; s++)
959             if (S.schedInfo.instrCanUseSlot(opCode, s))
960               S.addChoiceToSlot(s, S.getChoice(i));
961         }
962     } // endif (no delay slots and no breaking slots)
963   
964   return S.getNumChoices();
965 }
966
967
968 static unsigned
969 ChooseOneGroup(SchedulingManager& S)
970 {
971   assert(S.schedPrio.getNumReady() > 0
972          && "Don't get here without ready instructions.");
973   
974   cycles_t firstCycle = S.getTime();
975   DelaySlotInfo* getDelaySlotInfo = NULL;
976   
977   // Choose up to `nslots' feasible instructions and their possible slots.
978   unsigned numIssued = FindSlotChoices(S, getDelaySlotInfo);
979   
980   while (numIssued == 0)
981     {
982       S.updateTime(S.getTime()+1);
983       numIssued = FindSlotChoices(S, getDelaySlotInfo);
984     }
985   
986   AssignInstructionsToSlots(S, numIssued);
987   
988   if (getDelaySlotInfo != NULL)
989     numIssued += getDelaySlotInfo->scheduleDelayedNode(S); 
990   
991   // Print trace of scheduled instructions before newly ready ones
992   if (SchedDebugLevel >= Sched_PrintSchedTrace)
993     {
994       for (cycles_t c = firstCycle; c <= S.getTime(); c++)
995         {
996           cerr << "    Cycle " << (long)c << " : Scheduled instructions:\n";
997           const InstrGroup* igroup = S.isched.getIGroup(c);
998           for (unsigned int s=0; s < S.nslots; s++)
999             {
1000               cerr << "        ";
1001               if ((*igroup)[s] != NULL)
1002                 cerr << * ((*igroup)[s])->getMachineInstr() << "\n";
1003               else
1004                 cerr << "<none>\n";
1005             }
1006         }
1007     }
1008   
1009   return numIssued;
1010 }
1011
1012
1013 static void
1014 ForwardListSchedule(SchedulingManager& S)
1015 {
1016   unsigned N;
1017   const SchedGraphNode* node;
1018   
1019   S.schedPrio.initialize();
1020   
1021   while ((N = S.schedPrio.getNumReady()) > 0)
1022     {
1023       cycles_t nextCycle = S.getTime();
1024       
1025       // Choose one group of instructions for a cycle, plus any delay slot
1026       // instructions (which may overflow into successive cycles).
1027       // This will advance S.getTime() to the last cycle in which
1028       // instructions are actually issued.
1029       // 
1030       unsigned numIssued = ChooseOneGroup(S);
1031       assert(numIssued > 0 && "Deadlock in list scheduling algorithm?");
1032       
1033       // Notify the priority manager of scheduled instructions and mark
1034       // any successors that may now be ready
1035       // 
1036       for (cycles_t c = nextCycle; c <= S.getTime(); c++)
1037         {
1038           const InstrGroup* igroup = S.isched.getIGroup(c);
1039           for (unsigned int s=0; s < S.nslots; s++)
1040             if ((node = (*igroup)[s]) != NULL)
1041               {
1042                 S.schedPrio.issuedReadyNodeAt(S.getTime(), node);
1043                 MarkSuccessorsReady(S, node);
1044               }
1045         }
1046       
1047       // Move to the next the next earliest cycle for which
1048       // an instruction can be issued, or the next earliest in which
1049       // one will be ready, or to the next cycle, whichever is latest.
1050       // 
1051       S.updateTime(std::max(S.getTime() + 1,
1052                             std::max(S.getEarliestIssueTime(),
1053                                      S.schedPrio.getEarliestReadyTime())));
1054     }
1055 }
1056
1057
1058 //---------------------------------------------------------------------
1059 // Code for filling delay slots for delayed terminator instructions
1060 // (e.g., BRANCH and RETURN).  Delay slots for non-terminator
1061 // instructions (e.g., CALL) are not handled here because they almost
1062 // always can be filled with instructions from the call sequence code
1063 // before a call.  That's preferable because we incur many tradeoffs here
1064 // when we cannot find single-cycle instructions that can be reordered.
1065 //----------------------------------------------------------------------
1066
1067 static bool
1068 NodeCanFillDelaySlot(const SchedulingManager& S,
1069                      const SchedGraphNode* node,
1070                      const SchedGraphNode* brNode,
1071                      bool nodeIsPredecessor)
1072 {
1073   assert(! node->isDummyNode());
1074   
1075   // don't put a branch in the delay slot of another branch
1076   if (S.getInstrInfo().isBranch(node->getOpCode()))
1077     return false;
1078   
1079   // don't put a single-issue instruction in the delay slot of a branch
1080   if (S.schedInfo.isSingleIssue(node->getOpCode()))
1081     return false;
1082   
1083   // don't put a load-use dependence in the delay slot of a branch
1084   const MachineInstrInfo& mii = S.getInstrInfo();
1085   
1086   for (SchedGraphNode::const_iterator EI = node->beginInEdges();
1087        EI != node->endInEdges(); ++EI)
1088     if (! (*EI)->getSrc()->isDummyNode()
1089         && mii.isLoad((*EI)->getSrc()->getOpCode())
1090         && (*EI)->getDepType() == SchedGraphEdge::CtrlDep)
1091       return false;
1092   
1093   // for now, don't put an instruction that does not have operand
1094   // interlocks in the delay slot of a branch
1095   if (! S.getInstrInfo().hasOperandInterlock(node->getOpCode()))
1096     return false;
1097   
1098   // Finally, if the instruction preceeds the branch, we make sure the
1099   // instruction can be reordered relative to the branch.  We simply check
1100   // if the instr. has only 1 outgoing edge, viz., a CD edge to the branch.
1101   // 
1102   if (nodeIsPredecessor)
1103     {
1104       bool onlyCDEdgeToBranch = true;
1105       for (SchedGraphNode::const_iterator OEI = node->beginOutEdges();
1106            OEI != node->endOutEdges(); ++OEI)
1107         if (! (*OEI)->getSink()->isDummyNode()
1108             && ((*OEI)->getSink() != brNode
1109                 || (*OEI)->getDepType() != SchedGraphEdge::CtrlDep))
1110           {
1111             onlyCDEdgeToBranch = false;
1112             break;
1113           }
1114       
1115       if (!onlyCDEdgeToBranch)
1116         return false;
1117     }
1118   
1119   return true;
1120 }
1121
1122
1123 static void
1124 MarkNodeForDelaySlot(SchedulingManager& S,
1125                      SchedGraph* graph,
1126                      SchedGraphNode* node,
1127                      const SchedGraphNode* brNode,
1128                      bool nodeIsPredecessor)
1129 {
1130   if (nodeIsPredecessor)
1131     { // If node is in the same basic block (i.e., preceeds brNode),
1132       // remove it and all its incident edges from the graph.  Make sure we
1133       // add dummy edges for pred/succ nodes that become entry/exit nodes.
1134       graph->eraseIncidentEdges(node, /*addDummyEdges*/ true);
1135     }
1136   else
1137     { // If the node was from a target block, add the node to the graph
1138       // and add a CD edge from brNode to node.
1139       assert(0 && "NOT IMPLEMENTED YET");
1140     }
1141   
1142   DelaySlotInfo* dinfo = S.getDelaySlotInfoForInstr(brNode, /*create*/ true);
1143   dinfo->addDelayNode(node);
1144 }
1145
1146
1147 void
1148 FindUsefulInstructionsForDelaySlots(SchedulingManager& S,
1149                                     SchedGraphNode* brNode,
1150                                     vector<SchedGraphNode*>& sdelayNodeVec)
1151 {
1152   const MachineInstrInfo& mii = S.getInstrInfo();
1153   unsigned ndelays =
1154     mii.getNumDelaySlots(brNode->getOpCode());
1155   
1156   if (ndelays == 0)
1157     return;
1158   
1159   sdelayNodeVec.reserve(ndelays);
1160   
1161   // Use a separate vector to hold the feasible multi-cycle nodes.
1162   // These will be used if not enough single-cycle nodes are found.
1163   // 
1164   vector<SchedGraphNode*> mdelayNodeVec;
1165   
1166   for (sg_pred_iterator P = pred_begin(brNode);
1167        P != pred_end(brNode) && sdelayNodeVec.size() < ndelays; ++P)
1168     if (! (*P)->isDummyNode() &&
1169         ! mii.isNop((*P)->getOpCode()) &&
1170         NodeCanFillDelaySlot(S, *P, brNode, /*pred*/ true))
1171       {
1172         if (mii.maxLatency((*P)->getOpCode()) > 1)
1173           mdelayNodeVec.push_back(*P);
1174         else
1175           sdelayNodeVec.push_back(*P);
1176       }
1177   
1178   // If not enough single-cycle instructions were found, select the
1179   // lowest-latency multi-cycle instructions and use them.
1180   // Note that this is the most efficient code when only 1 (or even 2)
1181   // values need to be selected.
1182   // 
1183   while (sdelayNodeVec.size() < ndelays && mdelayNodeVec.size() > 0)
1184     {
1185       unsigned lmin =
1186         mii.maxLatency(mdelayNodeVec[0]->getOpCode());
1187       unsigned minIndex   = 0;
1188       for (unsigned i=1; i < mdelayNodeVec.size(); i++)
1189         {
1190           unsigned li = 
1191             mii.maxLatency(mdelayNodeVec[i]->getOpCode());
1192           if (lmin >= li)
1193             {
1194               lmin = li;
1195               minIndex = i;
1196             }
1197         }
1198       sdelayNodeVec.push_back(mdelayNodeVec[minIndex]);
1199       if (sdelayNodeVec.size() < ndelays) // avoid the last erase!
1200         mdelayNodeVec.erase(mdelayNodeVec.begin() + minIndex);
1201     }
1202 }
1203
1204
1205 // Remove the NOPs currently in delay slots from the graph.
1206 // Mark instructions specified in sdelayNodeVec to replace them.
1207 // If not enough useful instructions were found, mark the NOPs to be used
1208 // for filling delay slots, otherwise, otherwise just discard them.
1209 // 
1210 void
1211 ReplaceNopsWithUsefulInstr(SchedulingManager& S,
1212                            SchedGraphNode* node,
1213                            vector<SchedGraphNode*> sdelayNodeVec,
1214                            SchedGraph* graph)
1215 {
1216   vector<SchedGraphNode*> nopNodeVec;   // this will hold unused NOPs
1217   const MachineInstrInfo& mii = S.getInstrInfo();
1218   const MachineInstr* brInstr = node->getMachineInstr();
1219   unsigned ndelays= mii.getNumDelaySlots(brInstr->getOpCode());
1220   assert(ndelays > 0 && "Unnecessary call to replace NOPs");
1221   
1222   // Remove the NOPs currently in delay slots from the graph.
1223   // If not enough useful instructions were found, use the NOPs to
1224   // fill delay slots, otherwise, just discard them.
1225   //  
1226   unsigned int firstDelaySlotIdx = node->getOrigIndexInBB() + 1;
1227   MachineCodeForBasicBlock& bbMvec  = node->getBB()->getMachineInstrVec();
1228   assert(bbMvec[firstDelaySlotIdx - 1] == brInstr &&
1229          "Incorrect instr. index in basic block for brInstr");
1230   
1231   // First find all useful instructions already in the delay slots
1232   // and USE THEM.  We'll throw away the unused alternatives below
1233   // 
1234   for (unsigned i=firstDelaySlotIdx; i < firstDelaySlotIdx + ndelays; ++i)
1235     if (! mii.isNop(bbMvec[i]->getOpCode()))
1236       sdelayNodeVec.insert(sdelayNodeVec.begin(),
1237                            graph->getGraphNodeForInstr(bbMvec[i]));
1238   
1239   // Then find the NOPs and keep only as many as are needed.
1240   // Put the rest in nopNodeVec to be deleted.
1241   for (unsigned i=firstDelaySlotIdx; i < firstDelaySlotIdx + ndelays; ++i)
1242     if (mii.isNop(bbMvec[i]->getOpCode()))
1243       if (sdelayNodeVec.size() < ndelays)
1244         sdelayNodeVec.push_back(graph->getGraphNodeForInstr(bbMvec[i]));
1245       else
1246         nopNodeVec.push_back(graph->getGraphNodeForInstr(bbMvec[i]));
1247   
1248   assert(sdelayNodeVec.size() >= ndelays);
1249   
1250   // If some delay slots were already filled, throw away that many new choices
1251   if (sdelayNodeVec.size() > ndelays)
1252     sdelayNodeVec.resize(ndelays);
1253   
1254   // Mark the nodes chosen for delay slots.  This removes them from the graph.
1255   for (unsigned i=0; i < sdelayNodeVec.size(); i++)
1256     MarkNodeForDelaySlot(S, graph, sdelayNodeVec[i], node, true);
1257   
1258   // And remove the unused NOPs from the graph.
1259   for (unsigned i=0; i < nopNodeVec.size(); i++)
1260     graph->eraseIncidentEdges(nopNodeVec[i], /*addDummyEdges*/ true);
1261 }
1262
1263
1264 // For all delayed instructions, choose instructions to put in the delay
1265 // slots and pull those out of the graph.  Mark them for the delay slots
1266 // in the DelaySlotInfo object for that graph node.  If no useful work
1267 // is found for a delay slot, use the NOP that is currently in that slot.
1268 // 
1269 // We try to fill the delay slots with useful work for all instructions
1270 // EXCEPT CALLS AND RETURNS.
1271 // For CALLs and RETURNs, it is nearly always possible to use one of the
1272 // call sequence instrs and putting anything else in the delay slot could be
1273 // suboptimal.  Also, it complicates generating the calling sequence code in
1274 // regalloc.
1275 // 
1276 static void
1277 ChooseInstructionsForDelaySlots(SchedulingManager& S,
1278                                 const BasicBlock *bb,
1279                                 SchedGraph *graph)
1280 {
1281   const MachineInstrInfo& mii = S.getInstrInfo();
1282   const Instruction *termInstr = (Instruction*)bb->getTerminator();
1283   MachineCodeForInstruction &termMvec=MachineCodeForInstruction::get(termInstr);
1284   vector<SchedGraphNode*> delayNodeVec;
1285   const MachineInstr* brInstr = NULL;
1286   
1287   if (termInstr->getOpcode() != Instruction::Ret)
1288     {
1289       // To find instructions that need delay slots without searching the full
1290       // machine code, we assume that the only delayed instructions are CALLs
1291       // or instructions generated for the terminator inst.
1292       // Find the first branch instr in the sequence of machine instrs for term
1293       // 
1294       unsigned first = 0;
1295       while (first < termMvec.size() &&
1296              ! mii.isBranch(termMvec[first]->getOpCode()))
1297         {
1298           ++first;
1299         }
1300       assert(first < termMvec.size() &&
1301          "No branch instructions for BR?  Ok, but weird!  Delete assertion.");
1302       
1303       brInstr = (first < termMvec.size())? termMvec[first] : NULL;
1304       
1305       // Compute a vector of the nodes chosen for delay slots and then
1306       // mark delay slots to replace NOPs with these useful instructions.
1307       // 
1308       if (brInstr != NULL)
1309         {
1310           SchedGraphNode* brNode = graph->getGraphNodeForInstr(brInstr);
1311           FindUsefulInstructionsForDelaySlots(S, brNode, delayNodeVec);
1312           ReplaceNopsWithUsefulInstr(S, brNode, delayNodeVec, graph);
1313         }
1314     }
1315   
1316   // Also mark delay slots for other delayed instructions to hold NOPs. 
1317   // Simply passing in an empty delayNodeVec will have this effect.
1318   // 
1319   delayNodeVec.clear();
1320   const MachineCodeForBasicBlock& bbMvec = bb->getMachineInstrVec();
1321   for (unsigned i=0; i < bbMvec.size(); i++)
1322     if (bbMvec[i] != brInstr &&
1323         mii.getNumDelaySlots(bbMvec[i]->getOpCode()) > 0)
1324       {
1325         SchedGraphNode* node = graph->getGraphNodeForInstr(bbMvec[i]);
1326         ReplaceNopsWithUsefulInstr(S, node, delayNodeVec, graph);
1327       }
1328 }
1329
1330
1331 // 
1332 // Schedule the delayed branch and its delay slots
1333 // 
1334 unsigned
1335 DelaySlotInfo::scheduleDelayedNode(SchedulingManager& S)
1336 {
1337   assert(delayedNodeSlotNum < S.nslots && "Illegal slot for branch");
1338   assert(S.isched.getInstr(delayedNodeSlotNum, delayedNodeCycle) == NULL
1339          && "Slot for branch should be empty");
1340   
1341   unsigned int nextSlot = delayedNodeSlotNum;
1342   cycles_t nextTime = delayedNodeCycle;
1343   
1344   S.scheduleInstr(brNode, nextSlot, nextTime);
1345   
1346   for (unsigned d=0; d < ndelays; d++)
1347     {
1348       ++nextSlot;
1349       if (nextSlot == S.nslots)
1350         {
1351           nextSlot = 0;
1352           nextTime++;
1353         }
1354       
1355       // Find the first feasible instruction for this delay slot
1356       // Note that we only check for issue restrictions here.
1357       // We do *not* check for flow dependences but rely on pipeline
1358       // interlocks to resolve them.  Machines without interlocks
1359       // will require this code to be modified.
1360       for (unsigned i=0; i < delayNodeVec.size(); i++)
1361         {
1362           const SchedGraphNode* dnode = delayNodeVec[i];
1363           if ( ! S.isScheduled(dnode)
1364                && S.schedInfo.instrCanUseSlot(dnode->getOpCode(), nextSlot)
1365                && instrIsFeasible(S, dnode->getOpCode()))
1366             {
1367               assert(S.getInstrInfo().hasOperandInterlock(dnode->getOpCode())
1368                      && "Instructions without interlocks not yet supported "
1369                      "when filling branch delay slots");
1370               S.scheduleInstr(dnode, nextSlot, nextTime);
1371               break;
1372             }
1373         }
1374     }
1375   
1376   // Update current time if delay slots overflowed into later cycles.
1377   // Do this here because we know exactly which cycle is the last cycle
1378   // that contains delay slots.  The next loop doesn't compute that.
1379   if (nextTime > S.getTime())
1380     S.updateTime(nextTime);
1381   
1382   // Now put any remaining instructions in the unfilled delay slots.
1383   // This could lead to suboptimal performance but needed for correctness.
1384   nextSlot = delayedNodeSlotNum;
1385   nextTime = delayedNodeCycle;
1386   for (unsigned i=0; i < delayNodeVec.size(); i++)
1387     if (! S.isScheduled(delayNodeVec[i]))
1388       {
1389         do { // find the next empty slot
1390           ++nextSlot;
1391           if (nextSlot == S.nslots)
1392             {
1393               nextSlot = 0;
1394               nextTime++;
1395             }
1396         } while (S.isched.getInstr(nextSlot, nextTime) != NULL);
1397         
1398         S.scheduleInstr(delayNodeVec[i], nextSlot, nextTime);
1399         break;
1400       }
1401
1402   return 1 + ndelays;
1403 }
1404
1405
1406 // Check if the instruction would conflict with instructions already
1407 // chosen for the current cycle
1408 // 
1409 static inline bool
1410 ConflictsWithChoices(const SchedulingManager& S,
1411                      MachineOpCode opCode)
1412 {
1413   // Check if the instruction must issue by itself, and some feasible
1414   // choices have already been made for this cycle
1415   if (S.getNumChoices() > 0 && S.schedInfo.isSingleIssue(opCode))
1416     return true;
1417   
1418   // For each class that opCode belongs to, check if there are too many
1419   // instructions of that class.
1420   // 
1421   const InstrSchedClass sc = S.schedInfo.getSchedClass(opCode);
1422   return (S.getNumChoicesInClass(sc) == S.schedInfo.getMaxIssueForClass(sc));
1423 }
1424
1425
1426 //************************* External Functions *****************************/
1427
1428
1429 //---------------------------------------------------------------------------
1430 // Function: ViolatesMinimumGap
1431 // 
1432 // Purpose:
1433 //   Check minimum gap requirements relative to instructions scheduled in
1434 //   previous cycles.
1435 //   Note that we do not need to consider `nextEarliestIssueTime' here because
1436 //   that is also captured in the earliest start times for each opcode.
1437 //---------------------------------------------------------------------------
1438
1439 static inline bool
1440 ViolatesMinimumGap(const SchedulingManager& S,
1441                    MachineOpCode opCode,
1442                    const cycles_t inCycle)
1443 {
1444   return (inCycle < S.getEarliestStartTimeForOp(opCode));
1445 }
1446
1447
1448 //---------------------------------------------------------------------------
1449 // Function: instrIsFeasible
1450 // 
1451 // Purpose:
1452 //   Check if any issue restrictions would prevent the instruction from
1453 //   being issued in the current cycle
1454 //---------------------------------------------------------------------------
1455
1456 bool
1457 instrIsFeasible(const SchedulingManager& S,
1458                 MachineOpCode opCode)
1459 {
1460   // skip the instruction if it cannot be issued due to issue restrictions
1461   // caused by previously issued instructions
1462   if (ViolatesMinimumGap(S, opCode, S.getTime()))
1463     return false;
1464   
1465   // skip the instruction if it cannot be issued due to issue restrictions
1466   // caused by previously chosen instructions for the current cycle
1467   if (ConflictsWithChoices(S, opCode))
1468     return false;
1469   
1470   return true;
1471 }
1472
1473 //---------------------------------------------------------------------------
1474 // Function: ScheduleInstructionsWithSSA
1475 // 
1476 // Purpose:
1477 //   Entry point for instruction scheduling on SSA form.
1478 //   Schedules the machine instructions generated by instruction selection.
1479 //   Assumes that register allocation has not been done, i.e., operands
1480 //   are still in SSA form.
1481 //---------------------------------------------------------------------------
1482
1483 namespace {
1484   class InstructionSchedulingWithSSA : public MethodPass {
1485     const TargetMachine &target;
1486   public:
1487     inline InstructionSchedulingWithSSA(const TargetMachine &T) : target(T) {}
1488   
1489     // getAnalysisUsageInfo - We use LiveVarInfo...
1490     virtual void getAnalysisUsageInfo(Pass::AnalysisSet &Requires,
1491                                       Pass::AnalysisSet &Destroyed,
1492                                       Pass::AnalysisSet &Provided) {
1493       Requires.push_back(MethodLiveVarInfo::ID);
1494       Destroyed.push_back(MethodLiveVarInfo::ID);
1495     }
1496     
1497     bool runOnMethod(Function *F);
1498   };
1499 } // end anonymous namespace
1500
1501
1502 bool
1503 InstructionSchedulingWithSSA::runOnMethod(Function *M)
1504 {
1505   if (SchedDebugLevel == Sched_Disable)
1506     return false;
1507   
1508   SchedGraphSet graphSet(M, target);    
1509   
1510   if (SchedDebugLevel >= Sched_PrintSchedGraphs)
1511     {
1512       cerr << "\n*** SCHEDULING GRAPHS FOR INSTRUCTION SCHEDULING\n";
1513       graphSet.dump();
1514     }
1515   
1516   for (SchedGraphSet::const_iterator GI=graphSet.begin(), GE=graphSet.end();
1517        GI != GE; ++GI)
1518     {
1519       SchedGraph* graph = (*GI);
1520       const vector<const BasicBlock*> &bbvec = graph->getBasicBlocks();
1521       assert(bbvec.size() == 1 && "Cannot schedule multiple basic blocks");
1522       const BasicBlock* bb = bbvec[0];
1523       
1524       if (SchedDebugLevel >= Sched_PrintSchedTrace)
1525         cerr << "\n*** TRACE OF INSTRUCTION SCHEDULING OPERATIONS\n\n";
1526       
1527       // expensive!
1528       SchedPriorities schedPrio(M, graph,getAnalysis<MethodLiveVarInfo>());
1529       SchedulingManager S(target, graph, schedPrio);
1530           
1531       ChooseInstructionsForDelaySlots(S, bb, graph); // modifies graph
1532       
1533       ForwardListSchedule(S);               // computes schedule in S
1534       
1535       RecordSchedule(bb, S);                // records schedule in BB
1536     }
1537   
1538   if (SchedDebugLevel >= Sched_PrintMachineCode)
1539     {
1540       cerr << "\n*** Machine instructions after INSTRUCTION SCHEDULING\n";
1541       MachineCodeForMethod::get(M).dump();
1542     }
1543   
1544   return false;
1545 }
1546
1547
1548 MethodPass*
1549 createInstructionSchedulingWithSSAPass(const TargetMachine &tgt)
1550 {
1551   return new InstructionSchedulingWithSSA(tgt);
1552 }