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