2 //***************************************************************************
7 // Scheduling graph based on SSA graph plus extra dependence edges
8 // capturing dependences due to machine resources (machine registers,
9 // CC registers, and any others).
12 // 7/20/01 - Vikram Adve - Created
13 //**************************************************************************/
15 #include "SchedGraph.h"
16 #include "llvm/CodeGen/InstrSelection.h"
17 #include "llvm/CodeGen/MachineCodeForInstruction.h"
18 #include "llvm/Target/MachineRegInfo.h"
19 #include "llvm/Target/TargetMachine.h"
20 #include "llvm/BasicBlock.h"
21 #include "llvm/Function.h"
22 #include "llvm/iOther.h"
23 #include "Support/StringExtras.h"
24 #include "Support/STLExtras.h"
32 //*********************** Internal Data Structures *************************/
34 // The following two types need to be classes, not typedefs, so we can use
35 // opaque declarations in SchedGraph.h
37 struct RefVec: public vector< pair<SchedGraphNode*, int> > {
38 typedef vector< pair<SchedGraphNode*, int> >:: iterator iterator;
39 typedef vector< pair<SchedGraphNode*, int> >::const_iterator const_iterator;
42 struct RegToRefVecMap: public hash_map<int, RefVec> {
43 typedef hash_map<int, RefVec>:: iterator iterator;
44 typedef hash_map<int, RefVec>::const_iterator const_iterator;
47 struct ValueToDefVecMap: public hash_map<const Instruction*, RefVec> {
48 typedef hash_map<const Instruction*, RefVec>:: iterator iterator;
49 typedef hash_map<const Instruction*, RefVec>::const_iterator const_iterator;
53 // class SchedGraphEdge
57 SchedGraphEdge::SchedGraphEdge(SchedGraphNode* _src,
58 SchedGraphNode* _sink,
59 SchedGraphEdgeDepType _depType,
60 unsigned int _depOrderType,
65 depOrderType(_depOrderType),
66 minDelay((_minDelay >= 0)? _minDelay : _src->getLatency()),
69 assert(src != sink && "Self-loop in scheduling graph!");
70 src->addOutEdge(this);
71 sink->addInEdge(this);
76 SchedGraphEdge::SchedGraphEdge(SchedGraphNode* _src,
77 SchedGraphNode* _sink,
79 unsigned int _depOrderType,
84 depOrderType(_depOrderType),
85 minDelay((_minDelay >= 0)? _minDelay : _src->getLatency()),
88 assert(src != sink && "Self-loop in scheduling graph!");
89 src->addOutEdge(this);
90 sink->addInEdge(this);
95 SchedGraphEdge::SchedGraphEdge(SchedGraphNode* _src,
96 SchedGraphNode* _sink,
98 unsigned int _depOrderType,
102 depType(MachineRegister),
103 depOrderType(_depOrderType),
104 minDelay((_minDelay >= 0)? _minDelay : _src->getLatency()),
105 machineRegNum(_regNum)
107 assert(src != sink && "Self-loop in scheduling graph!");
108 src->addOutEdge(this);
109 sink->addInEdge(this);
114 SchedGraphEdge::SchedGraphEdge(SchedGraphNode* _src,
115 SchedGraphNode* _sink,
116 ResourceId _resourceId,
120 depType(MachineResource),
121 depOrderType(NonDataDep),
122 minDelay((_minDelay >= 0)? _minDelay : _src->getLatency()),
123 resourceId(_resourceId)
125 assert(src != sink && "Self-loop in scheduling graph!");
126 src->addOutEdge(this);
127 sink->addInEdge(this);
131 SchedGraphEdge::~SchedGraphEdge()
135 void SchedGraphEdge::dump(int indent=0) const {
136 cerr << std::string(indent*2, ' ') << *this;
141 // class SchedGraphNode
145 SchedGraphNode::SchedGraphNode(unsigned int _nodeId,
146 const BasicBlock* _bb,
147 const MachineInstr* _minstr,
149 const TargetMachine& target)
153 origIndexInBB(indexInBB),
158 MachineOpCode mopCode = minstr->getOpCode();
159 latency = target.getInstrInfo().hasResultInterlock(mopCode)
160 ? target.getInstrInfo().minLatency(mopCode)
161 : target.getInstrInfo().maxLatency(mopCode);
167 SchedGraphNode::~SchedGraphNode()
169 // for each node, delete its out-edges
170 std::for_each(beginOutEdges(), endOutEdges(),
171 deleter<SchedGraphEdge>);
174 void SchedGraphNode::dump(int indent=0) const {
175 cerr << std::string(indent*2, ' ') << *this;
180 SchedGraphNode::addInEdge(SchedGraphEdge* edge)
182 inEdges.push_back(edge);
187 SchedGraphNode::addOutEdge(SchedGraphEdge* edge)
189 outEdges.push_back(edge);
193 SchedGraphNode::removeInEdge(const SchedGraphEdge* edge)
195 assert(edge->getSink() == this);
197 for (iterator I = beginInEdges(); I != endInEdges(); ++I)
206 SchedGraphNode::removeOutEdge(const SchedGraphEdge* edge)
208 assert(edge->getSrc() == this);
210 for (iterator I = beginOutEdges(); I != endOutEdges(); ++I)
225 SchedGraph::SchedGraph(const BasicBlock* bb,
226 const TargetMachine& target)
234 SchedGraph::~SchedGraph()
236 for (const_iterator I = begin(); I != end(); ++I)
244 SchedGraph::dump() const
246 cerr << " Sched Graph for Basic Blocks: ";
247 for (unsigned i=0, N=bbVec.size(); i < N; i++)
249 cerr << (bbVec[i]->hasName()? bbVec[i]->getName() : "block")
250 << " (" << bbVec[i] << ")"
251 << ((i == N-1)? "" : ", ");
254 cerr << "\n\n Actual Root nodes : ";
255 for (unsigned i=0, N=graphRoot->outEdges.size(); i < N; i++)
256 cerr << graphRoot->outEdges[i]->getSink()->getNodeId()
257 << ((i == N-1)? "" : ", ");
259 cerr << "\n Graph Nodes:\n";
260 for (const_iterator I=begin(); I != end(); ++I)
261 cerr << "\n" << *I->second;
268 SchedGraph::eraseIncomingEdges(SchedGraphNode* node, bool addDummyEdges)
270 // Delete and disconnect all in-edges for the node
271 for (SchedGraphNode::iterator I = node->beginInEdges();
272 I != node->endInEdges(); ++I)
274 SchedGraphNode* srcNode = (*I)->getSrc();
275 srcNode->removeOutEdge(*I);
279 srcNode != getRoot() &&
280 srcNode->beginOutEdges() == srcNode->endOutEdges())
281 { // srcNode has no more out edges, so add an edge to dummy EXIT node
282 assert(node != getLeaf() && "Adding edge that was just removed?");
283 (void) new SchedGraphEdge(srcNode, getLeaf(),
284 SchedGraphEdge::CtrlDep, SchedGraphEdge::NonDataDep, 0);
288 node->inEdges.clear();
292 SchedGraph::eraseOutgoingEdges(SchedGraphNode* node, bool addDummyEdges)
294 // Delete and disconnect all out-edges for the node
295 for (SchedGraphNode::iterator I = node->beginOutEdges();
296 I != node->endOutEdges(); ++I)
298 SchedGraphNode* sinkNode = (*I)->getSink();
299 sinkNode->removeInEdge(*I);
303 sinkNode != getLeaf() &&
304 sinkNode->beginInEdges() == sinkNode->endInEdges())
305 { //sinkNode has no more in edges, so add an edge from dummy ENTRY node
306 assert(node != getRoot() && "Adding edge that was just removed?");
307 (void) new SchedGraphEdge(getRoot(), sinkNode,
308 SchedGraphEdge::CtrlDep, SchedGraphEdge::NonDataDep, 0);
312 node->outEdges.clear();
316 SchedGraph::eraseIncidentEdges(SchedGraphNode* node, bool addDummyEdges)
318 this->eraseIncomingEdges(node, addDummyEdges);
319 this->eraseOutgoingEdges(node, addDummyEdges);
324 SchedGraph::addDummyEdges()
326 assert(graphRoot->outEdges.size() == 0);
328 for (const_iterator I=begin(); I != end(); ++I)
330 SchedGraphNode* node = (*I).second;
331 assert(node != graphRoot && node != graphLeaf);
332 if (node->beginInEdges() == node->endInEdges())
333 (void) new SchedGraphEdge(graphRoot, node, SchedGraphEdge::CtrlDep,
334 SchedGraphEdge::NonDataDep, 0);
335 if (node->beginOutEdges() == node->endOutEdges())
336 (void) new SchedGraphEdge(node, graphLeaf, SchedGraphEdge::CtrlDep,
337 SchedGraphEdge::NonDataDep, 0);
343 SchedGraph::addCDEdges(const TerminatorInst* term,
344 const TargetMachine& target)
346 const MachineInstrInfo& mii = target.getInstrInfo();
347 MachineCodeForInstruction &termMvec = MachineCodeForInstruction::get(term);
349 // Find the first branch instr in the sequence of machine instrs for term
352 while (!mii.isBranch(termMvec[first]->getOpCode()))
354 assert(first < termMvec.size() &&
355 "No branch instructions for BR? Ok, but weird! Delete assertion.");
356 if (first == termMvec.size())
359 SchedGraphNode* firstBrNode = this->getGraphNodeForInstr(termMvec[first]);
361 // Add CD edges from each instruction in the sequence to the
362 // *last preceding* branch instr. in the sequence
363 // Use a latency of 0 because we only need to prevent out-of-order issue.
365 for (int i = (int) termMvec.size()-1; i > (int) first; i--)
367 SchedGraphNode* toNode = this->getGraphNodeForInstr(termMvec[i]);
368 assert(toNode && "No node for instr generated for branch?");
370 for (int j = i-1; j >= 0; j--)
371 if (mii.isBranch(termMvec[j]->getOpCode()))
373 SchedGraphNode* brNode = this->getGraphNodeForInstr(termMvec[j]);
374 assert(brNode && "No node for instr generated for branch?");
375 (void) new SchedGraphEdge(brNode, toNode, SchedGraphEdge::CtrlDep,
376 SchedGraphEdge::NonDataDep, 0);
377 break; // only one incoming edge is enough
381 // Add CD edges from each instruction preceding the first branch
382 // to the first branch. Use a latency of 0 as above.
384 for (int i = first-1; i >= 0; i--)
386 SchedGraphNode* fromNode = this->getGraphNodeForInstr(termMvec[i]);
387 assert(fromNode && "No node for instr generated for branch?");
388 (void) new SchedGraphEdge(fromNode, firstBrNode, SchedGraphEdge::CtrlDep,
389 SchedGraphEdge::NonDataDep, 0);
392 // Now add CD edges to the first branch instruction in the sequence from
393 // all preceding instructions in the basic block. Use 0 latency again.
395 const BasicBlock* bb = firstBrNode->getBB();
396 const MachineCodeForBasicBlock& mvec = bb->getMachineInstrVec();
397 for (unsigned i=0, N=mvec.size(); i < N; i++)
399 if (mvec[i] == termMvec[first]) // reached the first branch
402 SchedGraphNode* fromNode = this->getGraphNodeForInstr(mvec[i]);
403 if (fromNode == NULL)
404 continue; // dummy instruction, e.g., PHI
406 (void) new SchedGraphEdge(fromNode, firstBrNode,
407 SchedGraphEdge::CtrlDep,
408 SchedGraphEdge::NonDataDep, 0);
410 // If we find any other machine instructions (other than due to
411 // the terminator) that also have delay slots, add an outgoing edge
412 // from the instruction to the instructions in the delay slots.
414 unsigned d = mii.getNumDelaySlots(mvec[i]->getOpCode());
415 assert(i+d < N && "Insufficient delay slots for instruction?");
417 for (unsigned j=1; j <= d; j++)
419 SchedGraphNode* toNode = this->getGraphNodeForInstr(mvec[i+j]);
420 assert(toNode && "No node for machine instr in delay slot?");
421 (void) new SchedGraphEdge(fromNode, toNode,
422 SchedGraphEdge::CtrlDep,
423 SchedGraphEdge::NonDataDep, 0);
428 static const int SG_LOAD_REF = 0;
429 static const int SG_STORE_REF = 1;
430 static const int SG_CALL_REF = 2;
432 static const unsigned int SG_DepOrderArray[][3] = {
433 { SchedGraphEdge::NonDataDep,
434 SchedGraphEdge::AntiDep,
435 SchedGraphEdge::AntiDep },
436 { SchedGraphEdge::TrueDep,
437 SchedGraphEdge::OutputDep,
438 SchedGraphEdge::TrueDep | SchedGraphEdge::OutputDep },
439 { SchedGraphEdge::TrueDep,
440 SchedGraphEdge::AntiDep | SchedGraphEdge::OutputDep,
441 SchedGraphEdge::TrueDep | SchedGraphEdge::AntiDep
442 | SchedGraphEdge::OutputDep }
446 // Add a dependence edge between every pair of machine load/store/call
447 // instructions, where at least one is a store or a call.
448 // Use latency 1 just to ensure that memory operations are ordered;
449 // latency does not otherwise matter (true dependences enforce that).
452 SchedGraph::addMemEdges(const vector<SchedGraphNode*>& memNodeVec,
453 const TargetMachine& target)
455 const MachineInstrInfo& mii = target.getInstrInfo();
457 // Instructions in memNodeVec are in execution order within the basic block,
458 // so simply look at all pairs <memNodeVec[i], memNodeVec[j: j > i]>.
460 for (unsigned im=0, NM=memNodeVec.size(); im < NM; im++)
462 MachineOpCode fromOpCode = memNodeVec[im]->getOpCode();
463 int fromType = mii.isCall(fromOpCode)? SG_CALL_REF
464 : mii.isLoad(fromOpCode)? SG_LOAD_REF
466 for (unsigned jm=im+1; jm < NM; jm++)
468 MachineOpCode toOpCode = memNodeVec[jm]->getOpCode();
469 int toType = mii.isCall(toOpCode)? SG_CALL_REF
470 : mii.isLoad(toOpCode)? SG_LOAD_REF
473 if (fromType != SG_LOAD_REF || toType != SG_LOAD_REF)
474 (void) new SchedGraphEdge(memNodeVec[im], memNodeVec[jm],
475 SchedGraphEdge::MemoryDep,
476 SG_DepOrderArray[fromType][toType], 1);
481 // Add edges from/to CC reg instrs to/from call instrs.
482 // Essentially this prevents anything that sets or uses a CC reg from being
483 // reordered w.r.t. a call.
484 // Use a latency of 0 because we only need to prevent out-of-order issue,
485 // like with control dependences.
488 SchedGraph::addCallCCEdges(const vector<SchedGraphNode*>& memNodeVec,
489 MachineCodeForBasicBlock& bbMvec,
490 const TargetMachine& target)
492 const MachineInstrInfo& mii = target.getInstrInfo();
493 vector<SchedGraphNode*> callNodeVec;
495 // Find the call instruction nodes and put them in a vector.
496 for (unsigned im=0, NM=memNodeVec.size(); im < NM; im++)
497 if (mii.isCall(memNodeVec[im]->getOpCode()))
498 callNodeVec.push_back(memNodeVec[im]);
500 // Now walk the entire basic block, looking for CC instructions *and*
501 // call instructions, and keep track of the order of the instructions.
502 // Use the call node vec to quickly find earlier and later call nodes
503 // relative to the current CC instruction.
505 int lastCallNodeIdx = -1;
506 for (unsigned i=0, N=bbMvec.size(); i < N; i++)
507 if (mii.isCall(bbMvec[i]->getOpCode()))
510 for ( ; lastCallNodeIdx < (int)callNodeVec.size(); ++lastCallNodeIdx)
511 if (callNodeVec[lastCallNodeIdx]->getMachineInstr() == bbMvec[i])
513 assert(lastCallNodeIdx < (int)callNodeVec.size() && "Missed Call?");
515 else if (mii.isCCInstr(bbMvec[i]->getOpCode()))
516 { // Add incoming/outgoing edges from/to preceding/later calls
517 SchedGraphNode* ccNode = this->getGraphNodeForInstr(bbMvec[i]);
519 for ( ; j <= lastCallNodeIdx; j++)
520 (void) new SchedGraphEdge(callNodeVec[j], ccNode,
521 MachineCCRegsRID, 0);
522 for ( ; j < (int) callNodeVec.size(); j++)
523 (void) new SchedGraphEdge(ccNode, callNodeVec[j],
524 MachineCCRegsRID, 0);
530 SchedGraph::addMachineRegEdges(RegToRefVecMap& regToRefVecMap,
531 const TargetMachine& target)
533 assert(bbVec.size() == 1 && "Only handling a single basic block here");
535 // This assumes that such hardwired registers are never allocated
536 // to any LLVM value (since register allocation happens later), i.e.,
537 // any uses or defs of this register have been made explicit!
538 // Also assumes that two registers with different numbers are
541 for (RegToRefVecMap::iterator I = regToRefVecMap.begin();
542 I != regToRefVecMap.end(); ++I)
544 int regNum = (*I).first;
545 RefVec& regRefVec = (*I).second;
547 // regRefVec is ordered by control flow order in the basic block
548 for (unsigned i=0; i < regRefVec.size(); ++i)
550 SchedGraphNode* node = regRefVec[i].first;
551 unsigned int opNum = regRefVec[i].second;
552 bool isDef = node->getMachineInstr()->operandIsDefined(opNum);
554 for (unsigned p=0; p < i; ++p)
556 SchedGraphNode* prevNode = regRefVec[p].first;
557 if (prevNode != node)
559 unsigned int prevOpNum = regRefVec[p].second;
561 prevNode->getMachineInstr()->operandIsDefined(prevOpNum);
564 new SchedGraphEdge(prevNode, node, regNum,
565 (prevIsDef)? SchedGraphEdge::OutputDep
566 : SchedGraphEdge::AntiDep);
568 new SchedGraphEdge(prevNode, node, regNum,
569 SchedGraphEdge::TrueDep);
578 SchedGraph::addEdgesForValue(SchedGraphNode* refNode,
579 const RefVec& defVec,
580 const Value* defValue,
582 const TargetMachine& target)
584 // Add true or output dep edges from all def nodes before refNode in BB.
585 // Add anti or output dep edges to all def nodes after refNode.
586 for (RefVec::const_iterator I=defVec.begin(), E=defVec.end(); I != E; ++I)
588 if ((*I).first == refNode)
589 continue; // Dont add any self-loops
591 if ((*I).first->getOrigIndexInBB() < refNode->getOrigIndexInBB())
592 // (*).first is before refNode
593 (void) new SchedGraphEdge((*I).first, refNode, defValue,
594 (refNodeIsDef)? SchedGraphEdge::OutputDep
595 : SchedGraphEdge::TrueDep);
597 // (*).first is after refNode
598 (void) new SchedGraphEdge(refNode, (*I).first, defValue,
599 (refNodeIsDef)? SchedGraphEdge::OutputDep
600 : SchedGraphEdge::AntiDep);
606 SchedGraph::addEdgesForInstruction(const MachineInstr& minstr,
607 const ValueToDefVecMap& valueToDefVecMap,
608 const TargetMachine& target)
610 SchedGraphNode* node = this->getGraphNodeForInstr(&minstr);
614 // Add edges for all operands of the machine instruction.
616 for (unsigned i=0, numOps=minstr.getNumOperands(); i < numOps; i++)
618 const MachineOperand& mop = minstr.getOperand(i);
619 switch(mop.getOperandType())
621 case MachineOperand::MO_VirtualRegister:
622 case MachineOperand::MO_CCRegister:
623 if (const Instruction* srcI =
624 dyn_cast_or_null<Instruction>(mop.getVRegValue()))
626 ValueToDefVecMap::const_iterator I = valueToDefVecMap.find(srcI);
627 if (I != valueToDefVecMap.end())
628 addEdgesForValue(node, (*I).second, mop.getVRegValue(),
629 minstr.operandIsDefined(i), target);
633 case MachineOperand::MO_MachineRegister:
636 case MachineOperand::MO_SignExtendedImmed:
637 case MachineOperand::MO_UnextendedImmed:
638 case MachineOperand::MO_PCRelativeDisp:
639 break; // nothing to do for immediate fields
642 assert(0 && "Unknown machine operand type in SchedGraph builder");
647 // Add edges for values implicitly used by the machine instruction.
648 // Examples include function arguments to a Call instructions or the return
649 // value of a Ret instruction.
651 for (unsigned i=0, N=minstr.getNumImplicitRefs(); i < N; ++i)
652 if (! minstr.implicitRefIsDefined(i))
653 if (const Instruction* srcI =
654 dyn_cast_or_null<Instruction>(minstr.getImplicitRef(i)))
656 ValueToDefVecMap::const_iterator I = valueToDefVecMap.find(srcI);
657 if (I != valueToDefVecMap.end())
658 addEdgesForValue(node, (*I).second, minstr.getImplicitRef(i),
659 minstr.implicitRefIsDefined(i), target);
664 #undef NEED_SEPARATE_NONSSA_EDGES_CODE
665 #ifdef NEED_SEPARATE_NONSSA_EDGES_CODE
667 SchedGraph::addNonSSAEdgesForValue(const Instruction* instr,
668 const TargetMachine& target)
670 if (isa<PHINode>(instr))
673 MachineCodeForVMInstr& mvec = instr->getMachineInstrVec();
674 const MachineInstrInfo& mii = target.getInstrInfo();
677 for (unsigned i=0, N=mvec.size(); i < N; i++)
678 for (int o=0, N = mii.getNumOperands(mvec[i]->getOpCode()); o < N; o++)
680 const MachineOperand& mop = mvec[i]->getOperand(o);
682 if ((mop.getOperandType() == MachineOperand::MO_VirtualRegister ||
683 mop.getOperandType() == MachineOperand::MO_CCRegister)
684 && mop.getVRegValue() == (Value*) instr)
686 // this operand is a definition or use of value `instr'
687 SchedGraphNode* node = this->getGraphNodeForInstr(mvec[i]);
688 assert(node && "No node for machine instruction in this BB?");
689 refVec.push_back(std::make_pair(node, o));
693 // refVec is ordered by control flow order of the machine instructions
694 for (unsigned i=0; i < refVec.size(); ++i)
696 SchedGraphNode* node = refVec[i].first;
697 unsigned int opNum = refVec[i].second;
698 bool isDef = node->getMachineInstr()->operandIsDefined(opNum);
701 // add output and/or anti deps to this definition
702 for (unsigned p=0; p < i; ++p)
704 SchedGraphNode* prevNode = refVec[p].first;
705 if (prevNode != node)
707 bool prevIsDef = prevNode->getMachineInstr()->
708 operandIsDefined(refVec[p].second);
709 new SchedGraphEdge(prevNode, node, SchedGraphEdge::ValueDep,
710 (prevIsDef)? SchedGraphEdge::OutputDep
711 : SchedGraphEdge::AntiDep);
716 #endif //NEED_SEPARATE_NONSSA_EDGES_CODE
720 SchedGraph::findDefUseInfoAtInstr(const TargetMachine& target,
721 SchedGraphNode* node,
722 vector<SchedGraphNode*>& memNodeVec,
723 RegToRefVecMap& regToRefVecMap,
724 ValueToDefVecMap& valueToDefVecMap)
726 const MachineInstrInfo& mii = target.getInstrInfo();
729 MachineOpCode opCode = node->getOpCode();
730 if (mii.isLoad(opCode) || mii.isStore(opCode) || mii.isCall(opCode))
731 memNodeVec.push_back(node);
733 // Collect the register references and value defs. for explicit operands
735 const MachineInstr& minstr = * node->getMachineInstr();
736 for (int i=0, numOps = (int) minstr.getNumOperands(); i < numOps; i++)
738 const MachineOperand& mop = minstr.getOperand(i);
740 // if this references a register other than the hardwired
741 // "zero" register, record the reference.
742 if (mop.getOperandType() == MachineOperand::MO_MachineRegister)
744 int regNum = mop.getMachineRegNum();
745 if (regNum != target.getRegInfo().getZeroRegNum())
746 regToRefVecMap[mop.getMachineRegNum()].push_back(
747 std::make_pair(node, i));
748 continue; // nothing more to do
751 // ignore all other non-def operands
752 if (! minstr.operandIsDefined(i))
755 // We must be defining a value.
756 assert((mop.getOperandType() == MachineOperand::MO_VirtualRegister ||
757 mop.getOperandType() == MachineOperand::MO_CCRegister)
758 && "Do not expect any other kind of operand to be defined!");
760 const Instruction* defInstr = cast<Instruction>(mop.getVRegValue());
761 valueToDefVecMap[defInstr].push_back(std::make_pair(node, i));
765 // Collect value defs. for implicit operands. The interface to extract
766 // them assumes they must be virtual registers!
768 for (int i=0, N = (int) minstr.getNumImplicitRefs(); i < N; ++i)
769 if (minstr.implicitRefIsDefined(i))
770 if (const Instruction* defInstr =
771 dyn_cast_or_null<Instruction>(minstr.getImplicitRef(i)))
773 valueToDefVecMap[defInstr].push_back(std::make_pair(node, -i));
779 SchedGraph::buildNodesforBB(const TargetMachine& target,
780 const BasicBlock* bb,
781 vector<SchedGraphNode*>& memNodeVec,
782 RegToRefVecMap& regToRefVecMap,
783 ValueToDefVecMap& valueToDefVecMap)
785 const MachineInstrInfo& mii = target.getInstrInfo();
787 // Build graph nodes for each VM instruction and gather def/use info.
788 // Do both those together in a single pass over all machine instructions.
789 const MachineCodeForBasicBlock& mvec = bb->getMachineInstrVec();
790 for (unsigned i=0; i < mvec.size(); i++)
791 if (! mii.isDummyPhiInstr(mvec[i]->getOpCode()))
793 SchedGraphNode* node = new SchedGraphNode(getNumNodes(), bb,
795 this->noteGraphNodeForInstr(mvec[i], node);
797 // Remember all register references and value defs
798 findDefUseInfoAtInstr(target, node,
799 memNodeVec, regToRefVecMap,valueToDefVecMap);
802 #undef REALLY_NEED_TO_SEARCH_SUCCESSOR_PHIS
803 #ifdef REALLY_NEED_TO_SEARCH_SUCCESSOR_PHIS
804 // This is a BIG UGLY HACK. IT NEEDS TO BE ELIMINATED.
805 // Look for copy instructions inserted in this BB due to Phi instructions
806 // in the successor BBs.
807 // There MUST be exactly one copy per Phi in successor nodes.
809 for (BasicBlock::succ_const_iterator SI=bb->succ_begin(), SE=bb->succ_end();
811 for (BasicBlock::const_iterator PI=(*SI)->begin(), PE=(*SI)->end();
814 if ((*PI)->getOpcode() != Instruction::PHINode)
815 break; // No more Phis in this successor
817 // Find the incoming value from block bb to block (*SI)
818 int bbIndex = cast<PHINode>(*PI)->getBasicBlockIndex(bb);
819 assert(bbIndex >= 0 && "But I know bb is a predecessor of (*SI)?");
820 Value* inVal = cast<PHINode>(*PI)->getIncomingValue(bbIndex);
821 assert(inVal != NULL && "There must be an in-value on every edge");
823 // Find the machine instruction that makes a copy of inval to (*PI).
824 // This must be in the current basic block (bb).
825 const MachineCodeForVMInstr& mvec = (*PI)->getMachineInstrVec();
826 const MachineInstr* theCopy = NULL;
827 for (unsigned i=0; i < mvec.size() && theCopy == NULL; i++)
828 if (! mii.isDummyPhiInstr(mvec[i]->getOpCode()))
829 // not a Phi: assume this is a copy and examine its operands
830 for (int o=0, N=(int) mvec[i]->getNumOperands(); o < N; o++)
832 const MachineOperand& mop = mvec[i]->getOperand(o);
833 if (mvec[i]->operandIsDefined(o))
834 assert(mop.getVRegValue() == (*PI) && "dest shd be my Phi");
835 else if (mop.getVRegValue() == inVal)
842 // Found the dang instruction. Now create a node and do the rest...
845 SchedGraphNode* node = new SchedGraphNode(getNumNodes(), bb,
846 theCopy, origIndexInBB++, target);
847 this->noteGraphNodeForInstr(theCopy, node);
848 findDefUseInfoAtInstr(target, node,
849 memNodeVec, regToRefVecMap,valueToDefVecMap);
852 #endif //REALLY_NEED_TO_SEARCH_SUCCESSOR_PHIS
857 SchedGraph::buildGraph(const TargetMachine& target)
859 const BasicBlock* bb = bbVec[0];
861 assert(bbVec.size() == 1 && "Only handling a single basic block here");
863 // Use this data structure to note all machine operands that compute
864 // ordinary LLVM values. These must be computed defs (i.e., instructions).
865 // Note that there may be multiple machine instructions that define
867 ValueToDefVecMap valueToDefVecMap;
869 // Use this data structure to note all memory instructions.
870 // We use this to add memory dependence edges without a second full walk.
872 // vector<const Instruction*> memVec;
873 vector<SchedGraphNode*> memNodeVec;
875 // Use this data structure to note any uses or definitions of
876 // machine registers so we can add edges for those later without
877 // extra passes over the nodes.
878 // The vector holds an ordered list of references to the machine reg,
879 // ordered according to control-flow order. This only works for a
880 // single basic block, hence the assertion. Each reference is identified
881 // by the pair: <node, operand-number>.
883 RegToRefVecMap regToRefVecMap;
885 // Make a dummy root node. We'll add edges to the real roots later.
886 graphRoot = new SchedGraphNode(0, NULL, NULL, -1, target);
887 graphLeaf = new SchedGraphNode(1, NULL, NULL, -1, target);
889 //----------------------------------------------------------------
890 // First add nodes for all the machine instructions in the basic block
891 // because this greatly simplifies identifying which edges to add.
892 // Do this one VM instruction at a time since the SchedGraphNode needs that.
893 // Also, remember the load/store instructions to add memory deps later.
894 //----------------------------------------------------------------
896 buildNodesforBB(target, bb, memNodeVec, regToRefVecMap, valueToDefVecMap);
898 //----------------------------------------------------------------
899 // Now add edges for the following (all are incoming edges except (4)):
900 // (1) operands of the machine instruction, including hidden operands
901 // (2) machine register dependences
902 // (3) memory load/store dependences
903 // (3) other resource dependences for the machine instruction, if any
904 // (4) output dependences when multiple machine instructions define the
905 // same value; all must have been generated from a single VM instrn
906 // (5) control dependences to branch instructions generated for the
907 // terminator instruction of the BB. Because of delay slots and
908 // 2-way conditional branches, multiple CD edges are needed
909 // (see addCDEdges for details).
910 // Also, note any uses or defs of machine registers.
912 //----------------------------------------------------------------
914 MachineCodeForBasicBlock& bbMvec = bb->getMachineInstrVec();
916 // First, add edges to the terminator instruction of the basic block.
917 this->addCDEdges(bb->getTerminator(), target);
919 // Then add memory dep edges: store->load, load->store, and store->store.
920 // Call instructions are treated as both load and store.
921 this->addMemEdges(memNodeVec, target);
923 // Then add edges between call instructions and CC set/use instructions
924 this->addCallCCEdges(memNodeVec, bbMvec, target);
926 // Then add incoming def-use (SSA) edges for each machine instruction.
927 for (unsigned i=0, N=bbMvec.size(); i < N; i++)
928 addEdgesForInstruction(*bbMvec[i], valueToDefVecMap, target);
930 #ifdef NEED_SEPARATE_NONSSA_EDGES_CODE
931 // Then add non-SSA edges for all VM instructions in the block.
932 // We assume that all machine instructions that define a value are
933 // generated from the VM instruction corresponding to that value.
934 // TODO: This could probably be done much more efficiently.
935 for (BasicBlock::const_iterator II = bb->begin(); II != bb->end(); ++II)
936 this->addNonSSAEdgesForValue(*II, target);
937 #endif //NEED_SEPARATE_NONSSA_EDGES_CODE
939 // Then add edges for dependences on machine registers
940 this->addMachineRegEdges(regToRefVecMap, target);
942 // Finally, add edges from the dummy root and to dummy leaf
943 this->addDummyEdges();
948 // class SchedGraphSet
952 SchedGraphSet::SchedGraphSet(const Function* _function,
953 const TargetMachine& target) :
956 buildGraphsForMethod(method, target);
961 SchedGraphSet::~SchedGraphSet()
963 // delete all the graphs
964 for(iterator I = begin(), E = end(); I != E; ++I)
965 delete *I; // destructor is a friend
970 SchedGraphSet::dump() const
972 cerr << "======== Sched graphs for function `" << method->getName()
975 for (const_iterator I=begin(); I != end(); ++I)
978 cerr << "\n====== End graphs for function `" << method->getName()
984 SchedGraphSet::buildGraphsForMethod(const Function *F,
985 const TargetMachine& target)
987 for (Function::const_iterator BI = F->begin(); BI != F->end(); ++BI)
988 addGraph(new SchedGraph(BI, target));
992 std::ostream &operator<<(std::ostream &os, const SchedGraphEdge& edge)
994 os << "edge [" << edge.src->getNodeId() << "] -> ["
995 << edge.sink->getNodeId() << "] : ";
997 switch(edge.depType) {
998 case SchedGraphEdge::CtrlDep: os<< "Control Dep"; break;
999 case SchedGraphEdge::ValueDep: os<< "Reg Value " << edge.val; break;
1000 case SchedGraphEdge::MemoryDep: os<< "Memory Dep"; break;
1001 case SchedGraphEdge::MachineRegister: os<< "Reg " <<edge.machineRegNum;break;
1002 case SchedGraphEdge::MachineResource: os<<"Resource "<<edge.resourceId;break;
1003 default: assert(0); break;
1006 os << " : delay = " << edge.minDelay << "\n";
1011 std::ostream &operator<<(std::ostream &os, const SchedGraphNode& node)
1013 os << std::string(8, ' ')
1014 << "Node " << node.nodeId << " : "
1015 << "latency = " << node.latency << "\n" << std::string(12, ' ');
1017 if (node.getMachineInstr() == NULL)
1018 os << "(Dummy node)\n";
1021 os << *node.getMachineInstr() << "\n" << std::string(12, ' ');
1022 os << node.inEdges.size() << " Incoming Edges:\n";
1023 for (unsigned i=0, N=node.inEdges.size(); i < N; i++)
1024 os << std::string(16, ' ') << *node.inEdges[i];
1026 os << std::string(12, ' ') << node.outEdges.size()
1027 << " Outgoing Edges:\n";
1028 for (unsigned i=0, N=node.outEdges.size(); i < N; i++)
1029 os << std::string(16, ' ') << *node.outEdges[i];