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