e88c801a425f1795d254a60615feba58db653875
[oota-llvm.git] / lib / Target / SparcV9 / InstrSched / SchedGraph.cpp
1 //===- SchedGraph.cpp - Scheduling Graph Implementation -------------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // Scheduling graph based on SSA graph plus extra dependence edges capturing
11 // dependences due to machine resources (machine registers, CC registers, and
12 // any others).
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "SchedGraph.h"
17 #include "llvm/Function.h"
18 #include "llvm/iOther.h"
19 #include "llvm/CodeGen/MachineCodeForInstruction.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/Target/TargetInstrInfo.h"
22 #include "llvm/Target/TargetMachine.h"
23 #include "../../Target/SparcV9/SparcV9RegInfo.h"
24 #include "Support/STLExtras.h"
25
26 namespace llvm {
27
28 //*********************** Internal Data Structures *************************/
29
30 // The following two types need to be classes, not typedefs, so we can use
31 // opaque declarations in SchedGraph.h
32 // 
33 struct RefVec: public std::vector<std::pair<SchedGraphNode*, int> > {
34   typedef std::vector<std::pair<SchedGraphNode*,int> >::iterator iterator;
35   typedef
36   std::vector<std::pair<SchedGraphNode*,int> >::const_iterator const_iterator;
37 };
38
39 struct RegToRefVecMap: public hash_map<int, RefVec> {
40   typedef hash_map<int, RefVec>::      iterator       iterator;
41   typedef hash_map<int, RefVec>::const_iterator const_iterator;
42 };
43
44 struct ValueToDefVecMap: public hash_map<const Value*, RefVec> {
45   typedef hash_map<const Value*, RefVec>::      iterator       iterator;
46   typedef hash_map<const Value*, RefVec>::const_iterator const_iterator;
47 };
48
49
50 // 
51 // class SchedGraphNode
52 // 
53
54 SchedGraphNode::SchedGraphNode(unsigned NID, MachineBasicBlock *mbb,
55                                int   indexInBB, const TargetMachine& Target)
56   : SchedGraphNodeCommon(NID,indexInBB), MBB(mbb), MI(0) {
57   if (mbb) {
58     MachineBasicBlock::iterator I = MBB->begin();
59     std::advance(I, indexInBB);
60     MI = I;
61
62     MachineOpCode mopCode = MI->getOpcode();
63     latency = Target.getInstrInfo()->hasResultInterlock(mopCode)
64       ? Target.getInstrInfo()->minLatency(mopCode)
65       : Target.getInstrInfo()->maxLatency(mopCode);
66   }
67 }
68
69 //
70 // Method: SchedGraphNode Destructor
71 //
72 // Description:
73 //      Free memory allocated by the SchedGraphNode object.
74 //
75 // Notes:
76 //      Do not delete the edges here.  The base class will take care of that.
77 //      Only handle subclass specific stuff here (where currently there is
78 //      none).
79 //
80 SchedGraphNode::~SchedGraphNode() {
81 }
82
83 // 
84 // class SchedGraph
85 // 
86 SchedGraph::SchedGraph(MachineBasicBlock &mbb, const TargetMachine& target)
87   : MBB(mbb) {
88   buildGraph(target);
89 }
90
91 //
92 // Method: SchedGraph Destructor
93 //
94 // Description:
95 //      This method deletes memory allocated by the SchedGraph object.
96 //
97 // Notes:
98 //      Do not delete the graphRoot or graphLeaf here.  The base class handles
99 //      that bit of work.
100 //
101 SchedGraph::~SchedGraph() {
102   for (const_iterator I = begin(); I != end(); ++I)
103     delete I->second;
104 }
105
106 void SchedGraph::dump() const {
107   std::cerr << "  Sched Graph for Basic Block: "
108             << MBB.getBasicBlock()->getName()
109             << " (" << MBB.getBasicBlock() << ")"
110             << "\n\n    Actual Root nodes: ";
111   for (SchedGraphNodeCommon::const_iterator I = graphRoot->beginOutEdges(),
112                                             E = graphRoot->endOutEdges();
113        I != E; ++I) {
114     std::cerr << (*I)->getSink ()->getNodeId ();
115     if (I + 1 != E) { std::cerr << ", "; }
116   }
117   std::cerr << "\n    Graph Nodes:\n";
118   for (const_iterator I = begin(), E = end(); I != E; ++I)
119     std::cerr << "\n" << *I->second;
120   std::cerr << "\n";
121 }
122
123 void SchedGraph::addDummyEdges() {
124   assert(graphRoot->getNumOutEdges() == 0);
125   
126   for (const_iterator I=begin(); I != end(); ++I) {
127     SchedGraphNode* node = (*I).second;
128     assert(node != graphRoot && node != graphLeaf);
129     if (node->beginInEdges() == node->endInEdges())
130       (void) new SchedGraphEdge(graphRoot, node, SchedGraphEdge::CtrlDep,
131                                 SchedGraphEdge::NonDataDep, 0);
132     if (node->beginOutEdges() == node->endOutEdges())
133       (void) new SchedGraphEdge(node, graphLeaf, SchedGraphEdge::CtrlDep,
134                                 SchedGraphEdge::NonDataDep, 0);
135   }
136 }
137
138
139 void SchedGraph::addCDEdges(const TerminatorInst* term,
140                             const TargetMachine& target) {
141   const TargetInstrInfo& mii = *target.getInstrInfo();
142   MachineCodeForInstruction &termMvec = MachineCodeForInstruction::get(term);
143   
144   // Find the first branch instr in the sequence of machine instrs for term
145   // 
146   unsigned first = 0;
147   while (! mii.isBranch(termMvec[first]->getOpcode()) &&
148          ! mii.isReturn(termMvec[first]->getOpcode()))
149     ++first;
150   assert(first < termMvec.size() &&
151          "No branch instructions for terminator?  Ok, but weird!");
152   if (first == termMvec.size())
153     return;
154   
155   SchedGraphNode* firstBrNode = getGraphNodeForInstr(termMvec[first]);
156   
157   // Add CD edges from each instruction in the sequence to the
158   // *last preceding* branch instr. in the sequence 
159   // Use a latency of 0 because we only need to prevent out-of-order issue.
160   // 
161   for (unsigned i = termMvec.size(); i > first+1; --i) {
162     SchedGraphNode* toNode = getGraphNodeForInstr(termMvec[i-1]);
163     assert(toNode && "No node for instr generated for branch/ret?");
164     
165     for (unsigned j = i-1; j != 0; --j) 
166       if (mii.isBranch(termMvec[j-1]->getOpcode()) ||
167           mii.isReturn(termMvec[j-1]->getOpcode())) {
168         SchedGraphNode* brNode = getGraphNodeForInstr(termMvec[j-1]);
169         assert(brNode && "No node for instr generated for branch/ret?");
170         (void) new SchedGraphEdge(brNode, toNode, SchedGraphEdge::CtrlDep,
171                                   SchedGraphEdge::NonDataDep, 0);
172         break;                  // only one incoming edge is enough
173       }
174   }
175   
176   // Add CD edges from each instruction preceding the first branch
177   // to the first branch.  Use a latency of 0 as above.
178   // 
179   for (unsigned i = first; i != 0; --i) {
180     SchedGraphNode* fromNode = getGraphNodeForInstr(termMvec[i-1]);
181     assert(fromNode && "No node for instr generated for branch?");
182     (void) new SchedGraphEdge(fromNode, firstBrNode, SchedGraphEdge::CtrlDep,
183                               SchedGraphEdge::NonDataDep, 0);
184   }
185   
186   // Now add CD edges to the first branch instruction in the sequence from
187   // all preceding instructions in the basic block.  Use 0 latency again.
188   // 
189   for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ++I){
190     if (&*I == termMvec[first])   // reached the first branch
191       break;
192     
193     SchedGraphNode* fromNode = getGraphNodeForInstr(I);
194     if (fromNode == NULL)
195       continue;                 // dummy instruction, e.g., PHI
196     
197     (void) new SchedGraphEdge(fromNode, firstBrNode,
198                               SchedGraphEdge::CtrlDep,
199                               SchedGraphEdge::NonDataDep, 0);
200       
201     // If we find any other machine instructions (other than due to
202     // the terminator) that also have delay slots, add an outgoing edge
203     // from the instruction to the instructions in the delay slots.
204     // 
205     unsigned d = mii.getNumDelaySlots(I->getOpcode());
206
207     MachineBasicBlock::iterator J = I; ++J;
208     for (unsigned j=1; j <= d; j++, ++J) {
209       SchedGraphNode* toNode = this->getGraphNodeForInstr(J);
210       assert(toNode && "No node for machine instr in delay slot?");
211       (void) new SchedGraphEdge(fromNode, toNode,
212                                 SchedGraphEdge::CtrlDep,
213                                 SchedGraphEdge::NonDataDep, 0);
214     }
215   }
216 }
217
218 static const int SG_LOAD_REF  = 0;
219 static const int SG_STORE_REF = 1;
220 static const int SG_CALL_REF  = 2;
221
222 static const unsigned int SG_DepOrderArray[][3] = {
223   { SchedGraphEdge::NonDataDep,
224     SchedGraphEdge::AntiDep,
225     SchedGraphEdge::AntiDep },
226   { SchedGraphEdge::TrueDep,
227     SchedGraphEdge::OutputDep,
228     SchedGraphEdge::TrueDep | SchedGraphEdge::OutputDep },
229   { SchedGraphEdge::TrueDep,
230     SchedGraphEdge::AntiDep | SchedGraphEdge::OutputDep,
231     SchedGraphEdge::TrueDep | SchedGraphEdge::AntiDep
232     | SchedGraphEdge::OutputDep }
233 };
234
235
236 // Add a dependence edge between every pair of machine load/store/call
237 // instructions, where at least one is a store or a call.
238 // Use latency 1 just to ensure that memory operations are ordered;
239 // latency does not otherwise matter (true dependences enforce that).
240 // 
241 void SchedGraph::addMemEdges(const std::vector<SchedGraphNode*>& memNodeVec,
242                              const TargetMachine& target) {
243   const TargetInstrInfo& mii = *target.getInstrInfo();
244   
245   // Instructions in memNodeVec are in execution order within the basic block,
246   // so simply look at all pairs <memNodeVec[i], memNodeVec[j: j > i]>.
247   // 
248   for (unsigned im=0, NM=memNodeVec.size(); im < NM; im++) {
249     MachineOpCode fromOpCode = memNodeVec[im]->getOpcode();
250     int fromType = (mii.isCall(fromOpCode)? SG_CALL_REF
251                     : (mii.isLoad(fromOpCode)? SG_LOAD_REF
252                        : SG_STORE_REF));
253     for (unsigned jm=im+1; jm < NM; jm++) {
254       MachineOpCode toOpCode = memNodeVec[jm]->getOpcode();
255       int toType = (mii.isCall(toOpCode)? SG_CALL_REF
256                     : (mii.isLoad(toOpCode)? SG_LOAD_REF
257                        : SG_STORE_REF));
258       
259       if (fromType != SG_LOAD_REF || toType != SG_LOAD_REF)
260         (void) new SchedGraphEdge(memNodeVec[im], memNodeVec[jm],
261                                   SchedGraphEdge::MemoryDep,
262                                   SG_DepOrderArray[fromType][toType], 1);
263     }
264   }
265
266
267 // Add edges from/to CC reg instrs to/from call instrs.
268 // Essentially this prevents anything that sets or uses a CC reg from being
269 // reordered w.r.t. a call.
270 // Use a latency of 0 because we only need to prevent out-of-order issue,
271 // like with control dependences.
272 // 
273 void SchedGraph::addCallDepEdges(const std::vector<SchedGraphNode*>& callDepNodeVec,
274                                  const TargetMachine& target) {
275   const TargetInstrInfo& mii = *target.getInstrInfo();
276   
277   // Instructions in memNodeVec are in execution order within the basic block,
278   // so simply look at all pairs <memNodeVec[i], memNodeVec[j: j > i]>.
279   // 
280   for (unsigned ic=0, NC=callDepNodeVec.size(); ic < NC; ic++)
281     if (mii.isCall(callDepNodeVec[ic]->getOpcode())) {
282       // Add SG_CALL_REF edges from all preds to this instruction.
283       for (unsigned jc=0; jc < ic; jc++)
284         (void) new SchedGraphEdge(callDepNodeVec[jc], callDepNodeVec[ic],
285                                   SchedGraphEdge::MachineRegister,
286                                   MachineIntRegsRID,  0);
287       
288       // And do the same from this instruction to all successors.
289       for (unsigned jc=ic+1; jc < NC; jc++)
290         (void) new SchedGraphEdge(callDepNodeVec[ic], callDepNodeVec[jc],
291                                   SchedGraphEdge::MachineRegister,
292                                   MachineIntRegsRID,  0);
293     }
294   
295 #ifdef CALL_DEP_NODE_VEC_CANNOT_WORK
296   // Find the call instruction nodes and put them in a vector.
297   std::vector<SchedGraphNode*> callNodeVec;
298   for (unsigned im=0, NM=memNodeVec.size(); im < NM; im++)
299     if (mii.isCall(memNodeVec[im]->getOpcode()))
300       callNodeVec.push_back(memNodeVec[im]);
301   
302   // Now walk the entire basic block, looking for CC instructions *and*
303   // call instructions, and keep track of the order of the instructions.
304   // Use the call node vec to quickly find earlier and later call nodes
305   // relative to the current CC instruction.
306   // 
307   int lastCallNodeIdx = -1;
308   for (unsigned i=0, N=bbMvec.size(); i < N; i++)
309     if (mii.isCall(bbMvec[i]->getOpcode())) {
310       ++lastCallNodeIdx;
311       for ( ; lastCallNodeIdx < (int)callNodeVec.size(); ++lastCallNodeIdx)
312         if (callNodeVec[lastCallNodeIdx]->getMachineInstr() == bbMvec[i])
313           break;
314       assert(lastCallNodeIdx < (int)callNodeVec.size() && "Missed Call?");
315     }
316     else if (mii.isCCInstr(bbMvec[i]->getOpcode())) {
317       // Add incoming/outgoing edges from/to preceding/later calls
318       SchedGraphNode* ccNode = this->getGraphNodeForInstr(bbMvec[i]);
319       int j=0;
320       for ( ; j <= lastCallNodeIdx; j++)
321         (void) new SchedGraphEdge(callNodeVec[j], ccNode,
322                                   MachineCCRegsRID, 0);
323       for ( ; j < (int) callNodeVec.size(); j++)
324         (void) new SchedGraphEdge(ccNode, callNodeVec[j],
325                                   MachineCCRegsRID, 0);
326     }
327 #endif
328 }
329
330
331 void SchedGraph::addMachineRegEdges(RegToRefVecMap& regToRefVecMap,
332                                     const TargetMachine& target) {
333   // This code assumes that two registers with different numbers are
334   // not aliased!
335   // 
336   for (RegToRefVecMap::iterator I = regToRefVecMap.begin();
337        I != regToRefVecMap.end(); ++I) {
338     int regNum        = (*I).first;
339     RefVec& regRefVec = (*I).second;
340     
341     // regRefVec is ordered by control flow order in the basic block
342     for (unsigned i=0; i < regRefVec.size(); ++i) {
343       SchedGraphNode* node = regRefVec[i].first;
344       unsigned int opNum   = regRefVec[i].second;
345       const MachineOperand& mop =
346         node->getMachineInstr()->getExplOrImplOperand(opNum);
347       bool isDef = mop.isDef() && !mop.isUse();
348       bool isDefAndUse = mop.isDef() && mop.isUse();
349           
350       for (unsigned p=0; p < i; ++p) {
351         SchedGraphNode* prevNode = regRefVec[p].first;
352         if (prevNode != node) {
353           unsigned int prevOpNum = regRefVec[p].second;
354           const MachineOperand& prevMop =
355             prevNode->getMachineInstr()->getExplOrImplOperand(prevOpNum);
356           bool prevIsDef = prevMop.isDef() && !prevMop.isUse();
357           bool prevIsDefAndUse = prevMop.isDef() && prevMop.isUse();
358           if (isDef) {
359             if (prevIsDef)
360               new SchedGraphEdge(prevNode, node, regNum,
361                                  SchedGraphEdge::OutputDep);
362             if (!prevIsDef || prevIsDefAndUse)
363               new SchedGraphEdge(prevNode, node, regNum,
364                                  SchedGraphEdge::AntiDep);
365           }
366           
367           if (prevIsDef)
368             if (!isDef || isDefAndUse)
369               new SchedGraphEdge(prevNode, node, regNum,
370                                  SchedGraphEdge::TrueDep);
371         }
372       }
373     }
374   }
375 }
376
377
378 // Adds dependences to/from refNode from/to all other defs
379 // in the basic block.  refNode may be a use, a def, or both.
380 // We do not consider other uses because we are not building use-use deps.
381 // 
382 void SchedGraph::addEdgesForValue(SchedGraphNode* refNode,
383                                   const RefVec& defVec,
384                                   const Value* defValue,
385                                   bool  refNodeIsDef,
386                                   bool  refNodeIsUse,
387                                   const TargetMachine& target) {
388   // Add true or output dep edges from all def nodes before refNode in BB.
389   // Add anti or output dep edges to all def nodes after refNode.
390   for (RefVec::const_iterator I=defVec.begin(), E=defVec.end(); I != E; ++I) {
391     if ((*I).first == refNode)
392       continue;                       // Dont add any self-loops
393     
394     if ((*I).first->getOrigIndexInBB() < refNode->getOrigIndexInBB()) {
395       // (*).first is before refNode
396       if (refNodeIsDef && !refNodeIsUse)
397         (void) new SchedGraphEdge((*I).first, refNode, defValue,
398                                   SchedGraphEdge::OutputDep);
399       if (refNodeIsUse)
400         (void) new SchedGraphEdge((*I).first, refNode, defValue,
401                                   SchedGraphEdge::TrueDep);
402     } else {
403       // (*).first is after refNode
404       if (refNodeIsDef && !refNodeIsUse)
405         (void) new SchedGraphEdge(refNode, (*I).first, defValue,
406                                   SchedGraphEdge::OutputDep);
407       if (refNodeIsUse)
408         (void) new SchedGraphEdge(refNode, (*I).first, defValue,
409                                   SchedGraphEdge::AntiDep);
410     }
411   }
412 }
413
414
415 void SchedGraph::addEdgesForInstruction(const MachineInstr& MI,
416                                         const ValueToDefVecMap& valueToDefVecMap,
417                                         const TargetMachine& target) {
418   SchedGraphNode* node = getGraphNodeForInstr(&MI);
419   if (node == NULL)
420     return;
421   
422   // Add edges for all operands of the machine instruction.
423   // 
424   for (unsigned i = 0, numOps = MI.getNumOperands(); i != numOps; ++i) {
425     switch (MI.getOperand(i).getType()) {
426     case MachineOperand::MO_VirtualRegister:
427     case MachineOperand::MO_CCRegister:
428       if (const Value* srcI = MI.getOperand(i).getVRegValue()) {
429         ValueToDefVecMap::const_iterator I = valueToDefVecMap.find(srcI);
430         if (I != valueToDefVecMap.end())
431           addEdgesForValue(node, I->second, srcI,
432                            MI.getOperand(i).isDef(), MI.getOperand(i).isUse(),
433                            target);
434       }
435       break;
436       
437     case MachineOperand::MO_MachineRegister:
438       break; 
439       
440     case MachineOperand::MO_SignExtendedImmed:
441     case MachineOperand::MO_UnextendedImmed:
442     case MachineOperand::MO_PCRelativeDisp:
443     case MachineOperand::MO_ConstantPoolIndex:
444       break;    // nothing to do for immediate fields
445       
446     default:
447       assert(0 && "Unknown machine operand type in SchedGraph builder");
448       break;
449     }
450   }
451   
452   // Add edges for values implicitly used by the machine instruction.
453   // Examples include function arguments to a Call instructions or the return
454   // value of a Ret instruction.
455   // 
456   for (unsigned i=0, N=MI.getNumImplicitRefs(); i < N; ++i)
457     if (MI.getImplicitOp(i).isUse())
458       if (const Value* srcI = MI.getImplicitRef(i)) {
459         ValueToDefVecMap::const_iterator I = valueToDefVecMap.find(srcI);
460         if (I != valueToDefVecMap.end())
461           addEdgesForValue(node, I->second, srcI,
462                            MI.getImplicitOp(i).isDef(),
463                            MI.getImplicitOp(i).isUse(), target);
464       }
465 }
466
467
468 void SchedGraph::findDefUseInfoAtInstr(const TargetMachine& target,
469                                        SchedGraphNode* node,
470                                        std::vector<SchedGraphNode*>& memNodeVec,
471                                        std::vector<SchedGraphNode*>& callDepNodeVec,
472                                        RegToRefVecMap& regToRefVecMap,
473                                        ValueToDefVecMap& valueToDefVecMap) {
474   const TargetInstrInfo& mii = *target.getInstrInfo();
475   
476   MachineOpCode opCode = node->getOpcode();
477   
478   if (mii.isCall(opCode) || mii.isCCInstr(opCode))
479     callDepNodeVec.push_back(node);
480   
481   if (mii.isLoad(opCode) || mii.isStore(opCode) || mii.isCall(opCode))
482     memNodeVec.push_back(node);
483   
484   // Collect the register references and value defs. for explicit operands
485   // 
486   const MachineInstr& MI = *node->getMachineInstr();
487   for (int i=0, numOps = (int) MI.getNumOperands(); i < numOps; i++) {
488     const MachineOperand& mop = MI.getOperand(i);
489     
490     // if this references a register other than the hardwired
491     // "zero" register, record the reference.
492     if (mop.hasAllocatedReg()) {
493       unsigned regNum = mop.getReg();
494       
495       // If this is not a dummy zero register, record the reference in order
496       if (regNum != target.getRegInfo()->getZeroRegNum())
497         regToRefVecMap[mop.getReg()]
498           .push_back(std::make_pair(node, i));
499
500       // If this is a volatile register, add the instruction to callDepVec
501       // (only if the node is not already on the callDepVec!)
502       if (callDepNodeVec.size() == 0 || callDepNodeVec.back() != node)
503         {
504           unsigned rcid;
505           int regInClass = target.getRegInfo()->getClassRegNum(regNum, rcid);
506           if (target.getRegInfo()->getMachineRegClass(rcid)
507               ->isRegVolatile(regInClass))
508             callDepNodeVec.push_back(node);
509         }
510           
511       continue;                     // nothing more to do
512     }
513     
514     // ignore all other non-def operands
515     if (!MI.getOperand(i).isDef())
516       continue;
517       
518     // We must be defining a value.
519     assert((mop.getType() == MachineOperand::MO_VirtualRegister ||
520             mop.getType() == MachineOperand::MO_CCRegister)
521            && "Do not expect any other kind of operand to be defined!");
522     assert(mop.getVRegValue() != NULL && "Null value being defined?");
523     
524     valueToDefVecMap[mop.getVRegValue()].push_back(std::make_pair(node, i)); 
525   }
526   
527   // 
528   // Collect value defs. for implicit operands.  They may have allocated
529   // physical registers also.
530   // 
531   for (unsigned i=0, N = MI.getNumImplicitRefs(); i != N; ++i) {
532     const MachineOperand& mop = MI.getImplicitOp(i);
533     if (mop.hasAllocatedReg()) {
534       unsigned regNum = mop.getReg();
535       if (regNum != target.getRegInfo()->getZeroRegNum())
536         regToRefVecMap[mop.getReg()]
537           .push_back(std::make_pair(node, i + MI.getNumOperands()));
538       continue;                     // nothing more to do
539     }
540
541     if (mop.isDef()) {
542       assert(MI.getImplicitRef(i) != NULL && "Null value being defined?");
543       valueToDefVecMap[MI.getImplicitRef(i)].push_back(
544         std::make_pair(node, -i)); 
545     }
546   }
547 }
548
549
550 void SchedGraph::buildNodesForBB(const TargetMachine& target,
551                                  MachineBasicBlock& MBB,
552                                  std::vector<SchedGraphNode*>& memNodeVec,
553                                  std::vector<SchedGraphNode*>& callDepNodeVec,
554                                  RegToRefVecMap& regToRefVecMap,
555                                  ValueToDefVecMap& valueToDefVecMap) {
556   const TargetInstrInfo& mii = *target.getInstrInfo();
557   
558   // Build graph nodes for each VM instruction and gather def/use info.
559   // Do both those together in a single pass over all machine instructions.
560   unsigned i = 0;
561   for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E;
562        ++I, ++i)
563     if (!mii.isDummyPhiInstr(I->getOpcode())) {
564       SchedGraphNode* node = new SchedGraphNode(getNumNodes(), &MBB, i, target);
565       noteGraphNodeForInstr(I, node);
566       
567       // Remember all register references and value defs
568       findDefUseInfoAtInstr(target, node, memNodeVec, callDepNodeVec,
569                             regToRefVecMap, valueToDefVecMap);
570     }
571 }
572
573
574 void SchedGraph::buildGraph(const TargetMachine& target) {
575   // Use this data structure to note all machine operands that compute
576   // ordinary LLVM values.  These must be computed defs (i.e., instructions). 
577   // Note that there may be multiple machine instructions that define
578   // each Value.
579   ValueToDefVecMap valueToDefVecMap;
580   
581   // Use this data structure to note all memory instructions.
582   // We use this to add memory dependence edges without a second full walk.
583   std::vector<SchedGraphNode*> memNodeVec;
584
585   // Use this data structure to note all instructions that access physical
586   // registers that can be modified by a call (including call instructions)
587   std::vector<SchedGraphNode*> callDepNodeVec;
588   
589   // Use this data structure to note any uses or definitions of
590   // machine registers so we can add edges for those later without
591   // extra passes over the nodes.
592   // The vector holds an ordered list of references to the machine reg,
593   // ordered according to control-flow order.  This only works for a
594   // single basic block, hence the assertion.  Each reference is identified
595   // by the pair: <node, operand-number>.
596   // 
597   RegToRefVecMap regToRefVecMap;
598   
599   // Make a dummy root node.  We'll add edges to the real roots later.
600   graphRoot = new SchedGraphNode(0, NULL, -1, target);
601   graphLeaf = new SchedGraphNode(1, NULL, -1, target);
602
603   //----------------------------------------------------------------
604   // First add nodes for all the machine instructions in the basic block
605   // because this greatly simplifies identifying which edges to add.
606   // Do this one VM instruction at a time since the SchedGraphNode needs that.
607   // Also, remember the load/store instructions to add memory deps later.
608   //----------------------------------------------------------------
609
610   buildNodesForBB(target, MBB, memNodeVec, callDepNodeVec,
611                   regToRefVecMap, valueToDefVecMap);
612   
613   //----------------------------------------------------------------
614   // Now add edges for the following (all are incoming edges except (4)):
615   // (1) operands of the machine instruction, including hidden operands
616   // (2) machine register dependences
617   // (3) memory load/store dependences
618   // (3) other resource dependences for the machine instruction, if any
619   // (4) output dependences when multiple machine instructions define the
620   //     same value; all must have been generated from a single VM instrn
621   // (5) control dependences to branch instructions generated for the
622   //     terminator instruction of the BB. Because of delay slots and
623   //     2-way conditional branches, multiple CD edges are needed
624   //     (see addCDEdges for details).
625   // Also, note any uses or defs of machine registers.
626   // 
627   //----------------------------------------------------------------
628       
629   // First, add edges to the terminator instruction of the basic block.
630   this->addCDEdges(MBB.getBasicBlock()->getTerminator(), target);
631       
632   // Then add memory dep edges: store->load, load->store, and store->store.
633   // Call instructions are treated as both load and store.
634   this->addMemEdges(memNodeVec, target);
635
636   // Then add edges between call instructions and CC set/use instructions
637   this->addCallDepEdges(callDepNodeVec, target);
638   
639   // Then add incoming def-use (SSA) edges for each machine instruction.
640   for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ++I)
641     addEdgesForInstruction(*I, valueToDefVecMap, target);
642
643   // Then add edges for dependences on machine registers
644   this->addMachineRegEdges(regToRefVecMap, target);
645
646   // Finally, add edges from the dummy root and to dummy leaf
647   this->addDummyEdges();                
648 }
649
650
651 // 
652 // class SchedGraphSet
653 // 
654 SchedGraphSet::SchedGraphSet(const Function* _function,
655                              const TargetMachine& target) :
656   function(_function) {
657   buildGraphsForMethod(function, target);
658 }
659
660 SchedGraphSet::~SchedGraphSet() {
661   // delete all the graphs
662   for(iterator I = begin(), E = end(); I != E; ++I)
663     delete *I;  // destructor is a friend
664 }
665
666
667 void SchedGraphSet::dump() const {
668   std::cerr << "======== Sched graphs for function `" << function->getName()
669             << "' ========\n\n";
670   
671   for (const_iterator I=begin(); I != end(); ++I)
672     (*I)->dump();
673   
674   std::cerr << "\n====== End graphs for function `" << function->getName()
675             << "' ========\n\n";
676 }
677
678
679 void SchedGraphSet::buildGraphsForMethod(const Function *F,
680                                          const TargetMachine& target) {
681   MachineFunction &MF = MachineFunction::get(F);
682   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
683     addGraph(new SchedGraph(*I, target));
684 }
685
686
687 void SchedGraphEdge::print(std::ostream &os) const {
688   os << "edge [" << src->getNodeId() << "] -> ["
689      << sink->getNodeId() << "] : ";
690   
691   switch(depType) {
692   case SchedGraphEdge::CtrlDep:         
693     os<< "Control Dep"; 
694     break;
695   case SchedGraphEdge::ValueDep:        
696     os<< "Reg Value " << val; 
697     break;
698   case SchedGraphEdge::MemoryDep:       
699     os<< "Memory Dep"; 
700     break;
701   case SchedGraphEdge::MachineRegister: 
702     os<< "Reg " << machineRegNum;
703     break;
704   case SchedGraphEdge::MachineResource:
705     os<<"Resource "<< resourceId;
706     break;
707   default: 
708     assert(0); 
709     break;
710   }
711   
712   os << " : delay = " << minDelay << "\n";
713 }
714
715 void SchedGraphNode::print(std::ostream &os) const {
716   os << std::string(8, ' ')
717      << "Node " << ID << " : "
718      << "latency = " << latency << "\n" << std::string(12, ' ');
719   
720   if (getMachineInstr() == NULL)
721     os << "(Dummy node)\n";
722   else {
723     os << *getMachineInstr() << "\n" << std::string(12, ' ');
724     os << inEdges.size() << " Incoming Edges:\n";
725     for (unsigned i=0, N = inEdges.size(); i < N; i++)
726       os << std::string(16, ' ') << *inEdges[i];
727   
728     os << std::string(12, ' ') << outEdges.size()
729        << " Outgoing Edges:\n";
730     for (unsigned i=0, N= outEdges.size(); i < N; i++)
731       os << std::string(16, ' ') << *outEdges[i];
732   }
733 }
734
735 } // End llvm namespace