MEGAPATCH checkin.
[oota-llvm.git] / lib / CodeGen / InstrSched / SchedGraph.cpp
1 // $Id$
2 //***************************************************************************
3 // File:
4 //      SchedGraph.cpp
5 // 
6 // Purpose:
7 //      Scheduling graph based on SSA graph plus extra dependence edges
8 //      capturing dependences due to machine resources (machine registers,
9 //      CC registers, and any others).
10 // 
11 // History:
12 //      7/20/01  -  Vikram Adve  -  Created
13 //**************************************************************************/
14
15 #include "SchedGraph.h"
16 #include "llvm/CodeGen/InstrSelection.h"
17 #include "llvm/CodeGen/MachineCodeForInstruction.h"
18 #include "llvm/Target/MachineRegInfo.h"
19 #include "llvm/Target/TargetMachine.h"
20 #include "llvm/BasicBlock.h"
21 #include "llvm/Function.h"
22 #include "llvm/iOther.h"
23 #include "Support/StringExtras.h"
24 #include "Support/STLExtras.h"
25 #include <iostream>
26
27 using std::vector;
28 using std::pair;
29 using std::hash_map;
30 using std::cerr;
31
32 //*********************** Internal Data Structures *************************/
33
34 // The following two types need to be classes, not typedefs, so we can use
35 // opaque declarations in SchedGraph.h
36 // 
37 struct RefVec: public vector< pair<SchedGraphNode*, int> > {
38   typedef vector< pair<SchedGraphNode*, int> >::      iterator       iterator;
39   typedef vector< pair<SchedGraphNode*, int> >::const_iterator const_iterator;
40 };
41
42 struct RegToRefVecMap: public hash_map<int, RefVec> {
43   typedef hash_map<int, RefVec>::      iterator       iterator;
44   typedef hash_map<int, RefVec>::const_iterator const_iterator;
45 };
46
47 struct ValueToDefVecMap: public hash_map<const Instruction*, RefVec> {
48   typedef hash_map<const Instruction*, RefVec>::      iterator       iterator;
49   typedef hash_map<const Instruction*, RefVec>::const_iterator const_iterator;
50 };
51
52 // 
53 // class SchedGraphEdge
54 // 
55
56 /*ctor*/
57 SchedGraphEdge::SchedGraphEdge(SchedGraphNode* _src,
58                                SchedGraphNode* _sink,
59                                SchedGraphEdgeDepType _depType,
60                                unsigned int     _depOrderType,
61                                int _minDelay)
62   : src(_src),
63     sink(_sink),
64     depType(_depType),
65     depOrderType(_depOrderType),
66     minDelay((_minDelay >= 0)? _minDelay : _src->getLatency()),
67     val(NULL)
68 {
69   assert(src != sink && "Self-loop in scheduling graph!");
70   src->addOutEdge(this);
71   sink->addInEdge(this);
72 }
73
74
75 /*ctor*/
76 SchedGraphEdge::SchedGraphEdge(SchedGraphNode*  _src,
77                                SchedGraphNode*  _sink,
78                                const Value*     _val,
79                                unsigned int     _depOrderType,
80                                int              _minDelay)
81   : src(_src),
82     sink(_sink),
83     depType(ValueDep),
84     depOrderType(_depOrderType),
85     minDelay((_minDelay >= 0)? _minDelay : _src->getLatency()),
86     val(_val)
87 {
88   assert(src != sink && "Self-loop in scheduling graph!");
89   src->addOutEdge(this);
90   sink->addInEdge(this);
91 }
92
93
94 /*ctor*/
95 SchedGraphEdge::SchedGraphEdge(SchedGraphNode*  _src,
96                                SchedGraphNode*  _sink,
97                                unsigned int     _regNum,
98                                unsigned int     _depOrderType,
99                                int             _minDelay)
100   : src(_src),
101     sink(_sink),
102     depType(MachineRegister),
103     depOrderType(_depOrderType),
104     minDelay((_minDelay >= 0)? _minDelay : _src->getLatency()),
105     machineRegNum(_regNum)
106 {
107   assert(src != sink && "Self-loop in scheduling graph!");
108   src->addOutEdge(this);
109   sink->addInEdge(this);
110 }
111
112
113 /*ctor*/
114 SchedGraphEdge::SchedGraphEdge(SchedGraphNode* _src,
115                                SchedGraphNode* _sink,
116                                ResourceId      _resourceId,
117                                int             _minDelay)
118   : src(_src),
119     sink(_sink),
120     depType(MachineResource),
121     depOrderType(NonDataDep),
122     minDelay((_minDelay >= 0)? _minDelay : _src->getLatency()),
123     resourceId(_resourceId)
124 {
125   assert(src != sink && "Self-loop in scheduling graph!");
126   src->addOutEdge(this);
127   sink->addInEdge(this);
128 }
129
130 /*dtor*/
131 SchedGraphEdge::~SchedGraphEdge()
132 {
133 }
134
135 void SchedGraphEdge::dump(int indent=0) const {
136   cerr << std::string(indent*2, ' ') << *this; 
137 }
138
139
140 // 
141 // class SchedGraphNode
142 // 
143
144 /*ctor*/
145 SchedGraphNode::SchedGraphNode(unsigned int _nodeId,
146                                const BasicBlock*   _bb,
147                                const MachineInstr* _minstr,
148                                int   indexInBB,
149                                const TargetMachine& target)
150   : nodeId(_nodeId),
151     bb(_bb),
152     minstr(_minstr),
153     origIndexInBB(indexInBB),
154     latency(0)
155 {
156   if (minstr)
157     {
158       MachineOpCode mopCode = minstr->getOpCode();
159       latency = target.getInstrInfo().hasResultInterlock(mopCode)
160         ? target.getInstrInfo().minLatency(mopCode)
161         : target.getInstrInfo().maxLatency(mopCode);
162     }
163 }
164
165
166 /*dtor*/
167 SchedGraphNode::~SchedGraphNode()
168 {
169   // for each node, delete its out-edges
170   std::for_each(beginOutEdges(), endOutEdges(),
171                 deleter<SchedGraphEdge>);
172 }
173
174 void SchedGraphNode::dump(int indent=0) const {
175   cerr << std::string(indent*2, ' ') << *this; 
176 }
177
178
179 inline void
180 SchedGraphNode::addInEdge(SchedGraphEdge* edge)
181 {
182   inEdges.push_back(edge);
183 }
184
185
186 inline void
187 SchedGraphNode::addOutEdge(SchedGraphEdge* edge)
188 {
189   outEdges.push_back(edge);
190 }
191
192 inline void
193 SchedGraphNode::removeInEdge(const SchedGraphEdge* edge)
194 {
195   assert(edge->getSink() == this);
196   
197   for (iterator I = beginInEdges(); I != endInEdges(); ++I)
198     if ((*I) == edge)
199       {
200         inEdges.erase(I);
201         break;
202       }
203 }
204
205 inline void
206 SchedGraphNode::removeOutEdge(const SchedGraphEdge* edge)
207 {
208   assert(edge->getSrc() == this);
209   
210   for (iterator I = beginOutEdges(); I != endOutEdges(); ++I)
211     if ((*I) == edge)
212       {
213         outEdges.erase(I);
214         break;
215       }
216 }
217
218
219 // 
220 // class SchedGraph
221 // 
222
223
224 /*ctor*/
225 SchedGraph::SchedGraph(const BasicBlock* bb,
226                        const TargetMachine& target)
227 {
228   bbVec.push_back(bb);
229   buildGraph(target);
230 }
231
232
233 /*dtor*/
234 SchedGraph::~SchedGraph()
235 {
236   for (const_iterator I = begin(); I != end(); ++I)
237     delete I->second;
238   delete graphRoot;
239   delete graphLeaf;
240 }
241
242
243 void
244 SchedGraph::dump() const
245 {
246   cerr << "  Sched Graph for Basic Blocks: ";
247   for (unsigned i=0, N=bbVec.size(); i < N; i++)
248     {
249       cerr << (bbVec[i]->hasName()? bbVec[i]->getName() : "block")
250            << " (" << bbVec[i] << ")"
251            << ((i == N-1)? "" : ", ");
252     }
253   
254   cerr << "\n\n    Actual Root nodes : ";
255   for (unsigned i=0, N=graphRoot->outEdges.size(); i < N; i++)
256     cerr << graphRoot->outEdges[i]->getSink()->getNodeId()
257          << ((i == N-1)? "" : ", ");
258   
259   cerr << "\n    Graph Nodes:\n";
260   for (const_iterator I=begin(); I != end(); ++I)
261     cerr << "\n" << *I->second;
262   
263   cerr << "\n";
264 }
265
266
267 void
268 SchedGraph::eraseIncomingEdges(SchedGraphNode* node, bool addDummyEdges)
269 {
270   // Delete and disconnect all in-edges for the node
271   for (SchedGraphNode::iterator I = node->beginInEdges();
272        I != node->endInEdges(); ++I)
273     {
274       SchedGraphNode* srcNode = (*I)->getSrc();
275       srcNode->removeOutEdge(*I);
276       delete *I;
277       
278       if (addDummyEdges &&
279           srcNode != getRoot() &&
280           srcNode->beginOutEdges() == srcNode->endOutEdges())
281         { // srcNode has no more out edges, so add an edge to dummy EXIT node
282           assert(node != getLeaf() && "Adding edge that was just removed?");
283           (void) new SchedGraphEdge(srcNode, getLeaf(),
284                     SchedGraphEdge::CtrlDep, SchedGraphEdge::NonDataDep, 0);
285         }
286     }
287   
288   node->inEdges.clear();
289 }
290
291 void
292 SchedGraph::eraseOutgoingEdges(SchedGraphNode* node, bool addDummyEdges)
293 {
294   // Delete and disconnect all out-edges for the node
295   for (SchedGraphNode::iterator I = node->beginOutEdges();
296        I != node->endOutEdges(); ++I)
297     {
298       SchedGraphNode* sinkNode = (*I)->getSink();
299       sinkNode->removeInEdge(*I);
300       delete *I;
301       
302       if (addDummyEdges &&
303           sinkNode != getLeaf() &&
304           sinkNode->beginInEdges() == sinkNode->endInEdges())
305         { //sinkNode has no more in edges, so add an edge from dummy ENTRY node
306           assert(node != getRoot() && "Adding edge that was just removed?");
307           (void) new SchedGraphEdge(getRoot(), sinkNode,
308                     SchedGraphEdge::CtrlDep, SchedGraphEdge::NonDataDep, 0);
309         }
310     }
311   
312   node->outEdges.clear();
313 }
314
315 void
316 SchedGraph::eraseIncidentEdges(SchedGraphNode* node, bool addDummyEdges)
317 {
318   this->eraseIncomingEdges(node, addDummyEdges);        
319   this->eraseOutgoingEdges(node, addDummyEdges);        
320 }
321
322
323 void
324 SchedGraph::addDummyEdges()
325 {
326   assert(graphRoot->outEdges.size() == 0);
327   
328   for (const_iterator I=begin(); I != end(); ++I)
329     {
330       SchedGraphNode* node = (*I).second;
331       assert(node != graphRoot && node != graphLeaf);
332       if (node->beginInEdges() == node->endInEdges())
333         (void) new SchedGraphEdge(graphRoot, node, SchedGraphEdge::CtrlDep,
334                                   SchedGraphEdge::NonDataDep, 0);
335       if (node->beginOutEdges() == node->endOutEdges())
336         (void) new SchedGraphEdge(node, graphLeaf, SchedGraphEdge::CtrlDep,
337                                   SchedGraphEdge::NonDataDep, 0);
338     }
339 }
340
341
342 void
343 SchedGraph::addCDEdges(const TerminatorInst* term,
344                        const TargetMachine& target)
345 {
346   const MachineInstrInfo& mii = target.getInstrInfo();
347   MachineCodeForInstruction &termMvec = MachineCodeForInstruction::get(term);
348   
349   // Find the first branch instr in the sequence of machine instrs for term
350   // 
351   unsigned first = 0;
352   while (!mii.isBranch(termMvec[first]->getOpCode()))
353     ++first;
354   assert(first < termMvec.size() &&
355          "No branch instructions for BR?  Ok, but weird!  Delete assertion.");
356   if (first == termMvec.size())
357     return;
358   
359   SchedGraphNode* firstBrNode = this->getGraphNodeForInstr(termMvec[first]);
360   
361   // Add CD edges from each instruction in the sequence to the
362   // *last preceding* branch instr. in the sequence 
363   // Use a latency of 0 because we only need to prevent out-of-order issue.
364   // 
365   for (int i = (int) termMvec.size()-1; i > (int) first; i--) 
366     {
367       SchedGraphNode* toNode = this->getGraphNodeForInstr(termMvec[i]);
368       assert(toNode && "No node for instr generated for branch?");
369       
370       for (int j = i-1; j >= 0; j--) 
371         if (mii.isBranch(termMvec[j]->getOpCode()))
372           {
373             SchedGraphNode* brNode = this->getGraphNodeForInstr(termMvec[j]);
374             assert(brNode && "No node for instr generated for branch?");
375             (void) new SchedGraphEdge(brNode, toNode, SchedGraphEdge::CtrlDep,
376                                       SchedGraphEdge::NonDataDep, 0);
377             break;                      // only one incoming edge is enough
378           }
379     }
380   
381   // Add CD edges from each instruction preceding the first branch
382   // to the first branch.  Use a latency of 0 as above.
383   // 
384   for (int i = first-1; i >= 0; i--) 
385     {
386       SchedGraphNode* fromNode = this->getGraphNodeForInstr(termMvec[i]);
387       assert(fromNode && "No node for instr generated for branch?");
388       (void) new SchedGraphEdge(fromNode, firstBrNode, SchedGraphEdge::CtrlDep,
389                                 SchedGraphEdge::NonDataDep, 0);
390     }
391   
392   // Now add CD edges to the first branch instruction in the sequence from
393   // all preceding instructions in the basic block.  Use 0 latency again.
394   // 
395   const BasicBlock* bb = firstBrNode->getBB();
396   const MachineCodeForBasicBlock& mvec = bb->getMachineInstrVec();
397   for (unsigned i=0, N=mvec.size(); i < N; i++) 
398     {
399       if (mvec[i] == termMvec[first]) // reached the first branch
400         break;
401       
402       SchedGraphNode* fromNode = this->getGraphNodeForInstr(mvec[i]);
403       if (fromNode == NULL)
404         continue;                       // dummy instruction, e.g., PHI
405       
406       (void) new SchedGraphEdge(fromNode, firstBrNode,
407                                 SchedGraphEdge::CtrlDep,
408                                 SchedGraphEdge::NonDataDep, 0);
409       
410       // If we find any other machine instructions (other than due to
411       // the terminator) that also have delay slots, add an outgoing edge
412       // from the instruction to the instructions in the delay slots.
413       // 
414       unsigned d = mii.getNumDelaySlots(mvec[i]->getOpCode());
415       assert(i+d < N && "Insufficient delay slots for instruction?");
416       
417       for (unsigned j=1; j <= d; j++)
418         {
419           SchedGraphNode* toNode = this->getGraphNodeForInstr(mvec[i+j]);
420           assert(toNode && "No node for machine instr in delay slot?");
421           (void) new SchedGraphEdge(fromNode, toNode,
422                                     SchedGraphEdge::CtrlDep,
423                                     SchedGraphEdge::NonDataDep, 0);
424         }
425     }
426 }
427
428 static const int SG_LOAD_REF  = 0;
429 static const int SG_STORE_REF = 1;
430 static const int SG_CALL_REF  = 2;
431
432 static const unsigned int SG_DepOrderArray[][3] = {
433   { SchedGraphEdge::NonDataDep,
434             SchedGraphEdge::AntiDep,
435                         SchedGraphEdge::AntiDep },
436   { SchedGraphEdge::TrueDep,
437             SchedGraphEdge::OutputDep,
438                         SchedGraphEdge::TrueDep | SchedGraphEdge::OutputDep },
439   { SchedGraphEdge::TrueDep,
440             SchedGraphEdge::AntiDep | SchedGraphEdge::OutputDep,
441                         SchedGraphEdge::TrueDep | SchedGraphEdge::AntiDep
442                                                 | SchedGraphEdge::OutputDep }
443 };
444
445
446 // Add a dependence edge between every pair of machine load/store/call
447 // instructions, where at least one is a store or a call.
448 // Use latency 1 just to ensure that memory operations are ordered;
449 // latency does not otherwise matter (true dependences enforce that).
450 // 
451 void
452 SchedGraph::addMemEdges(const vector<SchedGraphNode*>& memNodeVec,
453                         const TargetMachine& target)
454 {
455   const MachineInstrInfo& mii = target.getInstrInfo();
456   
457   // Instructions in memNodeVec are in execution order within the basic block,
458   // so simply look at all pairs <memNodeVec[i], memNodeVec[j: j > i]>.
459   // 
460   for (unsigned im=0, NM=memNodeVec.size(); im < NM; im++)
461     {
462       MachineOpCode fromOpCode = memNodeVec[im]->getOpCode();
463       int fromType = mii.isCall(fromOpCode)? SG_CALL_REF
464                        : mii.isLoad(fromOpCode)? SG_LOAD_REF
465                                                : SG_STORE_REF;
466       for (unsigned jm=im+1; jm < NM; jm++)
467         {
468           MachineOpCode toOpCode = memNodeVec[jm]->getOpCode();
469           int toType = mii.isCall(toOpCode)? SG_CALL_REF
470                          : mii.isLoad(toOpCode)? SG_LOAD_REF
471                                                : SG_STORE_REF;
472           
473           if (fromType != SG_LOAD_REF || toType != SG_LOAD_REF)
474             (void) new SchedGraphEdge(memNodeVec[im], memNodeVec[jm],
475                                       SchedGraphEdge::MemoryDep,
476                                       SG_DepOrderArray[fromType][toType], 1);
477         }
478     }
479
480
481 // Add edges from/to CC reg instrs to/from call instrs.
482 // Essentially this prevents anything that sets or uses a CC reg from being
483 // reordered w.r.t. a call.
484 // Use a latency of 0 because we only need to prevent out-of-order issue,
485 // like with control dependences.
486 // 
487 void
488 SchedGraph::addCallCCEdges(const vector<SchedGraphNode*>& memNodeVec,
489                            MachineCodeForBasicBlock& bbMvec,
490                            const TargetMachine& target)
491 {
492   const MachineInstrInfo& mii = target.getInstrInfo();
493   vector<SchedGraphNode*> callNodeVec;
494   
495   // Find the call instruction nodes and put them in a vector.
496   for (unsigned im=0, NM=memNodeVec.size(); im < NM; im++)
497     if (mii.isCall(memNodeVec[im]->getOpCode()))
498       callNodeVec.push_back(memNodeVec[im]);
499   
500   // Now walk the entire basic block, looking for CC instructions *and*
501   // call instructions, and keep track of the order of the instructions.
502   // Use the call node vec to quickly find earlier and later call nodes
503   // relative to the current CC instruction.
504   // 
505   int lastCallNodeIdx = -1;
506   for (unsigned i=0, N=bbMvec.size(); i < N; i++)
507     if (mii.isCall(bbMvec[i]->getOpCode()))
508       {
509         ++lastCallNodeIdx;
510         for ( ; lastCallNodeIdx < (int)callNodeVec.size(); ++lastCallNodeIdx)
511           if (callNodeVec[lastCallNodeIdx]->getMachineInstr() == bbMvec[i])
512             break;
513         assert(lastCallNodeIdx < (int)callNodeVec.size() && "Missed Call?");
514       }
515     else if (mii.isCCInstr(bbMvec[i]->getOpCode()))
516       { // Add incoming/outgoing edges from/to preceding/later calls
517         SchedGraphNode* ccNode = this->getGraphNodeForInstr(bbMvec[i]);
518         int j=0;
519         for ( ; j <= lastCallNodeIdx; j++)
520           (void) new SchedGraphEdge(callNodeVec[j], ccNode,
521                                     MachineCCRegsRID, 0);
522         for ( ; j < (int) callNodeVec.size(); j++)
523           (void) new SchedGraphEdge(ccNode, callNodeVec[j],
524                                     MachineCCRegsRID, 0);
525       }
526 }
527
528
529 void
530 SchedGraph::addMachineRegEdges(RegToRefVecMap& regToRefVecMap,
531                                const TargetMachine& target)
532 {
533   assert(bbVec.size() == 1 && "Only handling a single basic block here");
534   
535   // This assumes that such hardwired registers are never allocated
536   // to any LLVM value (since register allocation happens later), i.e.,
537   // any uses or defs of this register have been made explicit!
538   // Also assumes that two registers with different numbers are
539   // not aliased!
540   // 
541   for (RegToRefVecMap::iterator I = regToRefVecMap.begin();
542        I != regToRefVecMap.end(); ++I)
543     {
544       int regNum        = (*I).first;
545       RefVec& regRefVec = (*I).second;
546       
547       // regRefVec is ordered by control flow order in the basic block
548       for (unsigned i=0; i < regRefVec.size(); ++i)
549         {
550           SchedGraphNode* node = regRefVec[i].first;
551           unsigned int opNum   = regRefVec[i].second;
552           bool isDef = node->getMachineInstr()->operandIsDefined(opNum);
553                 
554           for (unsigned p=0; p < i; ++p)
555             {
556               SchedGraphNode* prevNode = regRefVec[p].first;
557               if (prevNode != node)
558                 {
559                   unsigned int prevOpNum = regRefVec[p].second;
560                   bool prevIsDef =
561                     prevNode->getMachineInstr()->operandIsDefined(prevOpNum);
562                   
563                   if (isDef)
564                     new SchedGraphEdge(prevNode, node, regNum,
565                                        (prevIsDef)? SchedGraphEdge::OutputDep
566                                                   : SchedGraphEdge::AntiDep);
567                   else if (prevIsDef)
568                     new SchedGraphEdge(prevNode, node, regNum,
569                                        SchedGraphEdge::TrueDep);
570                 }
571             }
572         }
573     }
574 }
575
576
577 void
578 SchedGraph::addEdgesForValue(SchedGraphNode* refNode,
579                              const RefVec& defVec,
580                              const Value* defValue,
581                              bool  refNodeIsDef,
582                              const TargetMachine& target)
583 {
584   // Add true or output dep edges from all def nodes before refNode in BB.
585   // Add anti or output dep edges to all def nodes after refNode.
586   for (RefVec::const_iterator I=defVec.begin(), E=defVec.end(); I != E; ++I)
587     {
588       if ((*I).first == refNode)
589         continue;                       // Dont add any self-loops
590       
591       if ((*I).first->getOrigIndexInBB() < refNode->getOrigIndexInBB())
592         // (*).first is before refNode
593         (void) new SchedGraphEdge((*I).first, refNode, defValue,
594                                   (refNodeIsDef)? SchedGraphEdge::OutputDep
595                                                 : SchedGraphEdge::TrueDep);
596       else
597         // (*).first is after refNode
598         (void) new SchedGraphEdge(refNode, (*I).first, defValue,
599                                   (refNodeIsDef)? SchedGraphEdge::OutputDep
600                                                 : SchedGraphEdge::AntiDep);
601     }
602 }
603
604
605 void
606 SchedGraph::addEdgesForInstruction(const MachineInstr& minstr,
607                                    const ValueToDefVecMap& valueToDefVecMap,
608                                    const TargetMachine& target)
609 {
610   SchedGraphNode* node = this->getGraphNodeForInstr(&minstr);
611   if (node == NULL)
612     return;
613   
614   // Add edges for all operands of the machine instruction.
615   // 
616   for (unsigned i=0, numOps=minstr.getNumOperands(); i < numOps; i++)
617     {
618       const MachineOperand& mop = minstr.getOperand(i);
619       switch(mop.getOperandType())
620         {
621         case MachineOperand::MO_VirtualRegister:
622         case MachineOperand::MO_CCRegister:
623           if (const Instruction* srcI =
624               dyn_cast_or_null<Instruction>(mop.getVRegValue()))
625             {
626               ValueToDefVecMap::const_iterator I = valueToDefVecMap.find(srcI);
627               if (I != valueToDefVecMap.end())
628                 addEdgesForValue(node, (*I).second, mop.getVRegValue(),
629                                  minstr.operandIsDefined(i), target);
630             }
631           break;
632           
633         case MachineOperand::MO_MachineRegister:
634           break; 
635           
636         case MachineOperand::MO_SignExtendedImmed:
637         case MachineOperand::MO_UnextendedImmed:
638         case MachineOperand::MO_PCRelativeDisp:
639           break;        // nothing to do for immediate fields
640           
641         default:
642           assert(0 && "Unknown machine operand type in SchedGraph builder");
643           break;
644         }
645     }
646   
647   // Add edges for values implicitly used by the machine instruction.
648   // Examples include function arguments to a Call instructions or the return
649   // value of a Ret instruction.
650   // 
651   for (unsigned i=0, N=minstr.getNumImplicitRefs(); i < N; ++i)
652     if (! minstr.implicitRefIsDefined(i))
653       if (const Instruction* srcI =
654           dyn_cast_or_null<Instruction>(minstr.getImplicitRef(i)))
655         {
656           ValueToDefVecMap::const_iterator I = valueToDefVecMap.find(srcI);
657           if (I != valueToDefVecMap.end())
658             addEdgesForValue(node, (*I).second, minstr.getImplicitRef(i),
659                              minstr.implicitRefIsDefined(i), target);
660         }
661 }
662
663
664 #undef NEED_SEPARATE_NONSSA_EDGES_CODE
665 #ifdef NEED_SEPARATE_NONSSA_EDGES_CODE
666 void
667 SchedGraph::addNonSSAEdgesForValue(const Instruction* instr,
668                                    const TargetMachine& target)
669 {
670   if (isa<PHINode>(instr))
671     return;
672   
673   MachineCodeForVMInstr& mvec = instr->getMachineInstrVec();
674   const MachineInstrInfo& mii = target.getInstrInfo();
675   RefVec refVec;
676   
677   for (unsigned i=0, N=mvec.size(); i < N; i++)
678     for (int o=0, N = mii.getNumOperands(mvec[i]->getOpCode()); o < N; o++)
679       {
680         const MachineOperand& mop = mvec[i]->getOperand(o); 
681         
682         if ((mop.getOperandType() == MachineOperand::MO_VirtualRegister ||
683              mop.getOperandType() == MachineOperand::MO_CCRegister)
684             && mop.getVRegValue() == (Value*) instr)
685           {
686             // this operand is a definition or use of value `instr'
687             SchedGraphNode* node = this->getGraphNodeForInstr(mvec[i]);
688             assert(node && "No node for machine instruction in this BB?");
689             refVec.push_back(std::make_pair(node, o));
690           }
691       }
692   
693   // refVec is ordered by control flow order of the machine instructions
694   for (unsigned i=0; i < refVec.size(); ++i)
695     {
696       SchedGraphNode* node = refVec[i].first;
697       unsigned int   opNum = refVec[i].second;
698       bool isDef = node->getMachineInstr()->operandIsDefined(opNum);
699       
700       if (isDef)
701         // add output and/or anti deps to this definition
702         for (unsigned p=0; p < i; ++p)
703           {
704             SchedGraphNode* prevNode = refVec[p].first;
705             if (prevNode != node)
706               {
707                 bool prevIsDef = prevNode->getMachineInstr()->
708                   operandIsDefined(refVec[p].second);
709                 new SchedGraphEdge(prevNode, node, SchedGraphEdge::ValueDep,
710                                    (prevIsDef)? SchedGraphEdge::OutputDep
711                                               : SchedGraphEdge::AntiDep);
712               }
713           }
714     }
715 }
716 #endif //NEED_SEPARATE_NONSSA_EDGES_CODE
717
718
719 void
720 SchedGraph::findDefUseInfoAtInstr(const TargetMachine& target,
721                                   SchedGraphNode* node,
722                                   vector<SchedGraphNode*>& memNodeVec,
723                                   RegToRefVecMap& regToRefVecMap,
724                                   ValueToDefVecMap& valueToDefVecMap)
725 {
726   const MachineInstrInfo& mii = target.getInstrInfo();
727   
728   
729   MachineOpCode opCode = node->getOpCode();
730   if (mii.isLoad(opCode) || mii.isStore(opCode) || mii.isCall(opCode))
731     memNodeVec.push_back(node);
732   
733   // Collect the register references and value defs. for explicit operands
734   // 
735   const MachineInstr& minstr = * node->getMachineInstr();
736   for (int i=0, numOps = (int) minstr.getNumOperands(); i < numOps; i++)
737     {
738       const MachineOperand& mop = minstr.getOperand(i);
739       
740       // if this references a register other than the hardwired
741       // "zero" register, record the reference.
742       if (mop.getOperandType() == MachineOperand::MO_MachineRegister)
743         {
744           int regNum = mop.getMachineRegNum();
745           if (regNum != target.getRegInfo().getZeroRegNum())
746             regToRefVecMap[mop.getMachineRegNum()].push_back(
747                                                   std::make_pair(node, i));
748           continue;                     // nothing more to do
749         }
750       
751       // ignore all other non-def operands
752       if (! minstr.operandIsDefined(i))
753         continue;
754       
755       // We must be defining a value.
756       assert((mop.getOperandType() == MachineOperand::MO_VirtualRegister ||
757               mop.getOperandType() == MachineOperand::MO_CCRegister)
758              && "Do not expect any other kind of operand to be defined!");
759       
760       const Instruction* defInstr = cast<Instruction>(mop.getVRegValue());
761       valueToDefVecMap[defInstr].push_back(std::make_pair(node, i)); 
762     }
763   
764   // 
765   // Collect value defs. for implicit operands.  The interface to extract
766   // them assumes they must be virtual registers!
767   // 
768   for (int i=0, N = (int) minstr.getNumImplicitRefs(); i < N; ++i)
769     if (minstr.implicitRefIsDefined(i))
770       if (const Instruction* defInstr =
771           dyn_cast_or_null<Instruction>(minstr.getImplicitRef(i)))
772         {
773           valueToDefVecMap[defInstr].push_back(std::make_pair(node, -i)); 
774         }
775 }
776
777
778 void
779 SchedGraph::buildNodesforBB(const TargetMachine& target,
780                             const BasicBlock* bb,
781                             vector<SchedGraphNode*>& memNodeVec,
782                             RegToRefVecMap& regToRefVecMap,
783                             ValueToDefVecMap& valueToDefVecMap)
784 {
785   const MachineInstrInfo& mii = target.getInstrInfo();
786   
787   // Build graph nodes for each VM instruction and gather def/use info.
788   // Do both those together in a single pass over all machine instructions.
789   const MachineCodeForBasicBlock& mvec = bb->getMachineInstrVec();
790   for (unsigned i=0; i < mvec.size(); i++)
791     if (! mii.isDummyPhiInstr(mvec[i]->getOpCode()))
792       {
793         SchedGraphNode* node = new SchedGraphNode(getNumNodes(), bb,
794                                                   mvec[i], i, target);
795         this->noteGraphNodeForInstr(mvec[i], node);
796         
797         // Remember all register references and value defs
798         findDefUseInfoAtInstr(target, node,
799                               memNodeVec, regToRefVecMap,valueToDefVecMap);
800       }
801   
802 #undef REALLY_NEED_TO_SEARCH_SUCCESSOR_PHIS
803 #ifdef REALLY_NEED_TO_SEARCH_SUCCESSOR_PHIS
804   // This is a BIG UGLY HACK.  IT NEEDS TO BE ELIMINATED.
805   // Look for copy instructions inserted in this BB due to Phi instructions
806   // in the successor BBs.
807   // There MUST be exactly one copy per Phi in successor nodes.
808   // 
809   for (BasicBlock::succ_const_iterator SI=bb->succ_begin(), SE=bb->succ_end();
810        SI != SE; ++SI)
811     for (BasicBlock::const_iterator PI=(*SI)->begin(), PE=(*SI)->end();
812          PI != PE; ++PI)
813       {
814         if ((*PI)->getOpcode() != Instruction::PHINode)
815           break;                        // No more Phis in this successor
816         
817         // Find the incoming value from block bb to block (*SI)
818         int bbIndex = cast<PHINode>(*PI)->getBasicBlockIndex(bb);
819         assert(bbIndex >= 0 && "But I know bb is a predecessor of (*SI)?");
820         Value* inVal = cast<PHINode>(*PI)->getIncomingValue(bbIndex);
821         assert(inVal != NULL && "There must be an in-value on every edge");
822         
823         // Find the machine instruction that makes a copy of inval to (*PI).
824         // This must be in the current basic block (bb).
825         const MachineCodeForVMInstr& mvec = (*PI)->getMachineInstrVec();
826         const MachineInstr* theCopy = NULL;
827         for (unsigned i=0; i < mvec.size() && theCopy == NULL; i++)
828           if (! mii.isDummyPhiInstr(mvec[i]->getOpCode()))
829             // not a Phi: assume this is a copy and examine its operands
830             for (int o=0, N=(int) mvec[i]->getNumOperands(); o < N; o++)
831               {
832                 const MachineOperand& mop = mvec[i]->getOperand(o);
833                 if (mvec[i]->operandIsDefined(o))
834                   assert(mop.getVRegValue() == (*PI) && "dest shd be my Phi");
835                 else if (mop.getVRegValue() == inVal)
836                   { // found the copy!
837                     theCopy = mvec[i];
838                     break;
839                   }
840               }
841         
842         // Found the dang instruction.  Now create a node and do the rest...
843         if (theCopy != NULL)
844           {
845             SchedGraphNode* node = new SchedGraphNode(getNumNodes(), bb,
846                                             theCopy, origIndexInBB++, target);
847             this->noteGraphNodeForInstr(theCopy, node);
848             findDefUseInfoAtInstr(target, node,
849                                   memNodeVec, regToRefVecMap,valueToDefVecMap);
850           }
851       }
852 #endif  //REALLY_NEED_TO_SEARCH_SUCCESSOR_PHIS
853 }
854
855
856 void
857 SchedGraph::buildGraph(const TargetMachine& target)
858 {
859   const BasicBlock* bb = bbVec[0];
860   
861   assert(bbVec.size() == 1 && "Only handling a single basic block here");
862   
863   // Use this data structure to note all machine operands that compute
864   // ordinary LLVM values.  These must be computed defs (i.e., instructions). 
865   // Note that there may be multiple machine instructions that define
866   // each Value.
867   ValueToDefVecMap valueToDefVecMap;
868   
869   // Use this data structure to note all memory instructions.
870   // We use this to add memory dependence edges without a second full walk.
871   // 
872   // vector<const Instruction*> memVec;
873   vector<SchedGraphNode*> memNodeVec;
874   
875   // Use this data structure to note any uses or definitions of
876   // machine registers so we can add edges for those later without
877   // extra passes over the nodes.
878   // The vector holds an ordered list of references to the machine reg,
879   // ordered according to control-flow order.  This only works for a
880   // single basic block, hence the assertion.  Each reference is identified
881   // by the pair: <node, operand-number>.
882   // 
883   RegToRefVecMap regToRefVecMap;
884   
885   // Make a dummy root node.  We'll add edges to the real roots later.
886   graphRoot = new SchedGraphNode(0, NULL, NULL, -1, target);
887   graphLeaf = new SchedGraphNode(1, NULL, NULL, -1, target);
888
889   //----------------------------------------------------------------
890   // First add nodes for all the machine instructions in the basic block
891   // because this greatly simplifies identifying which edges to add.
892   // Do this one VM instruction at a time since the SchedGraphNode needs that.
893   // Also, remember the load/store instructions to add memory deps later.
894   //----------------------------------------------------------------
895   
896   buildNodesforBB(target, bb, memNodeVec, regToRefVecMap, valueToDefVecMap);
897   
898   //----------------------------------------------------------------
899   // Now add edges for the following (all are incoming edges except (4)):
900   // (1) operands of the machine instruction, including hidden operands
901   // (2) machine register dependences
902   // (3) memory load/store dependences
903   // (3) other resource dependences for the machine instruction, if any
904   // (4) output dependences when multiple machine instructions define the
905   //     same value; all must have been generated from a single VM instrn
906   // (5) control dependences to branch instructions generated for the
907   //     terminator instruction of the BB. Because of delay slots and
908   //     2-way conditional branches, multiple CD edges are needed
909   //     (see addCDEdges for details).
910   // Also, note any uses or defs of machine registers.
911   // 
912   //----------------------------------------------------------------
913       
914   MachineCodeForBasicBlock& bbMvec = bb->getMachineInstrVec();
915   
916   // First, add edges to the terminator instruction of the basic block.
917   this->addCDEdges(bb->getTerminator(), target);
918       
919   // Then add memory dep edges: store->load, load->store, and store->store.
920   // Call instructions are treated as both load and store.
921   this->addMemEdges(memNodeVec, target);
922
923   // Then add edges between call instructions and CC set/use instructions
924   this->addCallCCEdges(memNodeVec, bbMvec, target);
925   
926   // Then add incoming def-use (SSA) edges for each machine instruction.
927   for (unsigned i=0, N=bbMvec.size(); i < N; i++)
928     addEdgesForInstruction(*bbMvec[i], valueToDefVecMap, target);
929   
930 #ifdef NEED_SEPARATE_NONSSA_EDGES_CODE
931   // Then add non-SSA edges for all VM instructions in the block.
932   // We assume that all machine instructions that define a value are
933   // generated from the VM instruction corresponding to that value.
934   // TODO: This could probably be done much more efficiently.
935   for (BasicBlock::const_iterator II = bb->begin(); II != bb->end(); ++II)
936     this->addNonSSAEdgesForValue(*II, target);
937 #endif //NEED_SEPARATE_NONSSA_EDGES_CODE
938   
939   // Then add edges for dependences on machine registers
940   this->addMachineRegEdges(regToRefVecMap, target);
941   
942   // Finally, add edges from the dummy root and to dummy leaf
943   this->addDummyEdges();                
944 }
945
946
947 // 
948 // class SchedGraphSet
949 // 
950
951 /*ctor*/
952 SchedGraphSet::SchedGraphSet(const Function* _function,
953                              const TargetMachine& target) :
954   method(_function)
955 {
956   buildGraphsForMethod(method, target);
957 }
958
959
960 /*dtor*/
961 SchedGraphSet::~SchedGraphSet()
962 {
963   // delete all the graphs
964   for(iterator I = begin(), E = end(); I != E; ++I)
965     delete *I;  // destructor is a friend
966 }
967
968
969 void
970 SchedGraphSet::dump() const
971 {
972   cerr << "======== Sched graphs for function `" << method->getName()
973        << "' ========\n\n";
974   
975   for (const_iterator I=begin(); I != end(); ++I)
976     (*I)->dump();
977   
978   cerr << "\n====== End graphs for function `" << method->getName()
979        << "' ========\n\n";
980 }
981
982
983 void
984 SchedGraphSet::buildGraphsForMethod(const Function *F,
985                                     const TargetMachine& target)
986 {
987   for (Function::const_iterator BI = F->begin(); BI != F->end(); ++BI)
988     addGraph(new SchedGraph(BI, target));
989 }
990
991
992 std::ostream &operator<<(std::ostream &os, const SchedGraphEdge& edge)
993 {
994   os << "edge [" << edge.src->getNodeId() << "] -> ["
995      << edge.sink->getNodeId() << "] : ";
996   
997   switch(edge.depType) {
998   case SchedGraphEdge::CtrlDep:         os<< "Control Dep"; break;
999   case SchedGraphEdge::ValueDep:        os<< "Reg Value " << edge.val; break;
1000   case SchedGraphEdge::MemoryDep:       os<< "Memory Dep"; break;
1001   case SchedGraphEdge::MachineRegister: os<< "Reg " <<edge.machineRegNum;break;
1002   case SchedGraphEdge::MachineResource: os<<"Resource "<<edge.resourceId;break;
1003   default: assert(0); break;
1004   }
1005   
1006   os << " : delay = " << edge.minDelay << "\n";
1007   
1008   return os;
1009 }
1010
1011 std::ostream &operator<<(std::ostream &os, const SchedGraphNode& node)
1012 {
1013   os << std::string(8, ' ')
1014      << "Node " << node.nodeId << " : "
1015      << "latency = " << node.latency << "\n" << std::string(12, ' ');
1016   
1017   if (node.getMachineInstr() == NULL)
1018     os << "(Dummy node)\n";
1019   else
1020     {
1021       os << *node.getMachineInstr() << "\n" << std::string(12, ' ');
1022       os << node.inEdges.size() << " Incoming Edges:\n";
1023       for (unsigned i=0, N=node.inEdges.size(); i < N; i++)
1024           os << std::string(16, ' ') << *node.inEdges[i];
1025   
1026       os << std::string(12, ' ') << node.outEdges.size()
1027          << " Outgoing Edges:\n";
1028       for (unsigned i=0, N=node.outEdges.size(); i < N; i++)
1029         os << std::string(16, ' ') << *node.outEdges[i];
1030     }
1031   
1032   return os;
1033 }