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