1 //===- SchedGraph.cpp - Scheduling Graph Implementation -------------------===//
3 // Scheduling graph based on SSA graph plus extra dependence edges capturing
4 // dependences due to machine resources (machine registers, CC registers, and
7 //===----------------------------------------------------------------------===//
9 #include "SchedGraph.h"
10 #include "llvm/CodeGen/InstrSelection.h"
11 #include "llvm/CodeGen/MachineCodeForInstruction.h"
12 #include "llvm/CodeGen/MachineFunction.h"
13 #include "llvm/Target/TargetRegInfo.h"
14 #include "llvm/Target/TargetMachine.h"
15 #include "llvm/Target/TargetInstrInfo.h"
16 #include "llvm/Function.h"
17 #include "llvm/iOther.h"
18 #include "Support/StringExtras.h"
19 #include "Support/STLExtras.h"
21 //*********************** Internal Data Structures *************************/
23 // The following two types need to be classes, not typedefs, so we can use
24 // opaque declarations in SchedGraph.h
26 struct RefVec: public std::vector<std::pair<SchedGraphNode*, int> > {
27 typedef std::vector<std::pair<SchedGraphNode*,int> >::iterator iterator;
29 std::vector<std::pair<SchedGraphNode*,int> >::const_iterator const_iterator;
32 struct RegToRefVecMap: public hash_map<int, RefVec> {
33 typedef hash_map<int, RefVec>:: iterator iterator;
34 typedef hash_map<int, RefVec>::const_iterator const_iterator;
37 struct ValueToDefVecMap: public hash_map<const Instruction*, RefVec> {
38 typedef hash_map<const Instruction*, RefVec>:: iterator iterator;
39 typedef hash_map<const Instruction*, RefVec>::const_iterator const_iterator;
43 // class SchedGraphEdge
47 SchedGraphEdge::SchedGraphEdge(SchedGraphNode* _src,
48 SchedGraphNode* _sink,
49 SchedGraphEdgeDepType _depType,
50 unsigned int _depOrderType,
55 depOrderType(_depOrderType),
56 minDelay((_minDelay >= 0)? _minDelay : _src->getLatency()),
59 assert(src != sink && "Self-loop in scheduling graph!");
60 src->addOutEdge(this);
61 sink->addInEdge(this);
66 SchedGraphEdge::SchedGraphEdge(SchedGraphNode* _src,
67 SchedGraphNode* _sink,
69 unsigned int _depOrderType,
74 depOrderType(_depOrderType),
75 minDelay((_minDelay >= 0)? _minDelay : _src->getLatency()),
78 assert(src != sink && "Self-loop in scheduling graph!");
79 src->addOutEdge(this);
80 sink->addInEdge(this);
85 SchedGraphEdge::SchedGraphEdge(SchedGraphNode* _src,
86 SchedGraphNode* _sink,
88 unsigned int _depOrderType,
92 depType(MachineRegister),
93 depOrderType(_depOrderType),
94 minDelay((_minDelay >= 0)? _minDelay : _src->getLatency()),
95 machineRegNum(_regNum)
97 assert(src != sink && "Self-loop in scheduling graph!");
98 src->addOutEdge(this);
99 sink->addInEdge(this);
104 SchedGraphEdge::SchedGraphEdge(SchedGraphNode* _src,
105 SchedGraphNode* _sink,
106 ResourceId _resourceId,
110 depType(MachineResource),
111 depOrderType(NonDataDep),
112 minDelay((_minDelay >= 0)? _minDelay : _src->getLatency()),
113 resourceId(_resourceId)
115 assert(src != sink && "Self-loop in scheduling graph!");
116 src->addOutEdge(this);
117 sink->addInEdge(this);
121 SchedGraphEdge::~SchedGraphEdge()
125 void SchedGraphEdge::dump(int indent) const {
126 std::cerr << std::string(indent*2, ' ') << *this;
131 // class SchedGraphNode
135 SchedGraphNode::SchedGraphNode(unsigned NID,
136 MachineBasicBlock *mbb,
138 const TargetMachine& Target)
139 : nodeId(NID), MBB(mbb), minstr(mbb ? (*mbb)[indexInBB] : 0),
140 origIndexInBB(indexInBB), latency(0) {
143 MachineOpCode mopCode = minstr->getOpCode();
144 latency = Target.getInstrInfo().hasResultInterlock(mopCode)
145 ? Target.getInstrInfo().minLatency(mopCode)
146 : Target.getInstrInfo().maxLatency(mopCode);
152 SchedGraphNode::~SchedGraphNode()
154 // for each node, delete its out-edges
155 std::for_each(beginOutEdges(), endOutEdges(),
156 deleter<SchedGraphEdge>);
159 void SchedGraphNode::dump(int indent) const {
160 std::cerr << std::string(indent*2, ' ') << *this;
165 SchedGraphNode::addInEdge(SchedGraphEdge* edge)
167 inEdges.push_back(edge);
172 SchedGraphNode::addOutEdge(SchedGraphEdge* edge)
174 outEdges.push_back(edge);
178 SchedGraphNode::removeInEdge(const SchedGraphEdge* edge)
180 assert(edge->getSink() == this);
182 for (iterator I = beginInEdges(); I != endInEdges(); ++I)
191 SchedGraphNode::removeOutEdge(const SchedGraphEdge* edge)
193 assert(edge->getSrc() == this);
195 for (iterator I = beginOutEdges(); I != endOutEdges(); ++I)
210 SchedGraph::SchedGraph(MachineBasicBlock &mbb, const TargetMachine& target)
217 SchedGraph::~SchedGraph()
219 for (const_iterator I = begin(); I != end(); ++I)
227 SchedGraph::dump() const
229 std::cerr << " Sched Graph for Basic Block: ";
230 std::cerr << MBB.getBasicBlock()->getName()
231 << " (" << MBB.getBasicBlock() << ")";
233 std::cerr << "\n\n Actual Root nodes : ";
234 for (unsigned i=0, N=graphRoot->outEdges.size(); i < N; i++)
235 std::cerr << graphRoot->outEdges[i]->getSink()->getNodeId()
236 << ((i == N-1)? "" : ", ");
238 std::cerr << "\n Graph Nodes:\n";
239 for (const_iterator I=begin(); I != end(); ++I)
240 std::cerr << "\n" << *I->second;
247 SchedGraph::eraseIncomingEdges(SchedGraphNode* node, bool addDummyEdges)
249 // Delete and disconnect all in-edges for the node
250 for (SchedGraphNode::iterator I = node->beginInEdges();
251 I != node->endInEdges(); ++I)
253 SchedGraphNode* srcNode = (*I)->getSrc();
254 srcNode->removeOutEdge(*I);
258 srcNode != getRoot() &&
259 srcNode->beginOutEdges() == srcNode->endOutEdges())
261 // srcNode has no more out edges, so add an edge to dummy EXIT node
262 assert(node != getLeaf() && "Adding edge that was just removed?");
263 (void) new SchedGraphEdge(srcNode, getLeaf(),
264 SchedGraphEdge::CtrlDep, SchedGraphEdge::NonDataDep, 0);
268 node->inEdges.clear();
272 SchedGraph::eraseOutgoingEdges(SchedGraphNode* node, bool addDummyEdges)
274 // Delete and disconnect all out-edges for the node
275 for (SchedGraphNode::iterator I = node->beginOutEdges();
276 I != node->endOutEdges(); ++I)
278 SchedGraphNode* sinkNode = (*I)->getSink();
279 sinkNode->removeInEdge(*I);
283 sinkNode != getLeaf() &&
284 sinkNode->beginInEdges() == sinkNode->endInEdges())
285 { //sinkNode has no more in edges, so add an edge from dummy ENTRY node
286 assert(node != getRoot() && "Adding edge that was just removed?");
287 (void) new SchedGraphEdge(getRoot(), sinkNode,
288 SchedGraphEdge::CtrlDep, SchedGraphEdge::NonDataDep, 0);
292 node->outEdges.clear();
296 SchedGraph::eraseIncidentEdges(SchedGraphNode* node, bool addDummyEdges)
298 this->eraseIncomingEdges(node, addDummyEdges);
299 this->eraseOutgoingEdges(node, addDummyEdges);
304 SchedGraph::addDummyEdges()
306 assert(graphRoot->outEdges.size() == 0);
308 for (const_iterator I=begin(); I != end(); ++I)
310 SchedGraphNode* node = (*I).second;
311 assert(node != graphRoot && node != graphLeaf);
312 if (node->beginInEdges() == node->endInEdges())
313 (void) new SchedGraphEdge(graphRoot, node, SchedGraphEdge::CtrlDep,
314 SchedGraphEdge::NonDataDep, 0);
315 if (node->beginOutEdges() == node->endOutEdges())
316 (void) new SchedGraphEdge(node, graphLeaf, SchedGraphEdge::CtrlDep,
317 SchedGraphEdge::NonDataDep, 0);
323 SchedGraph::addCDEdges(const TerminatorInst* term,
324 const TargetMachine& target)
326 const TargetInstrInfo& mii = target.getInstrInfo();
327 MachineCodeForInstruction &termMvec = MachineCodeForInstruction::get(term);
329 // Find the first branch instr in the sequence of machine instrs for term
332 while (! mii.isBranch(termMvec[first]->getOpCode()) &&
333 ! mii.isReturn(termMvec[first]->getOpCode()))
335 assert(first < termMvec.size() &&
336 "No branch instructions for terminator? Ok, but weird!");
337 if (first == termMvec.size())
340 SchedGraphNode* firstBrNode = getGraphNodeForInstr(termMvec[first]);
342 // Add CD edges from each instruction in the sequence to the
343 // *last preceding* branch instr. in the sequence
344 // Use a latency of 0 because we only need to prevent out-of-order issue.
346 for (unsigned i = termMvec.size(); i > first+1; --i)
348 SchedGraphNode* toNode = getGraphNodeForInstr(termMvec[i-1]);
349 assert(toNode && "No node for instr generated for branch/ret?");
351 for (unsigned j = i-1; j != 0; --j)
352 if (mii.isBranch(termMvec[j-1]->getOpCode()) ||
353 mii.isReturn(termMvec[j-1]->getOpCode()))
355 SchedGraphNode* brNode = getGraphNodeForInstr(termMvec[j-1]);
356 assert(brNode && "No node for instr generated for branch/ret?");
357 (void) new SchedGraphEdge(brNode, toNode, SchedGraphEdge::CtrlDep,
358 SchedGraphEdge::NonDataDep, 0);
359 break; // only one incoming edge is enough
363 // Add CD edges from each instruction preceding the first branch
364 // to the first branch. Use a latency of 0 as above.
366 for (unsigned i = first; i != 0; --i)
368 SchedGraphNode* fromNode = getGraphNodeForInstr(termMvec[i-1]);
369 assert(fromNode && "No node for instr generated for branch?");
370 (void) new SchedGraphEdge(fromNode, firstBrNode, SchedGraphEdge::CtrlDep,
371 SchedGraphEdge::NonDataDep, 0);
374 // Now add CD edges to the first branch instruction in the sequence from
375 // all preceding instructions in the basic block. Use 0 latency again.
377 for (unsigned i=0, N=MBB.size(); i < N; i++)
379 if (MBB[i] == termMvec[first]) // reached the first branch
382 SchedGraphNode* fromNode = this->getGraphNodeForInstr(MBB[i]);
383 if (fromNode == NULL)
384 continue; // dummy instruction, e.g., PHI
386 (void) new SchedGraphEdge(fromNode, firstBrNode,
387 SchedGraphEdge::CtrlDep,
388 SchedGraphEdge::NonDataDep, 0);
390 // If we find any other machine instructions (other than due to
391 // the terminator) that also have delay slots, add an outgoing edge
392 // from the instruction to the instructions in the delay slots.
394 unsigned d = mii.getNumDelaySlots(MBB[i]->getOpCode());
395 assert(i+d < N && "Insufficient delay slots for instruction?");
397 for (unsigned j=1; j <= d; j++)
399 SchedGraphNode* toNode = this->getGraphNodeForInstr(MBB[i+j]);
400 assert(toNode && "No node for machine instr in delay slot?");
401 (void) new SchedGraphEdge(fromNode, toNode,
402 SchedGraphEdge::CtrlDep,
403 SchedGraphEdge::NonDataDep, 0);
408 static const int SG_LOAD_REF = 0;
409 static const int SG_STORE_REF = 1;
410 static const int SG_CALL_REF = 2;
412 static const unsigned int SG_DepOrderArray[][3] = {
413 { SchedGraphEdge::NonDataDep,
414 SchedGraphEdge::AntiDep,
415 SchedGraphEdge::AntiDep },
416 { SchedGraphEdge::TrueDep,
417 SchedGraphEdge::OutputDep,
418 SchedGraphEdge::TrueDep | SchedGraphEdge::OutputDep },
419 { SchedGraphEdge::TrueDep,
420 SchedGraphEdge::AntiDep | SchedGraphEdge::OutputDep,
421 SchedGraphEdge::TrueDep | SchedGraphEdge::AntiDep
422 | SchedGraphEdge::OutputDep }
426 // Add a dependence edge between every pair of machine load/store/call
427 // instructions, where at least one is a store or a call.
428 // Use latency 1 just to ensure that memory operations are ordered;
429 // latency does not otherwise matter (true dependences enforce that).
432 SchedGraph::addMemEdges(const std::vector<SchedGraphNode*>& memNodeVec,
433 const TargetMachine& target)
435 const TargetInstrInfo& mii = target.getInstrInfo();
437 // Instructions in memNodeVec are in execution order within the basic block,
438 // so simply look at all pairs <memNodeVec[i], memNodeVec[j: j > i]>.
440 for (unsigned im=0, NM=memNodeVec.size(); im < NM; im++)
442 MachineOpCode fromOpCode = memNodeVec[im]->getOpCode();
443 int fromType = mii.isCall(fromOpCode)? SG_CALL_REF
444 : mii.isLoad(fromOpCode)? SG_LOAD_REF
446 for (unsigned jm=im+1; jm < NM; jm++)
448 MachineOpCode toOpCode = memNodeVec[jm]->getOpCode();
449 int toType = mii.isCall(toOpCode)? SG_CALL_REF
450 : mii.isLoad(toOpCode)? SG_LOAD_REF
453 if (fromType != SG_LOAD_REF || toType != SG_LOAD_REF)
454 (void) new SchedGraphEdge(memNodeVec[im], memNodeVec[jm],
455 SchedGraphEdge::MemoryDep,
456 SG_DepOrderArray[fromType][toType], 1);
461 // Add edges from/to CC reg instrs to/from call instrs.
462 // Essentially this prevents anything that sets or uses a CC reg from being
463 // reordered w.r.t. a call.
464 // Use a latency of 0 because we only need to prevent out-of-order issue,
465 // like with control dependences.
468 SchedGraph::addCallCCEdges(const std::vector<SchedGraphNode*>& memNodeVec,
469 MachineBasicBlock& bbMvec,
470 const TargetMachine& target)
472 const TargetInstrInfo& mii = target.getInstrInfo();
473 std::vector<SchedGraphNode*> callNodeVec;
475 // Find the call instruction nodes and put them in a vector.
476 for (unsigned im=0, NM=memNodeVec.size(); im < NM; im++)
477 if (mii.isCall(memNodeVec[im]->getOpCode()))
478 callNodeVec.push_back(memNodeVec[im]);
480 // Now walk the entire basic block, looking for CC instructions *and*
481 // call instructions, and keep track of the order of the instructions.
482 // Use the call node vec to quickly find earlier and later call nodes
483 // relative to the current CC instruction.
485 int lastCallNodeIdx = -1;
486 for (unsigned i=0, N=bbMvec.size(); i < N; i++)
487 if (mii.isCall(bbMvec[i]->getOpCode()))
490 for ( ; lastCallNodeIdx < (int)callNodeVec.size(); ++lastCallNodeIdx)
491 if (callNodeVec[lastCallNodeIdx]->getMachineInstr() == bbMvec[i])
493 assert(lastCallNodeIdx < (int)callNodeVec.size() && "Missed Call?");
494 } else if (mii.isCCInstr(bbMvec[i]->getOpCode())) {
495 // Add incoming/outgoing edges from/to preceding/later calls
496 SchedGraphNode* ccNode = this->getGraphNodeForInstr(bbMvec[i]);
498 for ( ; j <= lastCallNodeIdx; j++)
499 (void) new SchedGraphEdge(callNodeVec[j], ccNode,
500 MachineCCRegsRID, 0);
501 for ( ; j < (int) callNodeVec.size(); j++)
502 (void) new SchedGraphEdge(ccNode, callNodeVec[j],
503 MachineCCRegsRID, 0);
509 SchedGraph::addMachineRegEdges(RegToRefVecMap& regToRefVecMap,
510 const TargetMachine& target)
512 // This assumes that such hardwired registers are never allocated
513 // to any LLVM value (since register allocation happens later), i.e.,
514 // any uses or defs of this register have been made explicit!
515 // Also assumes that two registers with different numbers are
518 for (RegToRefVecMap::iterator I = regToRefVecMap.begin();
519 I != regToRefVecMap.end(); ++I)
521 int regNum = (*I).first;
522 RefVec& regRefVec = (*I).second;
524 // regRefVec is ordered by control flow order in the basic block
525 for (unsigned i=0; i < regRefVec.size(); ++i) {
526 SchedGraphNode* node = regRefVec[i].first;
527 unsigned int opNum = regRefVec[i].second;
528 bool isDef = node->getMachineInstr()->operandIsDefined(opNum);
530 node->getMachineInstr()->operandIsDefinedAndUsed(opNum);
532 for (unsigned p=0; p < i; ++p) {
533 SchedGraphNode* prevNode = regRefVec[p].first;
534 if (prevNode != node) {
535 unsigned int prevOpNum = regRefVec[p].second;
537 prevNode->getMachineInstr()->operandIsDefined(prevOpNum);
538 bool prevIsDefAndUse =
539 prevNode->getMachineInstr()->operandIsDefinedAndUsed(prevOpNum);
542 new SchedGraphEdge(prevNode, node, regNum,
543 SchedGraphEdge::OutputDep);
544 if (!prevIsDef || prevIsDefAndUse)
545 new SchedGraphEdge(prevNode, node, regNum,
546 SchedGraphEdge::AntiDep);
550 if (!isDef || isDefAndUse)
551 new SchedGraphEdge(prevNode, node, regNum,
552 SchedGraphEdge::TrueDep);
560 // Adds dependences to/from refNode from/to all other defs
561 // in the basic block. refNode may be a use, a def, or both.
562 // We do not consider other uses because we are not building use-use deps.
565 SchedGraph::addEdgesForValue(SchedGraphNode* refNode,
566 const RefVec& defVec,
567 const Value* defValue,
569 bool refNodeIsDefAndUse,
570 const TargetMachine& target)
572 bool refNodeIsUse = !refNodeIsDef || refNodeIsDefAndUse;
574 // Add true or output dep edges from all def nodes before refNode in BB.
575 // Add anti or output dep edges to all def nodes after refNode.
576 for (RefVec::const_iterator I=defVec.begin(), E=defVec.end(); I != E; ++I)
578 if ((*I).first == refNode)
579 continue; // Dont add any self-loops
581 if ((*I).first->getOrigIndexInBB() < refNode->getOrigIndexInBB()) {
582 // (*).first is before refNode
584 (void) new SchedGraphEdge((*I).first, refNode, defValue,
585 SchedGraphEdge::OutputDep);
587 (void) new SchedGraphEdge((*I).first, refNode, defValue,
588 SchedGraphEdge::TrueDep);
590 // (*).first is after refNode
592 (void) new SchedGraphEdge(refNode, (*I).first, defValue,
593 SchedGraphEdge::OutputDep);
595 (void) new SchedGraphEdge(refNode, (*I).first, defValue,
596 SchedGraphEdge::AntiDep);
603 SchedGraph::addEdgesForInstruction(const MachineInstr& MI,
604 const ValueToDefVecMap& valueToDefVecMap,
605 const TargetMachine& target)
607 SchedGraphNode* node = getGraphNodeForInstr(&MI);
611 // Add edges for all operands of the machine instruction.
613 for (unsigned i = 0, numOps = MI.getNumOperands(); i != numOps; ++i)
615 switch (MI.getOperandType(i))
617 case MachineOperand::MO_VirtualRegister:
618 case MachineOperand::MO_CCRegister:
619 if (const Instruction* srcI =
620 dyn_cast_or_null<Instruction>(MI.getOperand(i).getVRegValue()))
622 ValueToDefVecMap::const_iterator I = valueToDefVecMap.find(srcI);
623 if (I != valueToDefVecMap.end())
624 addEdgesForValue(node, I->second, srcI,
625 MI.operandIsDefined(i),
626 MI.operandIsDefinedAndUsed(i), target);
630 case MachineOperand::MO_MachineRegister:
633 case MachineOperand::MO_SignExtendedImmed:
634 case MachineOperand::MO_UnextendedImmed:
635 case MachineOperand::MO_PCRelativeDisp:
636 break; // nothing to do for immediate fields
639 assert(0 && "Unknown machine operand type in SchedGraph builder");
644 // Add edges for values implicitly used by the machine instruction.
645 // Examples include function arguments to a Call instructions or the return
646 // value of a Ret instruction.
648 for (unsigned i=0, N=MI.getNumImplicitRefs(); i < N; ++i)
649 if (! MI.implicitRefIsDefined(i) ||
650 MI.implicitRefIsDefinedAndUsed(i))
651 if (const Instruction *srcI =
652 dyn_cast_or_null<Instruction>(MI.getImplicitRef(i)))
654 ValueToDefVecMap::const_iterator I = valueToDefVecMap.find(srcI);
655 if (I != valueToDefVecMap.end())
656 addEdgesForValue(node, I->second, srcI,
657 MI.implicitRefIsDefined(i),
658 MI.implicitRefIsDefinedAndUsed(i), target);
664 SchedGraph::findDefUseInfoAtInstr(const TargetMachine& target,
665 SchedGraphNode* node,
666 std::vector<SchedGraphNode*>& memNodeVec,
667 RegToRefVecMap& regToRefVecMap,
668 ValueToDefVecMap& valueToDefVecMap)
670 const TargetInstrInfo& mii = target.getInstrInfo();
673 MachineOpCode opCode = node->getOpCode();
674 if (mii.isLoad(opCode) || mii.isStore(opCode) || mii.isCall(opCode))
675 memNodeVec.push_back(node);
677 // Collect the register references and value defs. for explicit operands
679 const MachineInstr& minstr = *node->getMachineInstr();
680 for (int i=0, numOps = (int) minstr.getNumOperands(); i < numOps; i++)
682 const MachineOperand& mop = minstr.getOperand(i);
684 // if this references a register other than the hardwired
685 // "zero" register, record the reference.
686 if (mop.getType() == MachineOperand::MO_MachineRegister)
688 int regNum = mop.getMachineRegNum();
689 if (regNum != target.getRegInfo().getZeroRegNum())
690 regToRefVecMap[mop.getMachineRegNum()]
691 .push_back(std::make_pair(node, i));
692 continue; // nothing more to do
695 // ignore all other non-def operands
696 if (! minstr.operandIsDefined(i))
699 // We must be defining a value.
700 assert((mop.getType() == MachineOperand::MO_VirtualRegister ||
701 mop.getType() == MachineOperand::MO_CCRegister)
702 && "Do not expect any other kind of operand to be defined!");
704 const Instruction* defInstr = cast<Instruction>(mop.getVRegValue());
705 valueToDefVecMap[defInstr].push_back(std::make_pair(node, i));
709 // Collect value defs. for implicit operands. The interface to extract
710 // them assumes they must be virtual registers!
712 for (unsigned i=0, N = minstr.getNumImplicitRefs(); i != N; ++i)
713 if (minstr.implicitRefIsDefined(i))
714 if (const Instruction* defInstr =
715 dyn_cast_or_null<Instruction>(minstr.getImplicitRef(i)))
716 valueToDefVecMap[defInstr].push_back(std::make_pair(node, -i));
721 SchedGraph::buildNodesForBB(const TargetMachine& target,
722 MachineBasicBlock& MBB,
723 std::vector<SchedGraphNode*>& memNodeVec,
724 RegToRefVecMap& regToRefVecMap,
725 ValueToDefVecMap& valueToDefVecMap)
727 const TargetInstrInfo& mii = target.getInstrInfo();
729 // Build graph nodes for each VM instruction and gather def/use info.
730 // Do both those together in a single pass over all machine instructions.
731 for (unsigned i=0; i < MBB.size(); i++)
732 if (!mii.isDummyPhiInstr(MBB[i]->getOpCode())) {
733 SchedGraphNode* node = new SchedGraphNode(getNumNodes(), &MBB, i, target);
734 noteGraphNodeForInstr(MBB[i], node);
736 // Remember all register references and value defs
737 findDefUseInfoAtInstr(target, node, memNodeVec, regToRefVecMap,
744 SchedGraph::buildGraph(const TargetMachine& target)
746 // Use this data structure to note all machine operands that compute
747 // ordinary LLVM values. These must be computed defs (i.e., instructions).
748 // Note that there may be multiple machine instructions that define
750 ValueToDefVecMap valueToDefVecMap;
752 // Use this data structure to note all memory instructions.
753 // We use this to add memory dependence edges without a second full walk.
755 // vector<const Instruction*> memVec;
756 std::vector<SchedGraphNode*> memNodeVec;
758 // Use this data structure to note any uses or definitions of
759 // machine registers so we can add edges for those later without
760 // extra passes over the nodes.
761 // The vector holds an ordered list of references to the machine reg,
762 // ordered according to control-flow order. This only works for a
763 // single basic block, hence the assertion. Each reference is identified
764 // by the pair: <node, operand-number>.
766 RegToRefVecMap regToRefVecMap;
768 // Make a dummy root node. We'll add edges to the real roots later.
769 graphRoot = new SchedGraphNode(0, NULL, -1, target);
770 graphLeaf = new SchedGraphNode(1, NULL, -1, target);
772 //----------------------------------------------------------------
773 // First add nodes for all the machine instructions in the basic block
774 // because this greatly simplifies identifying which edges to add.
775 // Do this one VM instruction at a time since the SchedGraphNode needs that.
776 // Also, remember the load/store instructions to add memory deps later.
777 //----------------------------------------------------------------
779 buildNodesForBB(target, MBB, memNodeVec, regToRefVecMap, valueToDefVecMap);
781 //----------------------------------------------------------------
782 // Now add edges for the following (all are incoming edges except (4)):
783 // (1) operands of the machine instruction, including hidden operands
784 // (2) machine register dependences
785 // (3) memory load/store dependences
786 // (3) other resource dependences for the machine instruction, if any
787 // (4) output dependences when multiple machine instructions define the
788 // same value; all must have been generated from a single VM instrn
789 // (5) control dependences to branch instructions generated for the
790 // terminator instruction of the BB. Because of delay slots and
791 // 2-way conditional branches, multiple CD edges are needed
792 // (see addCDEdges for details).
793 // Also, note any uses or defs of machine registers.
795 //----------------------------------------------------------------
797 // First, add edges to the terminator instruction of the basic block.
798 this->addCDEdges(MBB.getBasicBlock()->getTerminator(), target);
800 // Then add memory dep edges: store->load, load->store, and store->store.
801 // Call instructions are treated as both load and store.
802 this->addMemEdges(memNodeVec, target);
804 // Then add edges between call instructions and CC set/use instructions
805 this->addCallCCEdges(memNodeVec, MBB, target);
807 // Then add incoming def-use (SSA) edges for each machine instruction.
808 for (unsigned i=0, N=MBB.size(); i < N; i++)
809 addEdgesForInstruction(*MBB[i], valueToDefVecMap, target);
811 #ifdef NEED_SEPARATE_NONSSA_EDGES_CODE
812 // Then add non-SSA edges for all VM instructions in the block.
813 // We assume that all machine instructions that define a value are
814 // generated from the VM instruction corresponding to that value.
815 // TODO: This could probably be done much more efficiently.
816 for (BasicBlock::const_iterator II = bb->begin(); II != bb->end(); ++II)
817 this->addNonSSAEdgesForValue(*II, target);
818 #endif //NEED_SEPARATE_NONSSA_EDGES_CODE
820 // Then add edges for dependences on machine registers
821 this->addMachineRegEdges(regToRefVecMap, target);
823 // Finally, add edges from the dummy root and to dummy leaf
824 this->addDummyEdges();
829 // class SchedGraphSet
833 SchedGraphSet::SchedGraphSet(const Function* _function,
834 const TargetMachine& target) :
837 buildGraphsForMethod(method, target);
842 SchedGraphSet::~SchedGraphSet()
844 // delete all the graphs
845 for(iterator I = begin(), E = end(); I != E; ++I)
846 delete *I; // destructor is a friend
851 SchedGraphSet::dump() const
853 std::cerr << "======== Sched graphs for function `" << method->getName()
856 for (const_iterator I=begin(); I != end(); ++I)
859 std::cerr << "\n====== End graphs for function `" << method->getName()
865 SchedGraphSet::buildGraphsForMethod(const Function *F,
866 const TargetMachine& target)
868 MachineFunction &MF = MachineFunction::get(F);
869 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
870 addGraph(new SchedGraph(*I, target));
874 std::ostream &operator<<(std::ostream &os, const SchedGraphEdge& edge)
876 os << "edge [" << edge.src->getNodeId() << "] -> ["
877 << edge.sink->getNodeId() << "] : ";
879 switch(edge.depType) {
880 case SchedGraphEdge::CtrlDep: os<< "Control Dep"; break;
881 case SchedGraphEdge::ValueDep: os<< "Reg Value " << edge.val; break;
882 case SchedGraphEdge::MemoryDep: os<< "Memory Dep"; break;
883 case SchedGraphEdge::MachineRegister: os<< "Reg " <<edge.machineRegNum;break;
884 case SchedGraphEdge::MachineResource: os<<"Resource "<<edge.resourceId;break;
885 default: assert(0); break;
888 os << " : delay = " << edge.minDelay << "\n";
893 std::ostream &operator<<(std::ostream &os, const SchedGraphNode& node)
895 os << std::string(8, ' ')
896 << "Node " << node.nodeId << " : "
897 << "latency = " << node.latency << "\n" << std::string(12, ' ');
899 if (node.getMachineInstr() == NULL)
900 os << "(Dummy node)\n";
902 os << *node.getMachineInstr() << "\n" << std::string(12, ' ');
903 os << node.inEdges.size() << " Incoming Edges:\n";
904 for (unsigned i=0, N=node.inEdges.size(); i < N; i++)
905 os << std::string(16, ' ') << *node.inEdges[i];
907 os << std::string(12, ' ') << node.outEdges.size()
908 << " Outgoing Edges:\n";
909 for (unsigned i=0, N=node.outEdges.size(); i < N; i++)
910 os << std::string(16, ' ') << *node.outEdges[i];