Add #includes now that MachineInstr.h doesn't include llvm/Target/MachineInstrInfo.h
[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& minstr,
627                                    const ValueToDefVecMap& valueToDefVecMap,
628                                    const TargetMachine& target)
629 {
630   SchedGraphNode* node = this->getGraphNodeForInstr(&minstr);
631   if (node == NULL)
632     return;
633   
634   // Add edges for all operands of the machine instruction.
635   // 
636   for (unsigned i=0, numOps=minstr.getNumOperands(); i < numOps; i++)
637     {
638       const MachineOperand& mop = minstr.getOperand(i);
639       switch(mop.getOperandType())
640         {
641         case MachineOperand::MO_VirtualRegister:
642         case MachineOperand::MO_CCRegister:
643           if (const Instruction* srcI =
644               dyn_cast_or_null<Instruction>(mop.getVRegValue()))
645             {
646               ValueToDefVecMap::const_iterator I = valueToDefVecMap.find(srcI);
647               if (I != valueToDefVecMap.end())
648                 addEdgesForValue(node, (*I).second, mop.getVRegValue(),
649                                  minstr.operandIsDefined(i),
650                                  minstr.operandIsDefinedAndUsed(i), target);
651             }
652           break;
653           
654         case MachineOperand::MO_MachineRegister:
655           break; 
656           
657         case MachineOperand::MO_SignExtendedImmed:
658         case MachineOperand::MO_UnextendedImmed:
659         case MachineOperand::MO_PCRelativeDisp:
660           break;        // nothing to do for immediate fields
661           
662         default:
663           assert(0 && "Unknown machine operand type in SchedGraph builder");
664           break;
665         }
666     }
667   
668   // Add edges for values implicitly used by the machine instruction.
669   // Examples include function arguments to a Call instructions or the return
670   // value of a Ret instruction.
671   // 
672   for (unsigned i=0, N=minstr.getNumImplicitRefs(); i < N; ++i)
673     if (! minstr.implicitRefIsDefined(i) ||
674         minstr.implicitRefIsDefinedAndUsed(i))
675       if (const Instruction* srcI =
676           dyn_cast_or_null<Instruction>(minstr.getImplicitRef(i)))
677         {
678           ValueToDefVecMap::const_iterator I = valueToDefVecMap.find(srcI);
679           if (I != valueToDefVecMap.end())
680             addEdgesForValue(node, (*I).second, minstr.getImplicitRef(i),
681                              minstr.implicitRefIsDefined(i),
682                              minstr.implicitRefIsDefinedAndUsed(i), target);
683         }
684 }
685
686
687 void
688 SchedGraph::findDefUseInfoAtInstr(const TargetMachine& target,
689                                   SchedGraphNode* node,
690                                   vector<SchedGraphNode*>& memNodeVec,
691                                   RegToRefVecMap& regToRefVecMap,
692                                   ValueToDefVecMap& valueToDefVecMap)
693 {
694   const MachineInstrInfo& mii = target.getInstrInfo();
695   
696   
697   MachineOpCode opCode = node->getOpCode();
698   if (mii.isLoad(opCode) || mii.isStore(opCode) || mii.isCall(opCode))
699     memNodeVec.push_back(node);
700   
701   // Collect the register references and value defs. for explicit operands
702   // 
703   const MachineInstr& minstr = * node->getMachineInstr();
704   for (int i=0, numOps = (int) minstr.getNumOperands(); i < numOps; i++)
705     {
706       const MachineOperand& mop = minstr.getOperand(i);
707       
708       // if this references a register other than the hardwired
709       // "zero" register, record the reference.
710       if (mop.getOperandType() == MachineOperand::MO_MachineRegister)
711         {
712           int regNum = mop.getMachineRegNum();
713           if (regNum != target.getRegInfo().getZeroRegNum())
714             regToRefVecMap[mop.getMachineRegNum()].push_back(
715                                                   std::make_pair(node, i));
716           continue;                     // nothing more to do
717         }
718       
719       // ignore all other non-def operands
720       if (! minstr.operandIsDefined(i))
721         continue;
722       
723       // We must be defining a value.
724       assert((mop.getOperandType() == MachineOperand::MO_VirtualRegister ||
725               mop.getOperandType() == MachineOperand::MO_CCRegister)
726              && "Do not expect any other kind of operand to be defined!");
727       
728       const Instruction* defInstr = cast<Instruction>(mop.getVRegValue());
729       valueToDefVecMap[defInstr].push_back(std::make_pair(node, i)); 
730     }
731   
732   // 
733   // Collect value defs. for implicit operands.  The interface to extract
734   // them assumes they must be virtual registers!
735   // 
736   for (int i=0, N = (int) minstr.getNumImplicitRefs(); i < N; ++i)
737     if (minstr.implicitRefIsDefined(i))
738       if (const Instruction* defInstr =
739           dyn_cast_or_null<Instruction>(minstr.getImplicitRef(i)))
740         {
741           valueToDefVecMap[defInstr].push_back(std::make_pair(node, -i)); 
742         }
743 }
744
745
746 void
747 SchedGraph::buildNodesforBB(const TargetMachine& target,
748                             const BasicBlock* bb,
749                             vector<SchedGraphNode*>& memNodeVec,
750                             RegToRefVecMap& regToRefVecMap,
751                             ValueToDefVecMap& valueToDefVecMap)
752 {
753   const MachineInstrInfo& mii = target.getInstrInfo();
754   
755   // Build graph nodes for each VM instruction and gather def/use info.
756   // Do both those together in a single pass over all machine instructions.
757   const MachineBasicBlock& mvec = MachineBasicBlock::get(bb);
758   for (unsigned i=0; i < mvec.size(); i++)
759     if (! mii.isDummyPhiInstr(mvec[i]->getOpCode()))
760       {
761         SchedGraphNode* node = new SchedGraphNode(getNumNodes(), bb,
762                                                   mvec[i], i, target);
763         this->noteGraphNodeForInstr(mvec[i], node);
764         
765         // Remember all register references and value defs
766         findDefUseInfoAtInstr(target, node,
767                               memNodeVec, regToRefVecMap,valueToDefVecMap);
768       }
769   
770 #undef REALLY_NEED_TO_SEARCH_SUCCESSOR_PHIS
771 #ifdef REALLY_NEED_TO_SEARCH_SUCCESSOR_PHIS
772   // This is a BIG UGLY HACK.  IT NEEDS TO BE ELIMINATED.
773   // Look for copy instructions inserted in this BB due to Phi instructions
774   // in the successor BBs.
775   // There MUST be exactly one copy per Phi in successor nodes.
776   // 
777   for (BasicBlock::succ_const_iterator SI=bb->succ_begin(), SE=bb->succ_end();
778        SI != SE; ++SI)
779     for (BasicBlock::const_iterator PI=(*SI)->begin(), PE=(*SI)->end();
780          PI != PE; ++PI)
781       {
782         if ((*PI)->getOpcode() != Instruction::PHINode)
783           break;                        // No more Phis in this successor
784         
785         // Find the incoming value from block bb to block (*SI)
786         int bbIndex = cast<PHINode>(*PI)->getBasicBlockIndex(bb);
787         assert(bbIndex >= 0 && "But I know bb is a predecessor of (*SI)?");
788         Value* inVal = cast<PHINode>(*PI)->getIncomingValue(bbIndex);
789         assert(inVal != NULL && "There must be an in-value on every edge");
790         
791         // Find the machine instruction that makes a copy of inval to (*PI).
792         // This must be in the current basic block (bb).
793         const MachineCodeForVMInstr& mvec = MachineBasicBlock::get(*PI);
794         const MachineInstr* theCopy = NULL;
795         for (unsigned i=0; i < mvec.size() && theCopy == NULL; i++)
796           if (! mii.isDummyPhiInstr(mvec[i]->getOpCode()))
797             // not a Phi: assume this is a copy and examine its operands
798             for (int o=0, N=(int) mvec[i]->getNumOperands(); o < N; o++)
799               {
800                 const MachineOperand& mop = mvec[i]->getOperand(o);
801                 
802                 if (mvec[i]->operandIsDefined(o))
803                   assert(mop.getVRegValue() == (*PI) && "dest shd be my Phi");
804                 
805                 if (! mvec[i]->operandIsDefined(o) ||
806                     NOT NEEDED? mvec[i]->operandIsDefinedAndUsed(o))
807                   if (mop.getVRegValue() == inVal)
808                     { // found the copy!
809                       theCopy = mvec[i];
810                       break;
811                     }
812               }
813         
814         // Found the dang instruction.  Now create a node and do the rest...
815         if (theCopy != NULL)
816           {
817             SchedGraphNode* node = new SchedGraphNode(getNumNodes(), bb,
818                                             theCopy, origIndexInBB++, target);
819             this->noteGraphNodeForInstr(theCopy, node);
820             findDefUseInfoAtInstr(target, node,
821                                   memNodeVec, regToRefVecMap,valueToDefVecMap);
822           }
823       }
824 #endif  //REALLY_NEED_TO_SEARCH_SUCCESSOR_PHIS
825 }
826
827
828 void
829 SchedGraph::buildGraph(const TargetMachine& target)
830 {
831   const BasicBlock* bb = bbVec[0];
832   
833   assert(bbVec.size() == 1 && "Only handling a single basic block here");
834   
835   // Use this data structure to note all machine operands that compute
836   // ordinary LLVM values.  These must be computed defs (i.e., instructions). 
837   // Note that there may be multiple machine instructions that define
838   // each Value.
839   ValueToDefVecMap valueToDefVecMap;
840   
841   // Use this data structure to note all memory instructions.
842   // We use this to add memory dependence edges without a second full walk.
843   // 
844   // vector<const Instruction*> memVec;
845   vector<SchedGraphNode*> memNodeVec;
846   
847   // Use this data structure to note any uses or definitions of
848   // machine registers so we can add edges for those later without
849   // extra passes over the nodes.
850   // The vector holds an ordered list of references to the machine reg,
851   // ordered according to control-flow order.  This only works for a
852   // single basic block, hence the assertion.  Each reference is identified
853   // by the pair: <node, operand-number>.
854   // 
855   RegToRefVecMap regToRefVecMap;
856   
857   // Make a dummy root node.  We'll add edges to the real roots later.
858   graphRoot = new SchedGraphNode(0, NULL, NULL, -1, target);
859   graphLeaf = new SchedGraphNode(1, NULL, NULL, -1, target);
860
861   //----------------------------------------------------------------
862   // First add nodes for all the machine instructions in the basic block
863   // because this greatly simplifies identifying which edges to add.
864   // Do this one VM instruction at a time since the SchedGraphNode needs that.
865   // Also, remember the load/store instructions to add memory deps later.
866   //----------------------------------------------------------------
867   
868   buildNodesforBB(target, bb, memNodeVec, regToRefVecMap, valueToDefVecMap);
869   
870   //----------------------------------------------------------------
871   // Now add edges for the following (all are incoming edges except (4)):
872   // (1) operands of the machine instruction, including hidden operands
873   // (2) machine register dependences
874   // (3) memory load/store dependences
875   // (3) other resource dependences for the machine instruction, if any
876   // (4) output dependences when multiple machine instructions define the
877   //     same value; all must have been generated from a single VM instrn
878   // (5) control dependences to branch instructions generated for the
879   //     terminator instruction of the BB. Because of delay slots and
880   //     2-way conditional branches, multiple CD edges are needed
881   //     (see addCDEdges for details).
882   // Also, note any uses or defs of machine registers.
883   // 
884   //----------------------------------------------------------------
885       
886   MachineBasicBlock& bbMvec = MachineBasicBlock::get(bb);
887   
888   // First, add edges to the terminator instruction of the basic block.
889   this->addCDEdges(bb->getTerminator(), target);
890       
891   // Then add memory dep edges: store->load, load->store, and store->store.
892   // Call instructions are treated as both load and store.
893   this->addMemEdges(memNodeVec, target);
894
895   // Then add edges between call instructions and CC set/use instructions
896   this->addCallCCEdges(memNodeVec, bbMvec, target);
897   
898   // Then add incoming def-use (SSA) edges for each machine instruction.
899   for (unsigned i=0, N=bbMvec.size(); i < N; i++)
900     addEdgesForInstruction(*bbMvec[i], valueToDefVecMap, target);
901   
902 #ifdef NEED_SEPARATE_NONSSA_EDGES_CODE
903   // Then add non-SSA edges for all VM instructions in the block.
904   // We assume that all machine instructions that define a value are
905   // generated from the VM instruction corresponding to that value.
906   // TODO: This could probably be done much more efficiently.
907   for (BasicBlock::const_iterator II = bb->begin(); II != bb->end(); ++II)
908     this->addNonSSAEdgesForValue(*II, target);
909 #endif //NEED_SEPARATE_NONSSA_EDGES_CODE
910   
911   // Then add edges for dependences on machine registers
912   this->addMachineRegEdges(regToRefVecMap, target);
913   
914   // Finally, add edges from the dummy root and to dummy leaf
915   this->addDummyEdges();                
916 }
917
918
919 // 
920 // class SchedGraphSet
921 // 
922
923 /*ctor*/
924 SchedGraphSet::SchedGraphSet(const Function* _function,
925                              const TargetMachine& target) :
926   method(_function)
927 {
928   buildGraphsForMethod(method, target);
929 }
930
931
932 /*dtor*/
933 SchedGraphSet::~SchedGraphSet()
934 {
935   // delete all the graphs
936   for(iterator I = begin(), E = end(); I != E; ++I)
937     delete *I;  // destructor is a friend
938 }
939
940
941 void
942 SchedGraphSet::dump() const
943 {
944   cerr << "======== Sched graphs for function `" << method->getName()
945        << "' ========\n\n";
946   
947   for (const_iterator I=begin(); I != end(); ++I)
948     (*I)->dump();
949   
950   cerr << "\n====== End graphs for function `" << method->getName()
951        << "' ========\n\n";
952 }
953
954
955 void
956 SchedGraphSet::buildGraphsForMethod(const Function *F,
957                                     const TargetMachine& target)
958 {
959   for (Function::const_iterator BI = F->begin(); BI != F->end(); ++BI)
960     addGraph(new SchedGraph(BI, target));
961 }
962
963
964 std::ostream &operator<<(std::ostream &os, const SchedGraphEdge& edge)
965 {
966   os << "edge [" << edge.src->getNodeId() << "] -> ["
967      << edge.sink->getNodeId() << "] : ";
968   
969   switch(edge.depType) {
970   case SchedGraphEdge::CtrlDep:         os<< "Control Dep"; break;
971   case SchedGraphEdge::ValueDep:        os<< "Reg Value " << edge.val; break;
972   case SchedGraphEdge::MemoryDep:       os<< "Memory Dep"; break;
973   case SchedGraphEdge::MachineRegister: os<< "Reg " <<edge.machineRegNum;break;
974   case SchedGraphEdge::MachineResource: os<<"Resource "<<edge.resourceId;break;
975   default: assert(0); break;
976   }
977   
978   os << " : delay = " << edge.minDelay << "\n";
979   
980   return os;
981 }
982
983 std::ostream &operator<<(std::ostream &os, const SchedGraphNode& node)
984 {
985   os << std::string(8, ' ')
986      << "Node " << node.nodeId << " : "
987      << "latency = " << node.latency << "\n" << std::string(12, ' ');
988   
989   if (node.getMachineInstr() == NULL)
990     os << "(Dummy node)\n";
991   else
992     {
993       os << *node.getMachineInstr() << "\n" << std::string(12, ' ');
994       os << node.inEdges.size() << " Incoming Edges:\n";
995       for (unsigned i=0, N=node.inEdges.size(); i < N; i++)
996           os << std::string(16, ' ') << *node.inEdges[i];
997   
998       os << std::string(12, ' ') << node.outEdges.size()
999          << " Outgoing Edges:\n";
1000       for (unsigned i=0, N=node.outEdges.size(); i < N; i++)
1001         os << std::string(16, ' ') << *node.outEdges[i];
1002     }
1003   
1004   return os;
1005 }