-
-//===- SPLInstrScheduling.cpp - Modulo Software Pipelining Instruction Scheduling support -------===//
+//===-- ModuloScheduling.cpp - ModuloScheduling ----------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file was developed by the LLVM research group and is distributed under
+// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
-// this file implements the llvm/CodeGen/ModuloScheduling.h interface
+//===----------------------------------------------------------------------===//
//
+//
//
//===----------------------------------------------------------------------===//
-#include "llvm/CodeGen/MachineInstr.h"
-#include "llvm/CodeGen/MachineCodeForInstruction.h"
-//#include "llvm/CodeGen/MachineCodeForBasicBlock.h"
-//#include "llvm/CodeGen/MachineCodeForMethod.h"
-#include "llvm/CodeGen/MachineFunction.h"
-//#include "llvm/Analysis/LiveVar/FunctionLiveVarInfo.h" // FIXME: Remove when modularized better
-#include "llvm/Target/TargetMachine.h"
-#include "llvm/BasicBlock.h"
-#include "llvm/Instruction.h"
-#include "Support/CommandLine.h"
-#include <algorithm>
-#include "ModuloSchedGraph.h"
+#define DEBUG_TYPE "ModuloSched"
+
#include "ModuloScheduling.h"
+#include "llvm/CodeGen/MachineFunction.h"
+#include "llvm/CodeGen/Passes.h"
+#include "llvm/Support/CFG.h"
#include "llvm/Target/TargetSchedInfo.h"
-#include "llvm/BasicBlock.h"
-#include "llvm/iTerminators.h"
-#include "llvm/iPHINode.h"
-#include "llvm/Constants.h"
+#include "Support/Debug.h"
+#include "Support/GraphWriter.h"
+#include "Support/StringExtras.h"
+#include <vector>
+#include <utility>
#include <iostream>
-//#include <swig.h>
#include <fstream>
-#include "llvm/CodeGen/InstrSelection.h"
+#include <sstream>
-#define max(x,y) (x>y?x:y)
-#define min(x,y) (x<y?x:y)
-using std::cerr;
-using std::cout;
-using std::ostream;
-using std::ios;
-using std::filebuf;
-//************************************************************
-//printing Debug information
-//ModuloSchedDebugLevel stores the value of debug level
-// modsched_os is the ostream to dump debug information, which is written into the file 'moduloSchedDebugInfo.output'
-//see ModuloSchedulingPass::runOnFunction()
-//************************************************************
+using namespace llvm;
-ModuloSchedDebugLevel_t ModuloSchedDebugLevel;
-static cl::opt<ModuloSchedDebugLevel_t, true>
-SDL_opt("modsched", cl::Hidden, cl::location(ModuloSchedDebugLevel),
- cl::desc("enable modulo scheduling debugging information"),
- cl::values(
- clEnumValN(ModuloSched_NoDebugInfo, "n", "disable debug output"),
- clEnumValN(ModuloSched_Disable, "off", "disable modulo scheduling"),
- clEnumValN(ModuloSched_PrintSchedule, "psched", "print original and new schedule"),
- clEnumValN(ModuloSched_PrintScheduleProcess,"pschedproc", "print how the new schdule is produced"),
- 0));
+/// Create ModuloSchedulingPass
+///
+FunctionPass *llvm::createModuloSchedulingPass(TargetMachine & targ) {
+ DEBUG(std::cerr << "Created ModuloSchedulingPass\n");
+ return new ModuloSchedulingPass(targ);
+}
-filebuf modSched_fb;
-ostream modSched_os(&modSched_fb);
+template<typename GraphType>
+static void WriteGraphToFile(std::ostream &O, const std::string &GraphName,
+ const GraphType >) {
+ std::string Filename = GraphName + ".dot";
+ O << "Writing '" << Filename << "'...";
+ std::ofstream F(Filename.c_str());
+
+ if (F.good())
+ WriteGraph(F, GT);
+ else
+ O << " error opening file for writing!";
+ O << "\n";
+};
+
+namespace llvm {
+
+ template<>
+ struct DOTGraphTraits<MSchedGraph*> : public DefaultDOTGraphTraits {
+ static std::string getGraphName(MSchedGraph *F) {
+ return "Dependence Graph";
+ }
+
+ static std::string getNodeLabel(MSchedGraphNode *Node, MSchedGraph *Graph) {
+ if (Node->getInst()) {
+ std::stringstream ss;
+ ss << *(Node->getInst());
+ return ss.str(); //((MachineInstr*)Node->getInst());
+ }
+ else
+ return "No Inst";
+ }
+ static std::string getEdgeSourceLabel(MSchedGraphNode *Node,
+ MSchedGraphNode::succ_iterator I) {
+ //Label each edge with the type of dependence
+ std::string edgelabel = "";
+ switch (I.getEdge().getDepOrderType()) {
+
+ case MSchedGraphEdge::TrueDep:
+ edgelabel = "True";
+ break;
+
+ case MSchedGraphEdge::AntiDep:
+ edgelabel = "Anti";
+ break;
+
+ case MSchedGraphEdge::OutputDep:
+ edgelabel = "Output";
+ break;
+
+ default:
+ edgelabel = "Unknown";
+ break;
+ }
-//************************************************************
+ //FIXME
+ int iteDiff = I.getEdge().getIteDiff();
+ std::string intStr = "(IteDiff: ";
+ intStr += itostr(iteDiff);
+ intStr += ")";
+ edgelabel += intStr;
-///the method to compute schedule and instert epilogue and prologue
-void ModuloScheduling::instrScheduling(){
-
- if( ModuloSchedDebugLevel >= ModuloSched_PrintScheduleProcess)
- modSched_os<<"*************************computing modulo schedule ************************\n";
+ return edgelabel;
+ }
+
+
+
+ };
+}
+
+/// ModuloScheduling::runOnFunction - main transformation entry point
+bool ModuloSchedulingPass::runOnFunction(Function &F) {
+ bool Changed = false;
+
+ DEBUG(std::cerr << "Creating ModuloSchedGraph for each BasicBlock in" + F.getName() + "\n");
+ //Get MachineFunction
+ MachineFunction &MF = MachineFunction::get(&F);
+
+ //Iterate over BasicBlocks and do ModuloScheduling if they are valid
+ for (MachineFunction::const_iterator BI = MF.begin(); BI != MF.end(); ++BI) {
+ if(MachineBBisValid(BI)) {
+ MSchedGraph *MSG = new MSchedGraph(BI, target);
+
+ //Write Graph out to file
+ DEBUG(WriteGraphToFile(std::cerr, F.getName(), MSG));
+
+ //Print out BB for debugging
+ DEBUG(BI->print(std::cerr));
+
+ //Calculate Resource II
+ int ResMII = calculateResMII(BI);
- const TargetSchedInfo& msi=target.getSchedInfo();
+ //Calculate Recurrence II
+ int RecMII = calculateRecMII(MSG, ResMII);
+
+ II = std::max(RecMII, ResMII);
- //number of issue slots in the in each cycle
- int numIssueSlots=msi.maxNumIssueTotal;
+ DEBUG(std::cerr << "II starts out as " << II << "\n");
+ //Calculate Node Properties
+ calculateNodeAttributes(MSG, ResMII);
+ //Dump node properties if in debug mode
+ for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I !=E; ++I) {
+ DEBUG(std::cerr << "Node: " << *(I->first) << " ASAP: " << I->second.ASAP << " ALAP: " << I->second.ALAP << " MOB: " << I->second.MOB << " Depth: " << I->second.depth << " Height: " << I->second.height << "\n");
+ }
+
+ //Put nodes in order to schedule them
+ computePartialOrder();
+
+ //Dump out partial order
+ for(std::vector<std::vector<MSchedGraphNode*> >::iterator I = partialOrder.begin(), E = partialOrder.end(); I !=E; ++I) {
+ DEBUG(std::cerr << "Start set in PO\n");
+ for(std::vector<MSchedGraphNode*>::iterator J = I->begin(), JE = I->end(); J != JE; ++J)
+ DEBUG(std::cerr << "PO:" << **J << "\n");
+ }
- //compute the schedule
- bool success=false;
- while(!success)
- {
- //clear memory from the last round and initialize if necessary
- clearInitMem(msi);
+ orderNodes();
- //compute schedule and coreSchedule with the current II
- success=computeSchedule();
-
- if(!success){
- II++;
- if( ModuloSchedDebugLevel >= ModuloSched_PrintScheduleProcess)
- modSched_os<<"increase II to "<<II<<"\n";
+ //Dump out order of nodes
+ for(std::vector<MSchedGraphNode*>::iterator I = FinalNodeOrder.begin(), E = FinalNodeOrder.end(); I != E; ++I)
+ DEBUG(std::cerr << "FO:" << **I << "\n");
+
+
+ //Finally schedule nodes
+ computeSchedule();
+
+
+ //Dump out final schedule
+ //std::cerr << "FINALSCHEDULE\n";
+ //Dump out current schedule
+ /*for(std::map<unsigned, std::vector<std::pair<unsigned, MSchedGraphNode*> > >::iterator J = schedule.begin(),
+ JE = schedule.end(); J != JE; ++J) {
+ std::cerr << "Cycle " << J->first << ":\n";
+ for(std::vector<std::pair<unsigned, MSchedGraphNode*> >::iterator VI = J->second.begin(), VE = J->second.end(); VI != VE; ++VI)
+ std::cerr << "Resource ID: " << VI->first << " by node " << *(VI->second) << "\n";
+ }
+ std::cerr << "END FINAL SCHEDULE\n";
+
+ DEBUG(std::cerr << "II ends up as " << II << "\n");
+ */
+
+
+ nodeToAttributesMap.clear();
+ partialOrder.clear();
+ recurrenceList.clear();
+ FinalNodeOrder.clear();
+ schedule.clear();
}
- }
-
- //print the final schedule if necessary
- if( ModuloSchedDebugLevel >= ModuloSched_PrintSchedule)
- dumpScheduling();
-
+
+ }
- //the schedule has been computed
- //create epilogue, prologue and kernel BasicBlock
-
- //find the successor for this BasicBlock
- BasicBlock* succ_bb= getSuccBB(bb);
+
+ return Changed;
+}
+
+
+bool ModuloSchedulingPass::MachineBBisValid(const MachineBasicBlock *BI) {
+
+ //Valid basic blocks must be loops and can not have if/else statements or calls.
+ bool isLoop = false;
- //print the original BasicBlock if necessary
- if( ModuloSchedDebugLevel >= ModuloSched_PrintSchedule){
- modSched_os<<"dumping the orginal block\n";
- graph.dump(bb);
+ //Check first if its a valid loop
+ for(succ_const_iterator I = succ_begin(BI->getBasicBlock()),
+ E = succ_end(BI->getBasicBlock()); I != E; ++I) {
+ if (*I == BI->getBasicBlock()) // has single block loop
+ isLoop = true;
}
+
+ if(!isLoop) {
+ DEBUG(std::cerr << "Basic Block is not a loop\n");
+ return false;
+ }
+ else
+ DEBUG(std::cerr << "Basic Block is a loop\n");
+
+ //Get Target machine instruction info
+ /*const TargetInstrInfo& TMI = targ.getInstrInfo();
+
+ //Check each instruction and look for calls or if/else statements
+ unsigned count = 0;
+ for(MachineBasicBlock::const_iterator I = BI->begin(), E = BI->end(); I != E; ++I) {
+ //Get opcode to check instruction type
+ MachineOpCode OC = I->getOpcode();
+ if(TMI.isControlFlow(OC) && (count+1 < BI->size()))
+ return false;
+ count++;
+ }*/
+ return true;
- //construction of prologue, kernel and epilogue
- BasicBlock* kernel=bb->splitBasicBlock(bb->begin());
- BasicBlock* prologue= bb;
- BasicBlock* epilogue=kernel->splitBasicBlock(kernel->begin());
+}
+
+//ResMII is calculated by determining the usage count for each resource
+//and using the maximum.
+//FIXME: In future there should be a way to get alternative resources
+//for each instruction
+int ModuloSchedulingPass::calculateResMII(const MachineBasicBlock *BI) {
+ const TargetInstrInfo & mii = target.getInstrInfo();
+ const TargetSchedInfo & msi = target.getSchedInfo();
+
+ int ResMII = 0;
- //construct prologue
- constructPrologue(prologue);
+ //Map to keep track of usage count of each resource
+ std::map<unsigned, unsigned> resourceUsageCount;
- //construct kernel
- constructKernel(prologue,kernel,epilogue);
+ for(MachineBasicBlock::const_iterator I = BI->begin(), E = BI->end(); I != E; ++I) {
- //construct epilogue
- constructEpilogue(epilogue,succ_bb);
+ //Get resource usage for this instruction
+ InstrRUsage rUsage = msi.getInstrRUsage(I->getOpcode());
+ std::vector<std::vector<resourceId_t> > resources = rUsage.resourcesByCycle;
-
- //print the BasicBlocks if necessary
- if( ModuloSchedDebugLevel >= ModuloSched_PrintSchedule){
- modSched_os<<"dumping the prologue block:\n";
- graph.dump(prologue);
- modSched_os<<"dumping the kernel block\n";
- graph.dump(kernel);
- modSched_os<<"dumping the epilogue block\n";
- graph.dump(epilogue);
+ //Loop over resources in each cycle and increments their usage count
+ for(unsigned i=0; i < resources.size(); ++i)
+ for(unsigned j=0; j < resources[i].size(); ++j) {
+ if( resourceUsageCount.find(resources[i][j]) == resourceUsageCount.end()) {
+ resourceUsageCount[resources[i][j]] = 1;
+ }
+ else {
+ resourceUsageCount[resources[i][j]] = resourceUsageCount[resources[i][j]] + 1;
+ }
+ }
}
-
-}
-//clear memory from the last round and initialize if necessary
-void ModuloScheduling::clearInitMem(const TargetSchedInfo& msi){
+ //Find maximum usage count
+ //Get max number of instructions that can be issued at once. (FIXME)
+ int issueSlots = 1; // msi.maxNumIssueTotal;
+
+ for(std::map<unsigned,unsigned>::iterator RB = resourceUsageCount.begin(), RE = resourceUsageCount.end(); RB != RE; ++RB) {
+ //Get the total number of the resources in our cpu
+ //int resourceNum = msi.getCPUResourceNum(RB->first);
+
+ //Get total usage count for this resources
+ unsigned usageCount = RB->second;
+
+ //Divide the usage count by either the max number we can issue or the number of
+ //resources (whichever is its upper bound)
+ double finalUsageCount;
+ //if( resourceNum <= issueSlots)
+ //finalUsageCount = ceil(1.0 * usageCount / resourceNum);
+ //else
+ finalUsageCount = ceil(1.0 * usageCount / issueSlots);
+
+
+ DEBUG(std::cerr << "Resource ID: " << RB->first << " (usage=" << usageCount << ", resourceNum=X" << ", issueSlots=" << issueSlots << ", finalUsage=" << finalUsageCount << ")\n");
+
+ //Only keep track of the max
+ ResMII = std::max( (int) finalUsageCount, ResMII);
- unsigned numIssueSlots = msi.maxNumIssueTotal;
- //clear nodeScheduled from the last round
- if( ModuloSchedDebugLevel >= ModuloSched_PrintScheduleProcess){
- modSched_os<< "***** new round with II= "<<II<<" *******************"<<"\n";
- modSched_os<< " **************clear the vector nodeScheduled**************** \n";
}
- nodeScheduled.clear();
-
-
- //clear resourceTable from the last round and reset it
- resourceTable.clear();
- for(unsigned i=0;i< II;i++)
- resourceTable.push_back(msi.resourceNumVector);
+
+ DEBUG(std::cerr << "Final Resource MII: " << ResMII << "\n");
+ return ResMII;
+
+}
+
+int ModuloSchedulingPass::calculateRecMII(MSchedGraph *graph, int MII) {
+ std::vector<MSchedGraphNode*> vNodes;
+ //Loop over all nodes in the graph
+ for(MSchedGraph::iterator I = graph->begin(), E = graph->end(); I != E; ++I) {
+ findAllReccurrences(I->second, vNodes, MII);
+ vNodes.clear();
+ }
+
+ int RecMII = 0;
- //clear the schdule and coreSchedule from the last round
- schedule.clear();
- coreSchedule.clear();
+ for(std::set<std::pair<int, std::vector<MSchedGraphNode*> > >::iterator I = recurrenceList.begin(), E=recurrenceList.end(); I !=E; ++I) {
+ std::cerr << "Recurrence: \n";
+ for(std::vector<MSchedGraphNode*>::const_iterator N = I->second.begin(), NE = I->second.end(); N != NE; ++N) {
+ std::cerr << **N << "\n";
+ }
+ RecMII = std::max(RecMII, I->first);
+ std::cerr << "End Recurrence with RecMII: " << I->first << "\n";
+ }
+ DEBUG(std::cerr << "RecMII: " << RecMII << "\n");
- //create a coreSchedule of size II*numIssueSlots
- //each entry is NULL
- while( coreSchedule.size() < II){
- std::vector<ModuloSchedGraphNode*>* newCycle=new std::vector<ModuloSchedGraphNode*>();
- for(unsigned k=0;k<numIssueSlots;k++)
- newCycle->push_back(NULL);
- coreSchedule.push_back(*newCycle);
- }
+ return MII;
}
+void ModuloSchedulingPass::calculateNodeAttributes(MSchedGraph *graph, int MII) {
-//compute schedule and coreSchedule with the current II
-bool ModuloScheduling::computeSchedule(){
+ //Loop over the nodes and add them to the map
+ for(MSchedGraph::iterator I = graph->begin(), E = graph->end(); I != E; ++I) {
+ //Assert if its already in the map
+ assert(nodeToAttributesMap.find(I->second) == nodeToAttributesMap.end() && "Node attributes are already in the map");
+
+ //Put into the map with default attribute values
+ nodeToAttributesMap[I->second] = MSNodeAttributes();
+ }
+
+ //Create set to deal with reccurrences
+ std::set<MSchedGraphNode*> visitedNodes;
- if( ModuloSchedDebugLevel >= ModuloSched_PrintScheduleProcess)
- modSched_os <<"start to compute schedule \n";
+ //Now Loop over map and calculate the node attributes
+ for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
+ calculateASAP(I->first, MII, (MSchedGraphNode*) 0);
+ visitedNodes.clear();
+ }
- //loop over the ordered nodes
- for(NodeVec::const_iterator I=oNodes.begin();I!=oNodes.end();I++)
- {
- //try to schedule for node I
- if( ModuloSchedDebugLevel >= ModuloSched_PrintScheduleProcess)
- dumpScheduling();
- ModuloSchedGraphNode* node=*I;
-
- //compute whether this node has successor(s)
- bool succ=true;
+ int maxASAP = findMaxASAP();
+ //Calculate ALAP which depends on ASAP being totally calculated
+ for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
+ calculateALAP(I->first, MII, maxASAP, (MSchedGraphNode*) 0);
+ visitedNodes.clear();
+ }
- //compute whether this node has predessor(s)
- bool pred=true;
+ //Calculate MOB which depends on ASAP being totally calculated, also do depth and height
+ for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
+ (I->second).MOB = std::max(0,(I->second).ALAP - (I->second).ASAP);
+
+ DEBUG(std::cerr << "MOB: " << (I->second).MOB << " (" << *(I->first) << ")\n");
+ calculateDepth(I->first, (MSchedGraphNode*) 0);
+ calculateHeight(I->first, (MSchedGraphNode*) 0);
+ }
- NodeVec schSucc=graph.vectorConj(nodeScheduled,graph.succSet(node));
- if(schSucc.empty())
- succ=false;
- NodeVec schPred=graph.vectorConj(nodeScheduled,graph.predSet(node));
- if(schPred.empty())
- pred=false;
-
- //startTime: the earliest time we will try to schedule this node
- //endTime: the latest time we will try to schedule this node
- int startTime, endTime;
-
- //node's earlyStart: possible earliest time to schedule this node
- //node's lateStart: possible latest time to schedule this node
- node->setEarlyStart(-1);
- node->setLateStart(9999);
-
- //this node has predessor but no successor
- if(!succ && pred){
+}
- //this node's earlyStart is it's predessor's schedule time + the edge delay
- // - the iteration difference* II
- for(unsigned i=0;i<schPred.size();i++){
- ModuloSchedGraphNode* predNode=schPred[i];
- SchedGraphEdge* edge=graph.getMaxDelayEdge(predNode->getNodeId(),node->getNodeId());
- int temp=predNode->getSchTime()+edge->getMinDelay() - edge->getIteDiff()*II;
- node->setEarlyStart( max(node->getEarlyStart(),temp));
- }
- startTime=node->getEarlyStart();
- endTime=node->getEarlyStart()+II-1;
- }
-
+bool ModuloSchedulingPass::ignoreEdge(MSchedGraphNode *srcNode, MSchedGraphNode *destNode) {
+ if(destNode == 0 || srcNode ==0)
+ return false;
- //this node has successor but no predessor
- if(succ && !pred){
- for(unsigned i=0;i<schSucc.size();i++){
- ModuloSchedGraphNode* succNode=schSucc[i];
- SchedGraphEdge* edge=graph.getMaxDelayEdge(succNode->getNodeId(),node->getNodeId());
- int temp=succNode->getSchTime() - edge->getMinDelay() + edge->getIteDiff()*II;
- node->setLateStart(min(node->getEarlyStart(),temp));
- }
- startTime=node->getLateStart()- II+1;
- endTime=node->getLateStart();
- }
+ bool findEdge = edgesToIgnore.count(std::make_pair(srcNode, destNode->getInEdgeNum(srcNode)));
+ DEBUG(std::cerr << "Ignore Edge from " << *srcNode << " to " << *destNode << "? " << findEdge << "\n");
+ return findEdge;
+}
- //this node has both successors and predessors
- if(succ && pred)
- {
- for(unsigned i=0;i<schPred.size();i++){
- ModuloSchedGraphNode* predNode=schPred[i];
- SchedGraphEdge* edge=graph.getMaxDelayEdge(predNode->getNodeId(),node->getNodeId());
- int temp=predNode->getSchTime()+edge->getMinDelay() - edge->getIteDiff()*II;
- node->setEarlyStart(max(node->getEarlyStart(),temp));
- }
- for(unsigned i=0;i<schSucc.size();i++){
- ModuloSchedGraphNode* succNode=schSucc[i];
- SchedGraphEdge* edge=graph.getMaxDelayEdge(succNode->getNodeId(),node->getNodeId());
- int temp=succNode->getSchTime() - edge->getMinDelay() + edge->getIteDiff()*II;
- node->setLateStart(min(node->getEarlyStart(),temp));
- }
- startTime=node->getEarlyStart();
- endTime=min(node->getLateStart(),node->getEarlyStart()+((int)II)-1);
- }
-
- //this node has no successor or predessor
- if(!succ && !pred){
- node->setEarlyStart(node->getASAP());
- startTime=node->getEarlyStart();
- endTime=node->getEarlyStart()+II -1;
- }
+int ModuloSchedulingPass::calculateASAP(MSchedGraphNode *node, int MII, MSchedGraphNode *destNode) {
+
+ DEBUG(std::cerr << "Calculating ASAP for " << *node << "\n");
- //try to schedule this node based on the startTime and endTime
- if( ModuloSchedDebugLevel >= ModuloSched_PrintScheduleProcess)
- modSched_os<<"scheduling the node "<<(*I)->getNodeId()<<"\n";
+ //Get current node attributes
+ MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
- bool success= this->ScheduleNode(node,startTime, endTime,nodeScheduled);
- if(!success)return false;
+ if(attributes.ASAP != -1)
+ return attributes.ASAP;
+
+ int maxPredValue = 0;
+
+ //Iterate over all of the predecessors and find max
+ for(MSchedGraphNode::pred_iterator P = node->pred_begin(), E = node->pred_end(); P != E; ++P) {
+
+ //Only process if we are not ignoring the edge
+ if(!ignoreEdge(*P, node)) {
+ int predASAP = -1;
+ predASAP = calculateASAP(*P, MII, node);
+
+ assert(predASAP != -1 && "ASAP has not been calculated");
+ int iteDiff = node->getInEdge(*P).getIteDiff();
+
+ int currentPredValue = predASAP + (*P)->getLatency() - (iteDiff * MII);
+ DEBUG(std::cerr << "pred ASAP: " << predASAP << ", iteDiff: " << iteDiff << ", PredLatency: " << (*P)->getLatency() << ", Current ASAP pred: " << currentPredValue << "\n");
+ maxPredValue = std::max(maxPredValue, currentPredValue);
}
- return true;
+ }
+
+ attributes.ASAP = maxPredValue;
+
+ DEBUG(std::cerr << "ASAP: " << attributes.ASAP << " (" << *node << ")\n");
+
+ return maxPredValue;
}
-//get the successor of the BasicBlock
-BasicBlock* ModuloScheduling::getSuccBB(BasicBlock* bb){
+int ModuloSchedulingPass::calculateALAP(MSchedGraphNode *node, int MII,
+ int maxASAP, MSchedGraphNode *srcNode) {
+
+ DEBUG(std::cerr << "Calculating ALAP for " << *node << "\n");
+
+ MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
+
+ if(attributes.ALAP != -1)
+ return attributes.ALAP;
+
+ if(node->hasSuccessors()) {
+
+ //Trying to deal with the issue where the node has successors, but
+ //we are ignoring all of the edges to them. So this is my hack for
+ //now.. there is probably a more elegant way of doing this (FIXME)
+ bool processedOneEdge = false;
- BasicBlock* succ_bb;
- for(unsigned i=0;i < II; i++)
- for(unsigned j=0;j< coreSchedule[i].size();j++)
- if(coreSchedule[i][j]){
- const Instruction* ist=coreSchedule[i][j]->getInst();
+ //FIXME, set to something high to start
+ int minSuccValue = 9999999;
+
+ //Iterate over all of the predecessors and fine max
+ for(MSchedGraphNode::succ_iterator P = node->succ_begin(),
+ E = node->succ_end(); P != E; ++P) {
+
+ //Only process if we are not ignoring the edge
+ if(!ignoreEdge(node, *P)) {
+ processedOneEdge = true;
+ int succALAP = -1;
+ succALAP = calculateALAP(*P, MII, maxASAP, node);
- //we can get successor from the BranchInst instruction
- //assume we only have one successor (besides itself) here
- if(BranchInst::classof(ist)){
- BranchInst* bi=(BranchInst*)ist;
- assert(bi->isConditional()&&"the branchInst is not a conditional one");
- assert(bi->getNumSuccessors() ==2&&" more than two successors?");
- BasicBlock* bb1=bi->getSuccessor(0);
- BasicBlock* bb2=bi->getSuccessor(1);
- assert( (bb1 == bb|| bb2 == bb) && " None of its successor is itself?");
- if(bb1 == bb) succ_bb=bb2;
- else succ_bb=bb1;
- return succ_bb;
- }
+ assert(succALAP != -1 && "Successors ALAP should have been caclulated");
+
+ int iteDiff = P.getEdge().getIteDiff();
+
+ int currentSuccValue = succALAP - node->getLatency() + iteDiff * MII;
+
+ DEBUG(std::cerr << "succ ALAP: " << succALAP << ", iteDiff: " << iteDiff << ", SuccLatency: " << (*P)->getLatency() << ", Current ALAP succ: " << currentSuccValue << "\n");
+
+ minSuccValue = std::min(minSuccValue, currentSuccValue);
}
- assert( 0 && "NO Successor?");
- return NULL;
-}
+ }
+
+ if(processedOneEdge)
+ attributes.ALAP = minSuccValue;
+
+ else
+ attributes.ALAP = maxASAP;
+ }
+ else
+ attributes.ALAP = maxASAP;
+ DEBUG(std::cerr << "ALAP: " << attributes.ALAP << " (" << *node << ")\n");
-//get the predecessor of the BasicBlock
-BasicBlock* ModuloScheduling::getPredBB(BasicBlock* bb){
+ if(attributes.ALAP < 0)
+ attributes.ALAP = 0;
- BasicBlock* pred_bb;
+ return attributes.ALAP;
+}
- for(unsigned i=0;i < II; i++)
- for(unsigned j=0;j< coreSchedule[i].size();j++)
- if(coreSchedule[i][j]){
- const Instruction* ist=coreSchedule[i][j]->getInst();
-
- //we can get predecessor from the PHINode instruction
- //assume we only have one predecessor (besides itself) here
- if(PHINode::classof(ist)){
- PHINode* phi=(PHINode*) ist;
- assert(phi->getNumIncomingValues() == 2 &&" the number of incoming value is not equal to two? ");
- BasicBlock* bb1= phi->getIncomingBlock(0);
- BasicBlock* bb2= phi->getIncomingBlock(1);
- assert( (bb1 == bb || bb2 == bb) && " None of its predecessor is itself?");
- if(bb1 == bb) pred_bb=bb2;
- else pred_bb=bb1;
- return pred_bb;
- }
- }
- assert(0 && " no predecessor?");
- return NULL;
+int ModuloSchedulingPass::findMaxASAP() {
+ int maxASAP = 0;
+
+ for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(),
+ E = nodeToAttributesMap.end(); I != E; ++I)
+ maxASAP = std::max(maxASAP, I->second.ASAP);
+ return maxASAP;
}
-//construct the prologue
-void ModuloScheduling::constructPrologue(BasicBlock* prologue){
-
- InstListType& prologue_ist = prologue->getInstList();
- vvNodeType& tempSchedule_prologue= *(new vector< std::vector<ModuloSchedGraphNode*> >(schedule));
+int ModuloSchedulingPass::calculateHeight(MSchedGraphNode *node,MSchedGraphNode *srcNode) {
- //compute the schedule for prologue
- unsigned round=0;
- unsigned scheduleSize=schedule.size();
- while(round < scheduleSize/II){
- round++;
- for(unsigned i=0;i < scheduleSize ;i++){
- if(round*II + i >= scheduleSize) break;
- for(unsigned j=0;j < schedule[i].size(); j++)
- if(schedule[i][j]){
- assert( tempSchedule_prologue[round*II +i ][j] == NULL && "table not consitant with core table");
-
- //move the schedule one iteration ahead and overlap with the original one
- tempSchedule_prologue[round*II + i][j]=schedule[i][j];
- }
+ MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
+
+ if(attributes.height != -1)
+ return attributes.height;
+
+ int maxHeight = 0;
+
+ //Iterate over all of the predecessors and find max
+ for(MSchedGraphNode::succ_iterator P = node->succ_begin(),
+ E = node->succ_end(); P != E; ++P) {
+
+
+ if(!ignoreEdge(node, *P)) {
+ int succHeight = calculateHeight(*P, node);
+
+ assert(succHeight != -1 && "Successors Height should have been caclulated");
+
+ int currentHeight = succHeight + node->getLatency();
+ maxHeight = std::max(maxHeight, currentHeight);
}
}
+ attributes.height = maxHeight;
+ DEBUG(std::cerr << "Height: " << attributes.height << " (" << *node << ")\n");
+ return maxHeight;
+}
- //clear the clone memory in the core schedule instructions
- clearCloneMemory();
-
- //fill in the prologue
- for(unsigned i=0;i < ceil(1.0*scheduleSize/II -1)*II ;i++)
- for(unsigned j=0;j < tempSchedule_prologue[i].size();j++)
- if(tempSchedule_prologue[i][j]){
- //get the instruction
- Instruction* orn=(Instruction*)tempSchedule_prologue[i][j]->getInst();
+int ModuloSchedulingPass::calculateDepth(MSchedGraphNode *node,
+ MSchedGraphNode *destNode) {
- //made a clone of it
- Instruction* cln=cloneInstSetMemory(orn);
+ MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
- //insert the instruction
- prologue_ist.insert(prologue_ist.back(),cln );
+ if(attributes.depth != -1)
+ return attributes.depth;
- //if there is PHINode in the prologue, the incoming value from itself should be removed
- //because it is not a loop any longer
- if( PHINode::classof(cln)){
- PHINode* phi=(PHINode*)cln;
- phi->removeIncomingValue(phi->getParent());
- }
- }
+ int maxDepth = 0;
+
+ //Iterate over all of the predecessors and fine max
+ for(MSchedGraphNode::pred_iterator P = node->pred_begin(), E = node->pred_end(); P != E; ++P) {
+
+ if(!ignoreEdge(*P, node)) {
+ int predDepth = -1;
+ predDepth = calculateDepth(*P, node);
+
+ assert(predDepth != -1 && "Predecessors ASAP should have been caclulated");
+
+ int currentDepth = predDepth + (*P)->getLatency();
+ maxDepth = std::max(maxDepth, currentDepth);
+ }
+ }
+ attributes.depth = maxDepth;
+
+ DEBUG(std::cerr << "Depth: " << attributes.depth << " (" << *node << "*)\n");
+ return maxDepth;
}
-//construct the kernel BasicBlock
-void ModuloScheduling::constructKernel(BasicBlock* prologue,BasicBlock* kernel,BasicBlock* epilogue){
- //*************fill instructions in the kernel****************
- InstListType& kernel_ist = kernel->getInstList();
- BranchInst* brchInst;
- PHINode* phiInst, *phiCln;
+void ModuloSchedulingPass::addReccurrence(std::vector<MSchedGraphNode*> &recurrence, int II, MSchedGraphNode *srcBENode, MSchedGraphNode *destBENode) {
+ //Check to make sure that this recurrence is unique
+ bool same = false;
- for(unsigned i=0;i<coreSchedule.size();i++)
- for(unsigned j=0;j<coreSchedule[i].size();j++)
- if(coreSchedule[i][j]){
-
- //we should take care of branch instruction differently with normal instructions
- if(BranchInst::classof(coreSchedule[i][j]->getInst())){
- brchInst=(BranchInst*)coreSchedule[i][j]->getInst();
- continue;
- }
-
- //we should take care of PHINode instruction differently with normal instructions
- if( PHINode::classof(coreSchedule[i][j]->getInst())){
- phiInst= (PHINode*)coreSchedule[i][j]->getInst();
- Instruction* cln=cloneInstSetMemory(phiInst);
- kernel_ist.insert(kernel_ist.back(),cln);
- phiCln=(PHINode*)cln;
- continue;
+
+ //Loop over all recurrences already in our list
+ for(std::set<std::pair<int, std::vector<MSchedGraphNode*> > >::iterator R = recurrenceList.begin(), RE = recurrenceList.end(); R != RE; ++R) {
+
+ bool all_same = true;
+ //First compare size
+ if(R->second.size() == recurrence.size()) {
+
+ for(std::vector<MSchedGraphNode*>::const_iterator node = R->second.begin(), end = R->second.end(); node != end; ++node) {
+ if(find(recurrence.begin(), recurrence.end(), *node) == recurrence.end()) {
+ all_same = all_same && false;
+ break;
}
-
- //for normal instructions: made a clone and insert it in the kernel_ist
- Instruction* cln=cloneInstSetMemory( (Instruction*)coreSchedule[i][j]->getInst());
- kernel_ist.insert(kernel_ist.back(),cln);
+ else
+ all_same = all_same && true;
}
+ if(all_same) {
+ same = true;
+ break;
+ }
+ }
+ }
+
+ if(!same) {
+ //if(srcBENode == 0 || destBENode == 0) {
+ srcBENode = recurrence.back();
+ destBENode = recurrence.front();
+ //}
+ DEBUG(std::cerr << "Back Edge to Remove: " << *srcBENode << " to " << *destBENode << "\n");
+ edgesToIgnore.insert(std::make_pair(srcBENode, destBENode->getInEdgeNum(srcBENode)));
+ recurrenceList.insert(std::make_pair(II, recurrence));
+ }
+
+}
- //the two incoming BasicBlock for PHINode is the prologue and the kernel (itself)
- phiCln->setIncomingBlock(0,prologue);
- phiCln->setIncomingBlock(1,kernel);
+void ModuloSchedulingPass::findAllReccurrences(MSchedGraphNode *node,
+ std::vector<MSchedGraphNode*> &visitedNodes,
+ int II) {
+
+ if(find(visitedNodes.begin(), visitedNodes.end(), node) != visitedNodes.end()) {
+ std::vector<MSchedGraphNode*> recurrence;
+ bool first = true;
+ int delay = 0;
+ int distance = 0;
+ int RecMII = II; //Starting value
+ MSchedGraphNode *last = node;
+ MSchedGraphNode *srcBackEdge;
+ MSchedGraphNode *destBackEdge;
+
- //the incoming value for the kernel (itself) is the new value which is computed in the kernel
- Instruction* originalVal=(Instruction*)phiInst->getIncomingValue(1);
- phiCln->setIncomingValue(1, originalVal->getClone());
-
- //make a clone of the branch instruction and insert it in the end
- BranchInst* cln=(BranchInst*)cloneInstSetMemory( brchInst);
- kernel_ist.insert(kernel_ist.back(),cln);
+ for(std::vector<MSchedGraphNode*>::iterator I = visitedNodes.begin(), E = visitedNodes.end();
+ I !=E; ++I) {
- //delete the unconditional branch instruction, which is generated when splitting the basicBlock
- kernel_ist.erase( --kernel_ist.end());
+ if(*I == node)
+ first = false;
+ if(first)
+ continue;
- //set the first successor to itself
- ((BranchInst*)cln)->setSuccessor(0, kernel);
- //set the second successor to eiplogue
- ((BranchInst*)cln)->setSuccessor(1,epilogue);
+ delay = delay + (*I)->getLatency();
- //*****change the condition*******
+ if(*I != node) {
+ int diff = (*I)->getInEdge(last).getIteDiff();
+ distance += diff;
+ if(diff > 0) {
+ srcBackEdge = last;
+ destBackEdge = *I;
+ }
+ }
- //get the condition instruction
- Instruction* cond=(Instruction*)cln->getCondition();
+ recurrence.push_back(*I);
+ last = *I;
+ }
- //get the condition's second operand, it should be a constant
- Value* operand=cond->getOperand(1);
- assert(ConstantSInt::classof(operand));
- //change the constant in the condtion instruction
- ConstantSInt* iteTimes=ConstantSInt::get(operand->getType(),((ConstantSInt*)operand)->getValue()-II+1);
- cond->setOperand(1,iteTimes);
+
+ //Get final distance calc
+ distance += node->getInEdge(last).getIteDiff();
+
+ //Adjust II until we get close to the inequality delay - II*distance <= 0
+
+ int value = delay-(RecMII * distance);
+ int lastII = II;
+ while(value <= 0) {
+
+ lastII = RecMII;
+ RecMII--;
+ value = delay-(RecMII * distance);
+ }
+
+
+ DEBUG(std::cerr << "Final II for this recurrence: " << lastII << "\n");
+ addReccurrence(recurrence, lastII, srcBackEdge, destBackEdge);
+ assert(distance != 0 && "Recurrence distance should not be zero");
+ return;
+ }
+
+ for(MSchedGraphNode::succ_iterator I = node->succ_begin(), E = node->succ_end(); I != E; ++I) {
+ visitedNodes.push_back(node);
+ findAllReccurrences(*I, visitedNodes, II);
+ visitedNodes.pop_back();
+ }
}
-//construct the epilogue
-void ModuloScheduling::constructEpilogue(BasicBlock* epilogue, BasicBlock* succ_bb){
+void ModuloSchedulingPass::computePartialOrder() {
- //compute the schedule for epilogue
- vvNodeType& tempSchedule_epilogue= *(new vector< std::vector<ModuloSchedGraphNode*> >(schedule));
- unsigned scheduleSize=schedule.size();
- int round =0;
- while(round < ceil(1.0*scheduleSize/II )-1 ){
- round++;
- for( unsigned i=0;i < scheduleSize ; i++){
- if(i + round *II >= scheduleSize) break;
- for(unsigned j=0;j < schedule[i].size();j++)
- if(schedule[i + round*II ][j]){
- assert( tempSchedule_epilogue[i][j] == NULL && "table not consitant with core table");
+
+ //Loop over all recurrences and add to our partial order
+ //be sure to remove nodes that are already in the partial order in
+ //a different recurrence and don't add empty recurrences.
+ for(std::set<std::pair<int, std::vector<MSchedGraphNode*> > >::reverse_iterator I = recurrenceList.rbegin(), E=recurrenceList.rend(); I !=E; ++I) {
+
+ //Add nodes that connect this recurrence to the previous recurrence
+
+ //If this is the first recurrence in the partial order, add all predecessors
+ for(std::vector<MSchedGraphNode*>::const_iterator N = I->second.begin(), NE = I->second.end(); N != NE; ++N) {
- //move the schdule one iteration behind and overlap
- tempSchedule_epilogue[i][j]=schedule[i + round*II][j];
- }
}
- }
-
- //fill in the epilogue
- InstListType& epilogue_ist = epilogue->getInstList();
- for(unsigned i=II;i <scheduleSize ;i++)
- for(unsigned j=0;j < tempSchedule_epilogue[i].size();j++)
- if(tempSchedule_epilogue[i][j]){
- Instruction* inst=(Instruction*)tempSchedule_epilogue[i][j]->getInst();
-
- //BranchInst and PHINode should be treated differently
- //BranchInst:unecessary, simly omitted
- //PHINode: omitted
- if( !BranchInst::classof(inst) && ! PHINode::classof(inst) ){
- //make a clone instruction and insert it into the epilogue
- Instruction* cln=cloneInstSetMemory(inst);
- epilogue_ist.push_front(cln);
- }
- }
- //*************delete the original instructions****************//
- //to delete the original instructions, we have to make sure their use is zero
+ std::vector<MSchedGraphNode*> new_recurrence;
+ //Loop through recurrence and remove any nodes already in the partial order
+ for(std::vector<MSchedGraphNode*>::const_iterator N = I->second.begin(), NE = I->second.end(); N != NE; ++N) {
+ bool found = false;
+ for(std::vector<std::vector<MSchedGraphNode*> >::iterator PO = partialOrder.begin(), PE = partialOrder.end(); PO != PE; ++PO) {
+ if(find(PO->begin(), PO->end(), *N) != PO->end())
+ found = true;
+ }
+ if(!found) {
+ new_recurrence.push_back(*N);
+
+ if(partialOrder.size() == 0)
+ //For each predecessors, add it to this recurrence ONLY if it is not already in it
+ for(MSchedGraphNode::pred_iterator P = (*N)->pred_begin(),
+ PE = (*N)->pred_end(); P != PE; ++P) {
+
+ //Check if we are supposed to ignore this edge or not
+ if(!ignoreEdge(*P, *N))
+ //Check if already in this recurrence
+ if(find(I->second.begin(), I->second.end(), *P) == I->second.end()) {
+ //Also need to check if in partial order
+ bool predFound = false;
+ for(std::vector<std::vector<MSchedGraphNode*> >::iterator PO = partialOrder.begin(), PEND = partialOrder.end(); PO != PEND; ++PO) {
+ if(find(PO->begin(), PO->end(), *P) != PO->end())
+ predFound = true;
+ }
+
+ if(!predFound)
+ if(find(new_recurrence.begin(), new_recurrence.end(), *P) == new_recurrence.end())
+ new_recurrence.push_back(*P);
+
+ }
+ }
+ }
+ }
+
+
+ if(new_recurrence.size() > 0)
+ partialOrder.push_back(new_recurrence);
+ }
- //update original core instruction's uses, using its clone instread
- for(unsigned i=0;i < II; i++)
- for(unsigned j=0;j < coreSchedule[i].size() ;j++){
- if(coreSchedule[i][j])
- updateUseWithClone((Instruction*)coreSchedule[i][j]->getInst() );
+ //Add any nodes that are not already in the partial order
+ std::vector<MSchedGraphNode*> lastNodes;
+ for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
+ bool found = false;
+ //Check if its already in our partial order, if not add it to the final vector
+ for(std::vector<std::vector<MSchedGraphNode*> >::iterator PO = partialOrder.begin(), PE = partialOrder.end(); PO != PE; ++PO) {
+ if(find(PO->begin(), PO->end(), I->first) != PO->end())
+ found = true;
}
+ if(!found)
+ lastNodes.push_back(I->first);
+ }
+
+ if(lastNodes.size() > 0)
+ partialOrder.push_back(lastNodes);
- //erase these instructions
- for(unsigned i=0;i < II; i++)
- for(unsigned j=0;j < coreSchedule[i].size();j++)
- if(coreSchedule[i][j]){
- Instruction* ist=(Instruction*)coreSchedule[i][j]->getInst();
- ist->getParent()->getInstList().erase(ist);
- }
- //**************************************************************//
+}
- //finally, insert an unconditional branch instruction at the end
- epilogue_ist.push_back(new BranchInst(succ_bb));
+void ModuloSchedulingPass::predIntersect(std::vector<MSchedGraphNode*> &CurrentSet, std::vector<MSchedGraphNode*> &IntersectResult) {
+ //Sort CurrentSet so we can use lowerbound
+ sort(CurrentSet.begin(), CurrentSet.end());
+
+ for(unsigned j=0; j < FinalNodeOrder.size(); ++j) {
+ for(MSchedGraphNode::pred_iterator P = FinalNodeOrder[j]->pred_begin(),
+ E = FinalNodeOrder[j]->pred_end(); P != E; ++P) {
+
+ //Check if we are supposed to ignore this edge or not
+ if(ignoreEdge(*P,FinalNodeOrder[j]))
+ continue;
+
+ if(find(CurrentSet.begin(),
+ CurrentSet.end(), *P) != CurrentSet.end())
+ if(find(FinalNodeOrder.begin(), FinalNodeOrder.end(), *P) == FinalNodeOrder.end())
+ IntersectResult.push_back(*P);
+ }
+ }
}
+void ModuloSchedulingPass::succIntersect(std::vector<MSchedGraphNode*> &CurrentSet, std::vector<MSchedGraphNode*> &IntersectResult) {
-//----------------------------------------------------------------------------------------------
-//this function replace the value(instruction) ist in other instructions with its latest clone
-//i.e. after this function is called, the ist is not used anywhere and it can be erased.
-//----------------------------------------------------------------------------------------------
-void ModuloScheduling::updateUseWithClone(Instruction* ist){
+ //Sort CurrentSet so we can use lowerbound
+ sort(CurrentSet.begin(), CurrentSet.end());
- while(ist->use_size() >0){
- bool destroyed=false;
-
- //other instruction is using this value ist
- assert(Instruction::classof(*ist->use_begin()));
- Instruction *inst=(Instruction*)(* ist->use_begin());
-
- for(unsigned i=0;i<inst->getNumOperands();i++)
- if(inst->getOperand(i) == ist && ist->getClone()){
+ for(unsigned j=0; j < FinalNodeOrder.size(); ++j) {
+ for(MSchedGraphNode::succ_iterator P = FinalNodeOrder[j]->succ_begin(),
+ E = FinalNodeOrder[j]->succ_end(); P != E; ++P) {
+
+ //Check if we are supposed to ignore this edge or not
+ if(ignoreEdge(FinalNodeOrder[j],*P))
+ continue;
+
+ if(find(CurrentSet.begin(),
+ CurrentSet.end(), *P) != CurrentSet.end())
+ if(find(FinalNodeOrder.begin(), FinalNodeOrder.end(), *P) == FinalNodeOrder.end())
+ IntersectResult.push_back(*P);
+ }
+ }
+}
- //if the instruction is TmpInstruction, simly delete it because it has no parent
- // and it does not belongs to any BasicBlock
- if(TmpInstruction::classof(inst)) {
- delete inst;
- destroyed=true;
- break;
- }
+void dumpIntersection(std::vector<MSchedGraphNode*> &IntersectCurrent) {
+ std::cerr << "Intersection (";
+ for(std::vector<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(), E = IntersectCurrent.end(); I != E; ++I)
+ std::cerr << **I << ", ";
+ std::cerr << ")\n";
+}
- //otherwise, set the instruction's operand to the value's clone
- inst->setOperand(i, ist->getClone());
- //the use from the original value ist is destroyed
- destroyed=true;
- break;
- }
- if( !destroyed)
- {
- //if the use can not be destroyed , something is wrong
- inst->dump();
- assert( 0 &&"this use can not be destroyed");
- }
- }
+void ModuloSchedulingPass::orderNodes() {
-}
+ int BOTTOM_UP = 0;
+ int TOP_DOWN = 1;
+ //Set default order
+ int order = BOTTOM_UP;
-//********************************************************
-//this function clear all clone mememoy
-//i.e. set all instruction's clone memory to NULL
-//*****************************************************
-void ModuloScheduling::clearCloneMemory(){
-for(unsigned i=0; i < coreSchedule.size();i++)
- for(unsigned j=0;j<coreSchedule[i].size();j++)
- if(coreSchedule[i][j]) ((Instruction*)coreSchedule[i][j]->getInst())->clearClone();
-
-}
+ //Loop over all the sets and place them in the final node order
+ for(std::vector<std::vector<MSchedGraphNode*> >::iterator CurrentSet = partialOrder.begin(), E= partialOrder.end(); CurrentSet != E; ++CurrentSet) {
-//********************************************************************************
-//this function make a clone of the instruction orn
-//the cloned instruction will use the orn's operands' latest clone as its operands
-//it is done this way because LLVM is in SSA form and we should use the correct value
-//
-//this fuction also update the instruction orn's latest clone memory
-//**********************************************************************************
-Instruction* ModuloScheduling::cloneInstSetMemory(Instruction* orn) {
+ DEBUG(std::cerr << "Processing set in S\n");
+ dumpIntersection(*CurrentSet);
+ //Result of intersection
+ std::vector<MSchedGraphNode*> IntersectCurrent;
-//make a clone instruction
- Instruction* cln=orn->clone();
-
+ predIntersect(*CurrentSet, IntersectCurrent);
- //update the operands
- for(unsigned k=0;k<orn->getNumOperands();k++){
- const Value* op=orn->getOperand(k);
- if(Instruction::classof(op) && ((Instruction*)op)->getClone()){
- Instruction* op_inst=(Instruction*)op;
- cln->setOperand(k, op_inst->getClone());
+ //If the intersection of predecessor and current set is not empty
+ //sort nodes bottom up
+ if(IntersectCurrent.size() != 0) {
+ DEBUG(std::cerr << "Final Node Order Predecessors and Current Set interesection is NOT empty\n");
+ order = BOTTOM_UP;
}
- }
+ //If empty, use successors
+ else {
+ DEBUG(std::cerr << "Final Node Order Predecessors and Current Set interesection is empty\n");
- //update clone memory
- orn->setClone(cln);
- return cln;
-}
+ succIntersect(*CurrentSet, IntersectCurrent);
+ //sort top-down
+ if(IntersectCurrent.size() != 0) {
+ DEBUG(std::cerr << "Final Node Order Successors and Current Set interesection is NOT empty\n");
+ order = TOP_DOWN;
+ }
+ else {
+ DEBUG(std::cerr << "Final Node Order Successors and Current Set interesection is empty\n");
+ //Find node with max ASAP in current Set
+ MSchedGraphNode *node;
+ int maxASAP = 0;
+ DEBUG(std::cerr << "Using current set of size " << CurrentSet->size() << "to find max ASAP\n");
+ for(unsigned j=0; j < CurrentSet->size(); ++j) {
+ //Get node attributes
+ MSNodeAttributes nodeAttr= nodeToAttributesMap.find((*CurrentSet)[j])->second;
+ //assert(nodeAttr != nodeToAttributesMap.end() && "Node not in attributes map!");
+ DEBUG(std::cerr << "CurrentSet index " << j << "has ASAP: " << nodeAttr.ASAP << "\n");
+ if(maxASAP < nodeAttr.ASAP) {
+ maxASAP = nodeAttr.ASAP;
+ node = (*CurrentSet)[j];
+ }
+ }
+ assert(node != 0 && "In node ordering node should not be null");
+ IntersectCurrent.push_back(node);
+ order = BOTTOM_UP;
+ }
+ }
+
+ //Repeat until all nodes are put into the final order from current set
+ while(IntersectCurrent.size() > 0) {
+ if(order == TOP_DOWN) {
+ DEBUG(std::cerr << "Order is TOP DOWN\n");
-bool ModuloScheduling::ScheduleNode(ModuloSchedGraphNode* node,unsigned start, unsigned end, NodeVec& nodeScheduled)
-{
-
- const TargetSchedInfo& msi=target.getSchedInfo();
- unsigned int numIssueSlots=msi.maxNumIssueTotal;
-
- if( ModuloSchedDebugLevel >= ModuloSched_PrintScheduleProcess)
- modSched_os<<"startTime= "<<start<<" endTime= "<<end<<"\n";
- bool isScheduled=false;
- for(unsigned i=start;i<= end;i++){
- if( ModuloSchedDebugLevel >= ModuloSched_PrintScheduleProcess)
- modSched_os<< " now try cycle " <<i<<":"<<"\n";
- for(unsigned j=0;j<numIssueSlots;j++){
- unsigned int core_i = i%II;
- unsigned int core_j=j;
- if( ModuloSchedDebugLevel >= ModuloSched_PrintScheduleProcess)
- modSched_os <<"\t Trying slot "<<j<<"...........";
- //check the resouce table, make sure there is no resource conflicts
- const Instruction* instr=node->getInst();
- MachineCodeForInstruction& tempMvec= MachineCodeForInstruction::get(instr);
- bool resourceConflict=false;
- const TargetInstrInfo &mii=msi.getInstrInfo();
-
- if(coreSchedule.size() < core_i+1 || !coreSchedule[core_i][core_j]){
- //this->dumpResourceUsageTable();
- int latency=0;
- for(unsigned k=0;k< tempMvec.size();k++)
- {
- MachineInstr* minstr=tempMvec[k];
- InstrRUsage rUsage=msi.getInstrRUsage(minstr->getOpCode());
- std::vector<std::vector<resourceId_t> > resources
- =rUsage.resourcesByCycle;
- updateResourceTable(resources,i + latency);
- latency +=max(mii.minLatency(minstr->getOpCode()),1) ;
+ while(IntersectCurrent.size() > 0) {
+ DEBUG(std::cerr << "Intersection is not empty, so find heighest height\n");
+
+ int MOB = 0;
+ int height = 0;
+ MSchedGraphNode *highestHeightNode = IntersectCurrent[0];
+
+ //Find node in intersection with highest heigh and lowest MOB
+ for(std::vector<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(),
+ E = IntersectCurrent.end(); I != E; ++I) {
+
+ //Get current nodes properties
+ MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*I)->second;
+
+ if(height < nodeAttr.height) {
+ highestHeightNode = *I;
+ height = nodeAttr.height;
+ MOB = nodeAttr.MOB;
+ }
+ else if(height == nodeAttr.height) {
+ if(MOB > nodeAttr.height) {
+ highestHeightNode = *I;
+ height = nodeAttr.height;
+ MOB = nodeAttr.MOB;
+ }
+ }
}
+
+ //Append our node with greatest height to the NodeOrder
+ if(find(FinalNodeOrder.begin(), FinalNodeOrder.end(), highestHeightNode) == FinalNodeOrder.end()) {
+ DEBUG(std::cerr << "Adding node to Final Order: " << *highestHeightNode << "\n");
+ FinalNodeOrder.push_back(highestHeightNode);
+ }
+
+ //Remove V from IntersectOrder
+ IntersectCurrent.erase(find(IntersectCurrent.begin(),
+ IntersectCurrent.end(), highestHeightNode));
+
+
+ //Intersect V's successors with CurrentSet
+ for(MSchedGraphNode::succ_iterator P = highestHeightNode->succ_begin(),
+ E = highestHeightNode->succ_end(); P != E; ++P) {
+ //if(lower_bound(CurrentSet->begin(),
+ // CurrentSet->end(), *P) != CurrentSet->end()) {
+ if(find(CurrentSet->begin(), CurrentSet->end(), *P) != CurrentSet->end()) {
+ if(ignoreEdge(highestHeightNode, *P))
+ continue;
+ //If not already in Intersect, add
+ if(find(IntersectCurrent.begin(), IntersectCurrent.end(), *P) == IntersectCurrent.end())
+ IntersectCurrent.push_back(*P);
+ }
+ }
+ } //End while loop over Intersect Size
+
+ //Change direction
+ order = BOTTOM_UP;
+
+ //Reset Intersect to reflect changes in OrderNodes
+ IntersectCurrent.clear();
+ predIntersect(*CurrentSet, IntersectCurrent);
- //this->dumpResourceUsageTable();
+ } //End If TOP_DOWN
- latency=0;
- if( resourceTableNegative()){
+ //Begin if BOTTOM_UP
+ else {
+ DEBUG(std::cerr << "Order is BOTTOM UP\n");
+ while(IntersectCurrent.size() > 0) {
+ DEBUG(std::cerr << "Intersection of size " << IntersectCurrent.size() << ", finding highest depth\n");
+
+ //dump intersection
+ DEBUG(dumpIntersection(IntersectCurrent));
+ //Get node with highest depth, if a tie, use one with lowest
+ //MOB
+ int MOB = 0;
+ int depth = 0;
+ MSchedGraphNode *highestDepthNode = IntersectCurrent[0];
- //undo-update the resource table
- for(unsigned k=0;k< tempMvec.size();k++){
- MachineInstr* minstr=tempMvec[k];
- InstrRUsage rUsage=msi.getInstrRUsage(minstr->getOpCode());
- std::vector<std::vector<resourceId_t> > resources
- =rUsage.resourcesByCycle;
- undoUpdateResourceTable(resources,i + latency);
- latency +=max(mii.minLatency(minstr->getOpCode()),1) ;
+ for(std::vector<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(),
+ E = IntersectCurrent.end(); I != E; ++I) {
+ //Find node attribute in graph
+ MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*I)->second;
+
+ if(depth < nodeAttr.depth) {
+ highestDepthNode = *I;
+ depth = nodeAttr.depth;
+ MOB = nodeAttr.MOB;
+ }
+ else if(depth == nodeAttr.depth) {
+ if(MOB > nodeAttr.MOB) {
+ highestDepthNode = *I;
+ depth = nodeAttr.depth;
+ MOB = nodeAttr.MOB;
+ }
+ }
}
- resourceConflict=true;
- }
- }
- if( !resourceConflict && !coreSchedule[core_i][core_j]){
- if( ModuloSchedDebugLevel >= ModuloSched_PrintScheduleProcess){
- modSched_os <<" OK!"<<"\n";
- modSched_os<<"Node "<<node->getNodeId()<< " is scheduleed."<<"\n";
- }
- //schedule[i][j]=node;
- while(schedule.size() <= i){
- std::vector<ModuloSchedGraphNode*>* newCycle=new std::vector<ModuloSchedGraphNode*>();
- for(unsigned k=0;k<numIssueSlots;k++)
- newCycle->push_back(NULL);
- schedule.push_back(*newCycle);
- }
- vector<ModuloSchedGraphNode*>::iterator startIterator;
- startIterator = schedule[i].begin();
- schedule[i].insert(startIterator+j,node);
- startIterator = schedule[i].begin();
- schedule[i].erase(startIterator+j+1);
-
- //update coreSchedule
- //coreSchedule[core_i][core_j]=node;
- while(coreSchedule.size() <= core_i){
- std::vector<ModuloSchedGraphNode*>* newCycle=new std::vector<ModuloSchedGraphNode*>();
- for(unsigned k=0;k<numIssueSlots;k++)
- newCycle->push_back(NULL);
- coreSchedule.push_back(*newCycle);
- }
+
+
- startIterator = coreSchedule[core_i].begin();
- coreSchedule[core_i].insert(startIterator+core_j,node);
- startIterator = coreSchedule[core_i].begin();
- coreSchedule[core_i].erase(startIterator+core_j+1);
+ //Append highest depth node to the NodeOrder
+ if(find(FinalNodeOrder.begin(), FinalNodeOrder.end(), highestDepthNode) == FinalNodeOrder.end()) {
+ DEBUG(std::cerr << "Adding node to Final Order: " << *highestDepthNode << "\n");
+ FinalNodeOrder.push_back(highestDepthNode);
+ }
+ //Remove heightestDepthNode from IntersectOrder
+ IntersectCurrent.erase(find(IntersectCurrent.begin(),
+ IntersectCurrent.end(),highestDepthNode));
+
- node->setSchTime(i);
- isScheduled=true;
- nodeScheduled.push_back(node);
+ //Intersect heightDepthNode's pred with CurrentSet
+ for(MSchedGraphNode::pred_iterator P = highestDepthNode->pred_begin(),
+ E = highestDepthNode->pred_end(); P != E; ++P) {
+ //if(lower_bound(CurrentSet->begin(),
+ // CurrentSet->end(), *P) != CurrentSet->end()) {
+ if(find(CurrentSet->begin(), CurrentSet->end(), *P) != CurrentSet->end()) {
+
+ if(ignoreEdge(*P, highestDepthNode))
+ continue;
+
+ //If not already in Intersect, add
+ if(find(IntersectCurrent.begin(),
+ IntersectCurrent.end(), *P) == IntersectCurrent.end())
+ IntersectCurrent.push_back(*P);
+ }
+ }
+
+ } //End while loop over Intersect Size
+
+ //Change order
+ order = TOP_DOWN;
+
+ //Reset IntersectCurrent to reflect changes in OrderNodes
+ IntersectCurrent.clear();
+ succIntersect(*CurrentSet, IntersectCurrent);
+ } //End if BOTTOM_DOWN
- break;
- }
- else if( coreSchedule[core_i][core_j]) {
- if( ModuloSchedDebugLevel >= ModuloSched_PrintScheduleProcess)
- modSched_os <<" Slot not available "<<"\n";
- }
- else{
- if( ModuloSchedDebugLevel >= ModuloSched_PrintScheduleProcess)
- modSched_os <<" Resource conflicts"<<"\n";
- }
}
- if(isScheduled) break;
- }
- //assert(nodeScheduled &&"this node can not be scheduled?");
- return isScheduled;
+ //End Wrapping while loop
+
+ }//End for over all sets of nodes
+
+ //Return final Order
+ //return FinalNodeOrder;
}
-void ModuloScheduling::updateResourceTable(std::vector<std::vector<unsigned int> > useResources, int startCycle){
- for(unsigned i=0;i< useResources.size();i++){
- int absCycle=startCycle+i;
- int coreCycle=absCycle % II;
- std::vector<pair<int,int> >& resourceRemained=resourceTable[coreCycle];
- std::vector<unsigned int>& resourceUsed= useResources[i];
- for(unsigned j=0;j< resourceUsed.size();j++){
- for(unsigned k=0;k< resourceRemained.size();k++)
- if((int)resourceUsed[j] == resourceRemained[k].first){
- resourceRemained[k].second--;
- }
- }
- }
-}
+void ModuloSchedulingPass::computeSchedule() {
-void ModuloScheduling::undoUpdateResourceTable(std::vector<std::vector<unsigned int> > useResources, int startCycle){
- for(unsigned i=0;i< useResources.size();i++){
- int absCycle=startCycle+i;
- int coreCycle=absCycle % II;
- std::vector<pair<int,int> >& resourceRemained=resourceTable[coreCycle];
- std::vector<unsigned int>& resourceUsed= useResources[i];
- for(unsigned j=0;j< resourceUsed.size();j++){
- for(unsigned k=0;k< resourceRemained.size();k++)
- if((int)resourceUsed[j] == resourceRemained[k].first){
- resourceRemained[k].second++;
- }
- }
- }
-}
+ bool success = false;
+
+ while(!success) {
+ //Loop over the final node order and process each node
+ for(std::vector<MSchedGraphNode*>::iterator I = FinalNodeOrder.begin(),
+ E = FinalNodeOrder.end(); I != E; ++I) {
+
+ //CalculateEarly and Late start
+ int EarlyStart = -1;
+ int LateStart = 99999; //Set to something higher then we would ever expect (FIXME)
+ bool hasSucc = false;
+ bool hasPred = false;
+ std::set<MSchedGraphNode*> seenNodes;
+
+ for(std::map<unsigned, std::vector<std::pair<unsigned, std::vector<MSchedGraphNode*> > > >::iterator J = schedule.begin(),
+ JE = schedule.end(); J != JE; ++J) {
+
+ //For each resource with nodes scheduled, loop over the nodes and see if they
+ //are a predecessor or successor of this current node we are trying
+ //to schedule.
+ for(std::vector<std::pair<unsigned, std::vector<MSchedGraphNode*> > >::iterator schedNodeVec = J->second.begin(), SNE = J->second.end(); schedNodeVec != SNE; ++schedNodeVec) {
+
+ for(std::vector<MSchedGraphNode*>::iterator schedNode = schedNodeVec->second.begin(), schedNodeEnd = schedNodeVec->second.end(); schedNode != schedNodeEnd; ++schedNode) {
+ if((*I)->isPredecessor(*schedNode) && !seenNodes.count(*schedNode)) {
+ if(!ignoreEdge(*schedNode, *I)) {
+ int diff = (*I)->getInEdge(*schedNode).getIteDiff();
+ int ES_Temp = J->first + (*schedNode)->getLatency() - diff * II;
+ DEBUG(std::cerr << "Diff: " << diff << " Cycle: " << J->first << "\n");
+ DEBUG(std::cerr << "Temp EarlyStart: " << ES_Temp << " Prev EarlyStart: " << EarlyStart << "\n");
+ EarlyStart = std::max(EarlyStart, ES_Temp);
+ hasPred = true;
+ }
+ }
+ if((*I)->isSuccessor(*schedNode) && !seenNodes.count(*schedNode)) {
+ if(!ignoreEdge(*I,*schedNode)) {
+ int diff = (*schedNode)->getInEdge(*I).getIteDiff();
+ int LS_Temp = J->first - (*I)->getLatency() + diff * II;
+ DEBUG(std::cerr << "Diff: " << diff << " Cycle: " << J->first << "\n");
+ DEBUG(std::cerr << "Temp LateStart: " << LS_Temp << " Prev LateStart: " << LateStart << "\n");
+ LateStart = std::min(LateStart, LS_Temp);
+ hasSucc = true;
+ }
+ }
+ seenNodes.insert(*schedNode);
+ }
+ }
+ }
+ seenNodes.clear();
+
+ DEBUG(std::cerr << "Has Successors: " << hasSucc << ", Has Pred: " << hasPred << "\n");
+ DEBUG(std::cerr << "EarlyStart: " << EarlyStart << ", LateStart: " << LateStart << "\n");
-//-----------------------------------------------------------------------
-//Function: resouceTableNegative
-//return value:
-// return false if any element in the resouceTable is negative
-// otherwise return true
-//Purpose:
-// this function is used to determine if an instruction is eligible for schedule at certain cycle
-//---------------------------------------------------------------------------------------
-
-bool ModuloScheduling::resourceTableNegative(){
- assert(resourceTable.size() == (unsigned)II&& "resouceTable size must be equal to II");
- bool isNegative=false;
- for(unsigned i=0; i < resourceTable.size();i++)
- for(unsigned j=0;j < resourceTable[i].size();j++){
- if(resourceTable[i][j].second <0) {
- isNegative=true;
+ //Check if the node has no pred or successors and set Early Start to its ASAP
+ if(!hasSucc && !hasPred)
+ EarlyStart = nodeToAttributesMap.find(*I)->second.ASAP;
+
+ //Now, try to schedule this node depending upon its pred and successor in the schedule
+ //already
+ if(!hasSucc && hasPred)
+ success = scheduleNode(*I, EarlyStart, (EarlyStart + II -1));
+ else if(!hasPred && hasSucc)
+ success = scheduleNode(*I, LateStart, (LateStart - II +1));
+ else if(hasPred && hasSucc)
+ success = scheduleNode(*I, EarlyStart, std::min(LateStart, (EarlyStart + II -1)));
+ else
+ success = scheduleNode(*I, EarlyStart, EarlyStart + II - 1);
+
+ if(!success) {
+ ++II;
+ schedule.clear();
break;
- }
+ }
+
}
- return isNegative;
+ }
}
-//----------------------------------------------------------------------
-//Function: dumpResouceUsageTable
-//Purpose:
-// print out ResouceTable for debug
-//
-//------------------------------------------------------------------------
-
-void ModuloScheduling::dumpResourceUsageTable(){
- modSched_os<<"dumping resource usage table"<<"\n";
- for(unsigned i=0;i< resourceTable.size();i++){
- for(unsigned j=0;j < resourceTable[i].size();j++)
- modSched_os <<resourceTable[i][j].first<<":"<< resourceTable[i][j].second<<" ";
- modSched_os <<"\n";
+bool ModuloSchedulingPass::scheduleNode(MSchedGraphNode *node,
+ int start, int end) {
+ bool success = false;
+
+ DEBUG(std::cerr << *node << " (Start Cycle: " << start << ", End Cycle: " << end << ")\n");
+
+ /*std::cerr << "CURRENT SCHEDULE\n";
+ //Dump out current schedule
+ for(std::map<unsigned, std::vector<std::pair<unsigned, MSchedGraphNode*> > >::iterator J = schedule.begin(),
+ JE = schedule.end(); J != JE; ++J) {
+ std::cerr << "Cycle " << J->first << ":\n";
+ for(std::vector<std::pair<unsigned, MSchedGraphNode*> >::iterator VI = J->second.begin(), VE = J->second.end(); VI != VE; ++VI)
+ std::cerr << "Resource ID: " << VI->first << " by node " << *(VI->second) << "\n";
}
-
-}
+ std::cerr << "END CURRENT SCHEDULE\n";
+ */
-//----------------------------------------------------------------------
-//Function: dumpSchedule
-//Purpose:
-// print out thisSchedule for debug
-//
-//-----------------------------------------------------------------------
-void ModuloScheduling::dumpSchedule(std::vector< std::vector<ModuloSchedGraphNode*> > thisSchedule){
-
- const TargetSchedInfo& msi=target.getSchedInfo();
- unsigned numIssueSlots=msi.maxNumIssueTotal;
- for(unsigned i=0;i< numIssueSlots;i++)
- modSched_os <<"\t#";
- modSched_os<<"\n";
- for(unsigned i=0;i < thisSchedule.size();i++)
- {
- modSched_os<<"cycle"<<i<<": ";
- for(unsigned j=0;j<thisSchedule[i].size();j++)
- if(thisSchedule[i][j]!= NULL)
- modSched_os<<thisSchedule[i][j]->getNodeId()<<"\t";
- else
- modSched_os<<"\t";
- modSched_os<<"\n";
- }
-
-}
+ //Make sure start and end are not negative
+ if(start < 0)
+ start = 0;
+ if(end < 0)
+ end = 0;
+ bool forward = true;
+ if(start > end)
+ forward = false;
-//----------------------------------------------------
-//Function: dumpScheduling
-//Purpose:
-// print out the schedule and coreSchedule for debug
-//
-//-------------------------------------------------------
-
-void ModuloScheduling::dumpScheduling(){
- modSched_os<<"dump schedule:"<<"\n";
- const TargetSchedInfo& msi=target.getSchedInfo();
- unsigned numIssueSlots=msi.maxNumIssueTotal;
- for(unsigned i=0;i< numIssueSlots;i++)
- modSched_os <<"\t#";
- modSched_os<<"\n";
- for(unsigned i=0;i < schedule.size();i++)
- {
- modSched_os<<"cycle"<<i<<": ";
- for(unsigned j=0;j<schedule[i].size();j++)
- if(schedule[i][j]!= NULL)
- modSched_os<<schedule[i][j]->getNodeId()<<"\t";
- else
- modSched_os<<"\t";
- modSched_os<<"\n";
- }
-
- modSched_os<<"dump coreSchedule:"<<"\n";
- for(unsigned i=0;i< numIssueSlots;i++)
- modSched_os <<"\t#";
- modSched_os<<"\n";
- for(unsigned i=0;i < coreSchedule.size();i++){
- modSched_os<<"cycle"<<i<<": ";
- for(unsigned j=0;j< coreSchedule[i].size();j++)
- if(coreSchedule[i][j] !=NULL)
- modSched_os<<coreSchedule[i][j]->getNodeId()<<"\t";
- else
- modSched_os<<"\t";
- modSched_os<<"\n";
- }
-}
+ const TargetSchedInfo & msi = target.getSchedInfo();
+ bool increaseSC = true;
+
+ int cycle = start ;
-//---------------------------------------------------------------------------
-// Function: ModuloSchedulingPass
-//
-// Purpose:
-// Entry point for Modulo Scheduling
-// Schedules LLVM instruction
-//
-//---------------------------------------------------------------------------
-
-namespace {
- class ModuloSchedulingPass : public FunctionPass {
- const TargetMachine ⌖
- public:
- ModuloSchedulingPass(const TargetMachine &T) : target(T) {}
- const char *getPassName() const { return "Modulo Scheduling"; }
-
- // getAnalysisUsage - We use LiveVarInfo...
- virtual void getAnalysisUsage(AnalysisUsage &AU) const {
- //AU.addRequired(FunctionLiveVarInfo::ID);
- }
- bool runOnFunction(Function &F);
- };
-} // end anonymous namespace
+ while(increaseSC) {
+
+ increaseSC = false;
+ //Get the resource used by this instruction
+ //Get resource usage for this instruction
+ InstrRUsage rUsage = msi.getInstrRUsage(node->getInst()->getOpcode());
+ std::vector<std::vector<resourceId_t> > resources = rUsage.resourcesByCycle;
+ //Loop over each resource and see if we can put it into the schedule
+ for(unsigned r=0; r < resources.size(); ++r) {
+ unsigned intermediateCycle = cycle + r;
+
+ for(unsigned j=0; j < resources[r].size(); ++j) {
+ //Put it into the schedule
+ DEBUG(std::cerr << "Attempting to put resource " << resources[r][j] << " in schedule at cycle: " << intermediateCycle << "\n");
+
+ //Check if resource is free at this cycle
+ std::vector<std::pair<unsigned, std::vector<MSchedGraphNode*> > > resourceForCycle = schedule[intermediateCycle];
+
+ //Vector of nodes using this resource
+ std::vector<MSchedGraphNode*> *nodesUsingResource;
-bool ModuloSchedulingPass::runOnFunction(Function &F)
-{
-
- //if necessary , open the output for debug purpose
- if(ModuloSchedDebugLevel== ModuloSched_Disable)
- return false;
-
- if(ModuloSchedDebugLevel>= ModuloSched_PrintSchedule){
- modSched_fb.open("moduloSchedDebugInfo.output", ios::out);
- modSched_os<<"******************Modula Scheduling debug information*************************"<<"\n ";
- }
-
- ModuloSchedGraphSet* graphSet = new ModuloSchedGraphSet(&F,target);
- ModuloSchedulingSet ModuloSchedulingSet(*graphSet);
-
- if(ModuloSchedDebugLevel>= ModuloSched_PrintSchedule)
- modSched_fb.close();
-
- return false;
-}
+ for(std::vector<std::pair<unsigned, std::vector<MSchedGraphNode*> > >::iterator I = resourceForCycle.begin(), E= resourceForCycle.end(); I != E; ++I) {
+
+ if(I->first == resources[r][j]) {
+ //Get the number of available for this resource
+ unsigned numResource = CPUResource::getCPUResource(resources[r][j])->maxNumUsers;
+ nodesUsingResource = &(I->second);
+
+ //Check that there are enough of this resource, otherwise
+ //we need to increase/decrease the cycle
+ if(I->second.size() >= numResource) {
+ DEBUG(std::cerr << "No open spot for this resource in this cycle\n");
+ increaseSC = true;
+ }
+ break;
+
+ }
+ //safe to put into schedule
+ }
+ if(increaseSC)
+ break;
-Pass *createModuloSchedulingPass(const TargetMachine &tgt) {
- return new ModuloSchedulingPass(tgt);
+ else {
+ DEBUG(std::cerr << "Found spot in schedule\n");
+ //Add node to resource vector
+ if(nodesUsingResource == 0) {
+ nodesUsingResource = new std::vector<MSchedGraphNode*>;
+ resourceForCycle.push_back(std::make_pair(resources[r][j], *nodesUsingResource));
+ }
+
+ nodesUsingResource->push_back(node);
+
+ schedule[intermediateCycle] = resourceForCycle;
+ }
+ }
+ if(increaseSC) {
+ /*for(unsigned x = 0; x < r; ++x) {
+ unsigned removeCycle = x + start;
+ for(unsigned j=0; j < resources[x].size(); ++j) {
+ std::vector<std::pair<unsigned, MSchedGraphNode*> > resourceForCycle = schedule[removeCycle];
+ for(std::vector<std::pair<unsigned,MSchedGraphNode*> >::iterator I = resourceForCycle.begin(), E= resourceForCycle.end(); I != E; ++I) {
+ if(I->first == resources[x][j]) {
+ //remove it
+ resourceForCycle.erase(I);
+ }
+ }
+ //Put vector back
+ schedule[removeCycle] = resourceForCycle;
+ }
+ }*/
+
+ break;
+ }
+ }
+ if(!increaseSC)
+ return true;
+
+ //Increment cycle to try again
+ if(forward) {
+ ++cycle;
+ DEBUG(std::cerr << "Increase cycle: " << cycle << "\n");
+ if(cycle > end)
+ return false;
+ }
+ else {
+ --cycle;
+ DEBUG(std::cerr << "Decrease cycle: " << cycle << "\n");
+ if(cycle < end)
+ return false;
+ }
+ }
+ return success;
}
-