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