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/MachineCodeForBasicBlock.h"
13 #include "llvm/Target/MachineRegInfo.h"
14 #include "llvm/Target/TargetMachine.h"
15 #include "llvm/Function.h"
16 #include "llvm/iOther.h"
17 #include "Support/StringExtras.h"
18 #include "Support/STLExtras.h"
24 //*********************** Internal Data Structures *************************/
26 // The following two types need to be classes, not typedefs, so we can use
27 // opaque declarations in SchedGraph.h
29 struct RefVec: public vector< pair<SchedGraphNode*, int> > {
30 typedef vector< pair<SchedGraphNode*, int> >:: iterator iterator;
31 typedef vector< pair<SchedGraphNode*, int> >::const_iterator const_iterator;
34 struct RegToRefVecMap: public hash_map<int, RefVec> {
35 typedef hash_map<int, RefVec>:: iterator iterator;
36 typedef hash_map<int, RefVec>::const_iterator const_iterator;
39 struct ValueToDefVecMap: public hash_map<const Instruction*, RefVec> {
40 typedef hash_map<const Instruction*, RefVec>:: iterator iterator;
41 typedef hash_map<const Instruction*, RefVec>::const_iterator const_iterator;
45 // class SchedGraphEdge
49 SchedGraphEdge::SchedGraphEdge(SchedGraphNode* _src,
50 SchedGraphNode* _sink,
51 SchedGraphEdgeDepType _depType,
52 unsigned int _depOrderType,
57 depOrderType(_depOrderType),
58 minDelay((_minDelay >= 0)? _minDelay : _src->getLatency()),
61 assert(src != sink && "Self-loop in scheduling graph!");
62 src->addOutEdge(this);
63 sink->addInEdge(this);
68 SchedGraphEdge::SchedGraphEdge(SchedGraphNode* _src,
69 SchedGraphNode* _sink,
71 unsigned int _depOrderType,
76 depOrderType(_depOrderType),
77 minDelay((_minDelay >= 0)? _minDelay : _src->getLatency()),
80 assert(src != sink && "Self-loop in scheduling graph!");
81 src->addOutEdge(this);
82 sink->addInEdge(this);
87 SchedGraphEdge::SchedGraphEdge(SchedGraphNode* _src,
88 SchedGraphNode* _sink,
90 unsigned int _depOrderType,
94 depType(MachineRegister),
95 depOrderType(_depOrderType),
96 minDelay((_minDelay >= 0)? _minDelay : _src->getLatency()),
97 machineRegNum(_regNum)
99 assert(src != sink && "Self-loop in scheduling graph!");
100 src->addOutEdge(this);
101 sink->addInEdge(this);
106 SchedGraphEdge::SchedGraphEdge(SchedGraphNode* _src,
107 SchedGraphNode* _sink,
108 ResourceId _resourceId,
112 depType(MachineResource),
113 depOrderType(NonDataDep),
114 minDelay((_minDelay >= 0)? _minDelay : _src->getLatency()),
115 resourceId(_resourceId)
117 assert(src != sink && "Self-loop in scheduling graph!");
118 src->addOutEdge(this);
119 sink->addInEdge(this);
123 SchedGraphEdge::~SchedGraphEdge()
127 void SchedGraphEdge::dump(int indent) const {
128 cerr << std::string(indent*2, ' ') << *this;
133 // class SchedGraphNode
137 SchedGraphNode::SchedGraphNode(unsigned int _nodeId,
138 const BasicBlock* _bb,
139 const MachineInstr* _minstr,
141 const TargetMachine& target)
145 origIndexInBB(indexInBB),
150 MachineOpCode mopCode = minstr->getOpCode();
151 latency = target.getInstrInfo().hasResultInterlock(mopCode)
152 ? target.getInstrInfo().minLatency(mopCode)
153 : target.getInstrInfo().maxLatency(mopCode);
159 SchedGraphNode::~SchedGraphNode()
161 // for each node, delete its out-edges
162 std::for_each(beginOutEdges(), endOutEdges(),
163 deleter<SchedGraphEdge>);
166 void SchedGraphNode::dump(int indent) const {
167 cerr << std::string(indent*2, ' ') << *this;
172 SchedGraphNode::addInEdge(SchedGraphEdge* edge)
174 inEdges.push_back(edge);
179 SchedGraphNode::addOutEdge(SchedGraphEdge* edge)
181 outEdges.push_back(edge);
185 SchedGraphNode::removeInEdge(const SchedGraphEdge* edge)
187 assert(edge->getSink() == this);
189 for (iterator I = beginInEdges(); I != endInEdges(); ++I)
198 SchedGraphNode::removeOutEdge(const SchedGraphEdge* edge)
200 assert(edge->getSrc() == this);
202 for (iterator I = beginOutEdges(); I != endOutEdges(); ++I)
217 SchedGraph::SchedGraph(const BasicBlock* bb,
218 const TargetMachine& target)
226 SchedGraph::~SchedGraph()
228 for (const_iterator I = begin(); I != end(); ++I)
236 SchedGraph::dump() const
238 cerr << " Sched Graph for Basic Blocks: ";
239 for (unsigned i=0, N=bbVec.size(); i < N; i++)
241 cerr << (bbVec[i]->hasName()? bbVec[i]->getName() : "block")
242 << " (" << bbVec[i] << ")"
243 << ((i == N-1)? "" : ", ");
246 cerr << "\n\n Actual Root nodes : ";
247 for (unsigned i=0, N=graphRoot->outEdges.size(); i < N; i++)
248 cerr << graphRoot->outEdges[i]->getSink()->getNodeId()
249 << ((i == N-1)? "" : ", ");
251 cerr << "\n Graph Nodes:\n";
252 for (const_iterator I=begin(); I != end(); ++I)
253 cerr << "\n" << *I->second;
260 SchedGraph::eraseIncomingEdges(SchedGraphNode* node, bool addDummyEdges)
262 // Delete and disconnect all in-edges for the node
263 for (SchedGraphNode::iterator I = node->beginInEdges();
264 I != node->endInEdges(); ++I)
266 SchedGraphNode* srcNode = (*I)->getSrc();
267 srcNode->removeOutEdge(*I);
271 srcNode != getRoot() &&
272 srcNode->beginOutEdges() == srcNode->endOutEdges())
273 { // srcNode has no more out edges, so add an edge to dummy EXIT node
274 assert(node != getLeaf() && "Adding edge that was just removed?");
275 (void) new SchedGraphEdge(srcNode, getLeaf(),
276 SchedGraphEdge::CtrlDep, SchedGraphEdge::NonDataDep, 0);
280 node->inEdges.clear();
284 SchedGraph::eraseOutgoingEdges(SchedGraphNode* node, bool addDummyEdges)
286 // Delete and disconnect all out-edges for the node
287 for (SchedGraphNode::iterator I = node->beginOutEdges();
288 I != node->endOutEdges(); ++I)
290 SchedGraphNode* sinkNode = (*I)->getSink();
291 sinkNode->removeInEdge(*I);
295 sinkNode != getLeaf() &&
296 sinkNode->beginInEdges() == sinkNode->endInEdges())
297 { //sinkNode has no more in edges, so add an edge from dummy ENTRY node
298 assert(node != getRoot() && "Adding edge that was just removed?");
299 (void) new SchedGraphEdge(getRoot(), sinkNode,
300 SchedGraphEdge::CtrlDep, SchedGraphEdge::NonDataDep, 0);
304 node->outEdges.clear();
308 SchedGraph::eraseIncidentEdges(SchedGraphNode* node, bool addDummyEdges)
310 this->eraseIncomingEdges(node, addDummyEdges);
311 this->eraseOutgoingEdges(node, addDummyEdges);
316 SchedGraph::addDummyEdges()
318 assert(graphRoot->outEdges.size() == 0);
320 for (const_iterator I=begin(); I != end(); ++I)
322 SchedGraphNode* node = (*I).second;
323 assert(node != graphRoot && node != graphLeaf);
324 if (node->beginInEdges() == node->endInEdges())
325 (void) new SchedGraphEdge(graphRoot, node, SchedGraphEdge::CtrlDep,
326 SchedGraphEdge::NonDataDep, 0);
327 if (node->beginOutEdges() == node->endOutEdges())
328 (void) new SchedGraphEdge(node, graphLeaf, SchedGraphEdge::CtrlDep,
329 SchedGraphEdge::NonDataDep, 0);
335 SchedGraph::addCDEdges(const TerminatorInst* term,
336 const TargetMachine& target)
338 const MachineInstrInfo& mii = target.getInstrInfo();
339 MachineCodeForInstruction &termMvec = MachineCodeForInstruction::get(term);
341 // Find the first branch instr in the sequence of machine instrs for term
344 while (!mii.isBranch(termMvec[first]->getOpCode()))
346 assert(first < termMvec.size() &&
347 "No branch instructions for BR? Ok, but weird! Delete assertion.");
348 if (first == termMvec.size())
351 SchedGraphNode* firstBrNode = getGraphNodeForInstr(termMvec[first]);
353 // Add CD edges from each instruction in the sequence to the
354 // *last preceding* branch instr. in the sequence
355 // Use a latency of 0 because we only need to prevent out-of-order issue.
357 for (unsigned i = termMvec.size(); i > first+1; --i)
359 SchedGraphNode* toNode = getGraphNodeForInstr(termMvec[i-1]);
360 assert(toNode && "No node for instr generated for branch?");
362 for (unsigned j = i-1; j != 0; --j)
363 if (mii.isBranch(termMvec[j-1]->getOpCode()))
365 SchedGraphNode* brNode = getGraphNodeForInstr(termMvec[j-1]);
366 assert(brNode && "No node for instr generated for branch?");
367 (void) new SchedGraphEdge(brNode, toNode, SchedGraphEdge::CtrlDep,
368 SchedGraphEdge::NonDataDep, 0);
369 break; // only one incoming edge is enough
373 // Add CD edges from each instruction preceding the first branch
374 // to the first branch. Use a latency of 0 as above.
376 for (unsigned i = first; i != 0; --i)
378 SchedGraphNode* fromNode = getGraphNodeForInstr(termMvec[i-1]);
379 assert(fromNode && "No node for instr generated for branch?");
380 (void) new SchedGraphEdge(fromNode, firstBrNode, SchedGraphEdge::CtrlDep,
381 SchedGraphEdge::NonDataDep, 0);
384 // Now add CD edges to the first branch instruction in the sequence from
385 // all preceding instructions in the basic block. Use 0 latency again.
387 const BasicBlock* bb = firstBrNode->getBB();
388 const MachineCodeForBasicBlock& mvec = MachineCodeForBasicBlock::get(bb);
389 for (unsigned i=0, N=mvec.size(); i < N; i++)
391 if (mvec[i] == termMvec[first]) // reached the first branch
394 SchedGraphNode* fromNode = this->getGraphNodeForInstr(mvec[i]);
395 if (fromNode == NULL)
396 continue; // dummy instruction, e.g., PHI
398 (void) new SchedGraphEdge(fromNode, firstBrNode,
399 SchedGraphEdge::CtrlDep,
400 SchedGraphEdge::NonDataDep, 0);
402 // If we find any other machine instructions (other than due to
403 // the terminator) that also have delay slots, add an outgoing edge
404 // from the instruction to the instructions in the delay slots.
406 unsigned d = mii.getNumDelaySlots(mvec[i]->getOpCode());
407 assert(i+d < N && "Insufficient delay slots for instruction?");
409 for (unsigned j=1; j <= d; j++)
411 SchedGraphNode* toNode = this->getGraphNodeForInstr(mvec[i+j]);
412 assert(toNode && "No node for machine instr in delay slot?");
413 (void) new SchedGraphEdge(fromNode, toNode,
414 SchedGraphEdge::CtrlDep,
415 SchedGraphEdge::NonDataDep, 0);
420 static const int SG_LOAD_REF = 0;
421 static const int SG_STORE_REF = 1;
422 static const int SG_CALL_REF = 2;
424 static const unsigned int SG_DepOrderArray[][3] = {
425 { SchedGraphEdge::NonDataDep,
426 SchedGraphEdge::AntiDep,
427 SchedGraphEdge::AntiDep },
428 { SchedGraphEdge::TrueDep,
429 SchedGraphEdge::OutputDep,
430 SchedGraphEdge::TrueDep | SchedGraphEdge::OutputDep },
431 { SchedGraphEdge::TrueDep,
432 SchedGraphEdge::AntiDep | SchedGraphEdge::OutputDep,
433 SchedGraphEdge::TrueDep | SchedGraphEdge::AntiDep
434 | SchedGraphEdge::OutputDep }
438 // Add a dependence edge between every pair of machine load/store/call
439 // instructions, where at least one is a store or a call.
440 // Use latency 1 just to ensure that memory operations are ordered;
441 // latency does not otherwise matter (true dependences enforce that).
444 SchedGraph::addMemEdges(const vector<SchedGraphNode*>& memNodeVec,
445 const TargetMachine& target)
447 const MachineInstrInfo& mii = target.getInstrInfo();
449 // Instructions in memNodeVec are in execution order within the basic block,
450 // so simply look at all pairs <memNodeVec[i], memNodeVec[j: j > i]>.
452 for (unsigned im=0, NM=memNodeVec.size(); im < NM; im++)
454 MachineOpCode fromOpCode = memNodeVec[im]->getOpCode();
455 int fromType = mii.isCall(fromOpCode)? SG_CALL_REF
456 : mii.isLoad(fromOpCode)? SG_LOAD_REF
458 for (unsigned jm=im+1; jm < NM; jm++)
460 MachineOpCode toOpCode = memNodeVec[jm]->getOpCode();
461 int toType = mii.isCall(toOpCode)? SG_CALL_REF
462 : mii.isLoad(toOpCode)? SG_LOAD_REF
465 if (fromType != SG_LOAD_REF || toType != SG_LOAD_REF)
466 (void) new SchedGraphEdge(memNodeVec[im], memNodeVec[jm],
467 SchedGraphEdge::MemoryDep,
468 SG_DepOrderArray[fromType][toType], 1);
473 // Add edges from/to CC reg instrs to/from call instrs.
474 // Essentially this prevents anything that sets or uses a CC reg from being
475 // reordered w.r.t. a call.
476 // Use a latency of 0 because we only need to prevent out-of-order issue,
477 // like with control dependences.
480 SchedGraph::addCallCCEdges(const vector<SchedGraphNode*>& memNodeVec,
481 MachineCodeForBasicBlock& bbMvec,
482 const TargetMachine& target)
484 const MachineInstrInfo& mii = target.getInstrInfo();
485 vector<SchedGraphNode*> callNodeVec;
487 // Find the call instruction nodes and put them in a vector.
488 for (unsigned im=0, NM=memNodeVec.size(); im < NM; im++)
489 if (mii.isCall(memNodeVec[im]->getOpCode()))
490 callNodeVec.push_back(memNodeVec[im]);
492 // Now walk the entire basic block, looking for CC instructions *and*
493 // call instructions, and keep track of the order of the instructions.
494 // Use the call node vec to quickly find earlier and later call nodes
495 // relative to the current CC instruction.
497 int lastCallNodeIdx = -1;
498 for (unsigned i=0, N=bbMvec.size(); i < N; i++)
499 if (mii.isCall(bbMvec[i]->getOpCode()))
502 for ( ; lastCallNodeIdx < (int)callNodeVec.size(); ++lastCallNodeIdx)
503 if (callNodeVec[lastCallNodeIdx]->getMachineInstr() == bbMvec[i])
505 assert(lastCallNodeIdx < (int)callNodeVec.size() && "Missed Call?");
507 else if (mii.isCCInstr(bbMvec[i]->getOpCode()))
508 { // Add incoming/outgoing edges from/to preceding/later calls
509 SchedGraphNode* ccNode = this->getGraphNodeForInstr(bbMvec[i]);
511 for ( ; j <= lastCallNodeIdx; j++)
512 (void) new SchedGraphEdge(callNodeVec[j], ccNode,
513 MachineCCRegsRID, 0);
514 for ( ; j < (int) callNodeVec.size(); j++)
515 (void) new SchedGraphEdge(ccNode, callNodeVec[j],
516 MachineCCRegsRID, 0);
522 SchedGraph::addMachineRegEdges(RegToRefVecMap& regToRefVecMap,
523 const TargetMachine& target)
525 assert(bbVec.size() == 1 && "Only handling a single basic block here");
527 // This assumes that such hardwired registers are never allocated
528 // to any LLVM value (since register allocation happens later), i.e.,
529 // any uses or defs of this register have been made explicit!
530 // Also assumes that two registers with different numbers are
533 for (RegToRefVecMap::iterator I = regToRefVecMap.begin();
534 I != regToRefVecMap.end(); ++I)
536 int regNum = (*I).first;
537 RefVec& regRefVec = (*I).second;
539 // regRefVec is ordered by control flow order in the basic block
540 for (unsigned i=0; i < regRefVec.size(); ++i)
542 SchedGraphNode* node = regRefVec[i].first;
543 unsigned int opNum = regRefVec[i].second;
544 bool isDef = node->getMachineInstr()->operandIsDefined(opNum);
546 node->getMachineInstr()->operandIsDefinedAndUsed(opNum);
548 for (unsigned p=0; p < i; ++p)
550 SchedGraphNode* prevNode = regRefVec[p].first;
551 if (prevNode != node)
553 unsigned int prevOpNum = regRefVec[p].second;
555 prevNode->getMachineInstr()->operandIsDefined(prevOpNum);
556 bool prevIsDefAndUse =
557 prevNode->getMachineInstr()->operandIsDefinedAndUsed(prevOpNum);
561 new SchedGraphEdge(prevNode, node, regNum,
562 SchedGraphEdge::OutputDep);
563 if (!prevIsDef || prevIsDefAndUse)
564 new SchedGraphEdge(prevNode, node, regNum,
565 SchedGraphEdge::AntiDep);
569 if (!isDef || isDefAndUse)
570 new SchedGraphEdge(prevNode, node, regNum,
571 SchedGraphEdge::TrueDep);
579 // Adds dependences to/from refNode from/to all other defs
580 // in the basic block. refNode may be a use, a def, or both.
581 // We do not consider other uses because we are not building use-use deps.
584 SchedGraph::addEdgesForValue(SchedGraphNode* refNode,
585 const RefVec& defVec,
586 const Value* defValue,
588 bool refNodeIsDefAndUse,
589 const TargetMachine& target)
591 bool refNodeIsUse = !refNodeIsDef || refNodeIsDefAndUse;
593 // Add true or output dep edges from all def nodes before refNode in BB.
594 // Add anti or output dep edges to all def nodes after refNode.
595 for (RefVec::const_iterator I=defVec.begin(), E=defVec.end(); I != E; ++I)
597 if ((*I).first == refNode)
598 continue; // Dont add any self-loops
600 if ((*I).first->getOrigIndexInBB() < refNode->getOrigIndexInBB())
601 { // (*).first is before refNode
603 (void) new SchedGraphEdge((*I).first, refNode, defValue,
604 SchedGraphEdge::OutputDep);
606 (void) new SchedGraphEdge((*I).first, refNode, defValue,
607 SchedGraphEdge::TrueDep);
610 { // (*).first is after refNode
612 (void) new SchedGraphEdge(refNode, (*I).first, defValue,
613 SchedGraphEdge::OutputDep);
615 (void) new SchedGraphEdge(refNode, (*I).first, defValue,
616 SchedGraphEdge::AntiDep);
623 SchedGraph::addEdgesForInstruction(const MachineInstr& minstr,
624 const ValueToDefVecMap& valueToDefVecMap,
625 const TargetMachine& target)
627 SchedGraphNode* node = this->getGraphNodeForInstr(&minstr);
631 // Add edges for all operands of the machine instruction.
633 for (unsigned i=0, numOps=minstr.getNumOperands(); i < numOps; i++)
635 const MachineOperand& mop = minstr.getOperand(i);
636 switch(mop.getOperandType())
638 case MachineOperand::MO_VirtualRegister:
639 case MachineOperand::MO_CCRegister:
640 if (const Instruction* srcI =
641 dyn_cast_or_null<Instruction>(mop.getVRegValue()))
643 ValueToDefVecMap::const_iterator I = valueToDefVecMap.find(srcI);
644 if (I != valueToDefVecMap.end())
645 addEdgesForValue(node, (*I).second, mop.getVRegValue(),
646 minstr.operandIsDefined(i),
647 minstr.operandIsDefinedAndUsed(i), target);
651 case MachineOperand::MO_MachineRegister:
654 case MachineOperand::MO_SignExtendedImmed:
655 case MachineOperand::MO_UnextendedImmed:
656 case MachineOperand::MO_PCRelativeDisp:
657 break; // nothing to do for immediate fields
660 assert(0 && "Unknown machine operand type in SchedGraph builder");
665 // Add edges for values implicitly used by the machine instruction.
666 // Examples include function arguments to a Call instructions or the return
667 // value of a Ret instruction.
669 for (unsigned i=0, N=minstr.getNumImplicitRefs(); i < N; ++i)
670 if (! minstr.implicitRefIsDefined(i) ||
671 minstr.implicitRefIsDefinedAndUsed(i))
672 if (const Instruction* srcI =
673 dyn_cast_or_null<Instruction>(minstr.getImplicitRef(i)))
675 ValueToDefVecMap::const_iterator I = valueToDefVecMap.find(srcI);
676 if (I != valueToDefVecMap.end())
677 addEdgesForValue(node, (*I).second, minstr.getImplicitRef(i),
678 minstr.implicitRefIsDefined(i),
679 minstr.implicitRefIsDefinedAndUsed(i), target);
685 SchedGraph::findDefUseInfoAtInstr(const TargetMachine& target,
686 SchedGraphNode* node,
687 vector<SchedGraphNode*>& memNodeVec,
688 RegToRefVecMap& regToRefVecMap,
689 ValueToDefVecMap& valueToDefVecMap)
691 const MachineInstrInfo& mii = target.getInstrInfo();
694 MachineOpCode opCode = node->getOpCode();
695 if (mii.isLoad(opCode) || mii.isStore(opCode) || mii.isCall(opCode))
696 memNodeVec.push_back(node);
698 // Collect the register references and value defs. for explicit operands
700 const MachineInstr& minstr = * node->getMachineInstr();
701 for (int i=0, numOps = (int) minstr.getNumOperands(); i < numOps; i++)
703 const MachineOperand& mop = minstr.getOperand(i);
705 // if this references a register other than the hardwired
706 // "zero" register, record the reference.
707 if (mop.getOperandType() == MachineOperand::MO_MachineRegister)
709 int regNum = mop.getMachineRegNum();
710 if (regNum != target.getRegInfo().getZeroRegNum())
711 regToRefVecMap[mop.getMachineRegNum()].push_back(
712 std::make_pair(node, i));
713 continue; // nothing more to do
716 // ignore all other non-def operands
717 if (! minstr.operandIsDefined(i))
720 // We must be defining a value.
721 assert((mop.getOperandType() == MachineOperand::MO_VirtualRegister ||
722 mop.getOperandType() == MachineOperand::MO_CCRegister)
723 && "Do not expect any other kind of operand to be defined!");
725 const Instruction* defInstr = cast<Instruction>(mop.getVRegValue());
726 valueToDefVecMap[defInstr].push_back(std::make_pair(node, i));
730 // Collect value defs. for implicit operands. The interface to extract
731 // them assumes they must be virtual registers!
733 for (int i=0, N = (int) minstr.getNumImplicitRefs(); i < N; ++i)
734 if (minstr.implicitRefIsDefined(i))
735 if (const Instruction* defInstr =
736 dyn_cast_or_null<Instruction>(minstr.getImplicitRef(i)))
738 valueToDefVecMap[defInstr].push_back(std::make_pair(node, -i));
744 SchedGraph::buildNodesforBB(const TargetMachine& target,
745 const BasicBlock* bb,
746 vector<SchedGraphNode*>& memNodeVec,
747 RegToRefVecMap& regToRefVecMap,
748 ValueToDefVecMap& valueToDefVecMap)
750 const MachineInstrInfo& mii = target.getInstrInfo();
752 // Build graph nodes for each VM instruction and gather def/use info.
753 // Do both those together in a single pass over all machine instructions.
754 const MachineCodeForBasicBlock& mvec = MachineCodeForBasicBlock::get(bb);
755 for (unsigned i=0; i < mvec.size(); i++)
756 if (! mii.isDummyPhiInstr(mvec[i]->getOpCode()))
758 SchedGraphNode* node = new SchedGraphNode(getNumNodes(), bb,
760 this->noteGraphNodeForInstr(mvec[i], node);
762 // Remember all register references and value defs
763 findDefUseInfoAtInstr(target, node,
764 memNodeVec, regToRefVecMap,valueToDefVecMap);
767 #undef REALLY_NEED_TO_SEARCH_SUCCESSOR_PHIS
768 #ifdef REALLY_NEED_TO_SEARCH_SUCCESSOR_PHIS
769 // This is a BIG UGLY HACK. IT NEEDS TO BE ELIMINATED.
770 // Look for copy instructions inserted in this BB due to Phi instructions
771 // in the successor BBs.
772 // There MUST be exactly one copy per Phi in successor nodes.
774 for (BasicBlock::succ_const_iterator SI=bb->succ_begin(), SE=bb->succ_end();
776 for (BasicBlock::const_iterator PI=(*SI)->begin(), PE=(*SI)->end();
779 if ((*PI)->getOpcode() != Instruction::PHINode)
780 break; // No more Phis in this successor
782 // Find the incoming value from block bb to block (*SI)
783 int bbIndex = cast<PHINode>(*PI)->getBasicBlockIndex(bb);
784 assert(bbIndex >= 0 && "But I know bb is a predecessor of (*SI)?");
785 Value* inVal = cast<PHINode>(*PI)->getIncomingValue(bbIndex);
786 assert(inVal != NULL && "There must be an in-value on every edge");
788 // Find the machine instruction that makes a copy of inval to (*PI).
789 // This must be in the current basic block (bb).
790 const MachineCodeForVMInstr& mvec = MachineCodeForBasicBlock::get(*PI);
791 const MachineInstr* theCopy = NULL;
792 for (unsigned i=0; i < mvec.size() && theCopy == NULL; i++)
793 if (! mii.isDummyPhiInstr(mvec[i]->getOpCode()))
794 // not a Phi: assume this is a copy and examine its operands
795 for (int o=0, N=(int) mvec[i]->getNumOperands(); o < N; o++)
797 const MachineOperand& mop = mvec[i]->getOperand(o);
799 if (mvec[i]->operandIsDefined(o))
800 assert(mop.getVRegValue() == (*PI) && "dest shd be my Phi");
802 if (! mvec[i]->operandIsDefined(o) ||
803 NOT NEEDED? mvec[i]->operandIsDefinedAndUsed(o))
804 if (mop.getVRegValue() == inVal)
811 // Found the dang instruction. Now create a node and do the rest...
814 SchedGraphNode* node = new SchedGraphNode(getNumNodes(), bb,
815 theCopy, origIndexInBB++, target);
816 this->noteGraphNodeForInstr(theCopy, node);
817 findDefUseInfoAtInstr(target, node,
818 memNodeVec, regToRefVecMap,valueToDefVecMap);
821 #endif //REALLY_NEED_TO_SEARCH_SUCCESSOR_PHIS
826 SchedGraph::buildGraph(const TargetMachine& target)
828 const BasicBlock* bb = bbVec[0];
830 assert(bbVec.size() == 1 && "Only handling a single basic block here");
832 // Use this data structure to note all machine operands that compute
833 // ordinary LLVM values. These must be computed defs (i.e., instructions).
834 // Note that there may be multiple machine instructions that define
836 ValueToDefVecMap valueToDefVecMap;
838 // Use this data structure to note all memory instructions.
839 // We use this to add memory dependence edges without a second full walk.
841 // vector<const Instruction*> memVec;
842 vector<SchedGraphNode*> memNodeVec;
844 // Use this data structure to note any uses or definitions of
845 // machine registers so we can add edges for those later without
846 // extra passes over the nodes.
847 // The vector holds an ordered list of references to the machine reg,
848 // ordered according to control-flow order. This only works for a
849 // single basic block, hence the assertion. Each reference is identified
850 // by the pair: <node, operand-number>.
852 RegToRefVecMap regToRefVecMap;
854 // Make a dummy root node. We'll add edges to the real roots later.
855 graphRoot = new SchedGraphNode(0, NULL, NULL, -1, target);
856 graphLeaf = new SchedGraphNode(1, NULL, NULL, -1, target);
858 //----------------------------------------------------------------
859 // First add nodes for all the machine instructions in the basic block
860 // because this greatly simplifies identifying which edges to add.
861 // Do this one VM instruction at a time since the SchedGraphNode needs that.
862 // Also, remember the load/store instructions to add memory deps later.
863 //----------------------------------------------------------------
865 buildNodesforBB(target, bb, memNodeVec, regToRefVecMap, valueToDefVecMap);
867 //----------------------------------------------------------------
868 // Now add edges for the following (all are incoming edges except (4)):
869 // (1) operands of the machine instruction, including hidden operands
870 // (2) machine register dependences
871 // (3) memory load/store dependences
872 // (3) other resource dependences for the machine instruction, if any
873 // (4) output dependences when multiple machine instructions define the
874 // same value; all must have been generated from a single VM instrn
875 // (5) control dependences to branch instructions generated for the
876 // terminator instruction of the BB. Because of delay slots and
877 // 2-way conditional branches, multiple CD edges are needed
878 // (see addCDEdges for details).
879 // Also, note any uses or defs of machine registers.
881 //----------------------------------------------------------------
883 MachineCodeForBasicBlock& bbMvec = MachineCodeForBasicBlock::get(bb);
885 // First, add edges to the terminator instruction of the basic block.
886 this->addCDEdges(bb->getTerminator(), target);
888 // Then add memory dep edges: store->load, load->store, and store->store.
889 // Call instructions are treated as both load and store.
890 this->addMemEdges(memNodeVec, target);
892 // Then add edges between call instructions and CC set/use instructions
893 this->addCallCCEdges(memNodeVec, bbMvec, target);
895 // Then add incoming def-use (SSA) edges for each machine instruction.
896 for (unsigned i=0, N=bbMvec.size(); i < N; i++)
897 addEdgesForInstruction(*bbMvec[i], valueToDefVecMap, target);
899 #ifdef NEED_SEPARATE_NONSSA_EDGES_CODE
900 // Then add non-SSA edges for all VM instructions in the block.
901 // We assume that all machine instructions that define a value are
902 // generated from the VM instruction corresponding to that value.
903 // TODO: This could probably be done much more efficiently.
904 for (BasicBlock::const_iterator II = bb->begin(); II != bb->end(); ++II)
905 this->addNonSSAEdgesForValue(*II, target);
906 #endif //NEED_SEPARATE_NONSSA_EDGES_CODE
908 // Then add edges for dependences on machine registers
909 this->addMachineRegEdges(regToRefVecMap, target);
911 // Finally, add edges from the dummy root and to dummy leaf
912 this->addDummyEdges();
917 // class SchedGraphSet
921 SchedGraphSet::SchedGraphSet(const Function* _function,
922 const TargetMachine& target) :
925 buildGraphsForMethod(method, target);
930 SchedGraphSet::~SchedGraphSet()
932 // delete all the graphs
933 for(iterator I = begin(), E = end(); I != E; ++I)
934 delete *I; // destructor is a friend
939 SchedGraphSet::dump() const
941 cerr << "======== Sched graphs for function `" << method->getName()
944 for (const_iterator I=begin(); I != end(); ++I)
947 cerr << "\n====== End graphs for function `" << method->getName()
953 SchedGraphSet::buildGraphsForMethod(const Function *F,
954 const TargetMachine& target)
956 for (Function::const_iterator BI = F->begin(); BI != F->end(); ++BI)
957 addGraph(new SchedGraph(BI, target));
961 std::ostream &operator<<(std::ostream &os, const SchedGraphEdge& edge)
963 os << "edge [" << edge.src->getNodeId() << "] -> ["
964 << edge.sink->getNodeId() << "] : ";
966 switch(edge.depType) {
967 case SchedGraphEdge::CtrlDep: os<< "Control Dep"; break;
968 case SchedGraphEdge::ValueDep: os<< "Reg Value " << edge.val; break;
969 case SchedGraphEdge::MemoryDep: os<< "Memory Dep"; break;
970 case SchedGraphEdge::MachineRegister: os<< "Reg " <<edge.machineRegNum;break;
971 case SchedGraphEdge::MachineResource: os<<"Resource "<<edge.resourceId;break;
972 default: assert(0); break;
975 os << " : delay = " << edge.minDelay << "\n";
980 std::ostream &operator<<(std::ostream &os, const SchedGraphNode& node)
982 os << std::string(8, ' ')
983 << "Node " << node.nodeId << " : "
984 << "latency = " << node.latency << "\n" << std::string(12, ' ');
986 if (node.getMachineInstr() == NULL)
987 os << "(Dummy node)\n";
990 os << *node.getMachineInstr() << "\n" << std::string(12, ' ');
991 os << node.inEdges.size() << " Incoming Edges:\n";
992 for (unsigned i=0, N=node.inEdges.size(); i < N; i++)
993 os << std::string(16, ' ') << *node.inEdges[i];
995 os << std::string(12, ' ') << node.outEdges.size()
996 << " Outgoing Edges:\n";
997 for (unsigned i=0, N=node.outEdges.size(); i < N; i++)
998 os << std::string(16, ' ') << *node.outEdges[i];