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