blob: eb73a3b093dc3b83ad56024a2f980ee183e4c3b0 [file] [log] [blame]
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001//===-- ModuloScheduling.cpp - ModuloScheduling ----------------*- C++ -*-===//
2//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Tanya Lattnerd14b8372004-03-01 02:50:01 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Tanya Lattnerd14b8372004-03-01 02:50:01 +00009//
Tanya Lattner0a88d2d2004-07-30 23:36:10 +000010// This ModuloScheduling pass is based on the Swing Modulo Scheduling
11// algorithm.
Misha Brukman82fd8d82004-08-02 13:59:10 +000012//
Guochun Shif1c154f2003-03-27 17:57:44 +000013//===----------------------------------------------------------------------===//
14
Tanya Lattnerd14b8372004-03-01 02:50:01 +000015#define DEBUG_TYPE "ModuloSched"
16
17#include "ModuloScheduling.h"
Tanya Lattner0a88d2d2004-07-30 23:36:10 +000018#include "llvm/Instructions.h"
19#include "llvm/Function.h"
Tanya Lattnerd14b8372004-03-01 02:50:01 +000020#include "llvm/CodeGen/MachineFunction.h"
21#include "llvm/CodeGen/Passes.h"
22#include "llvm/Support/CFG.h"
23#include "llvm/Target/TargetSchedInfo.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000024#include "llvm/Support/Debug.h"
25#include "llvm/Support/GraphWriter.h"
26#include "llvm/ADT/StringExtras.h"
Tanya Lattnere1df2122004-11-22 20:41:24 +000027#include "llvm/ADT/Statistic.h"
Misha Brukman82fd8d82004-08-02 13:59:10 +000028#include <cmath>
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +000029#include <algorithm>
Tanya Lattnerd14b8372004-03-01 02:50:01 +000030#include <fstream>
31#include <sstream>
Misha Brukman82fd8d82004-08-02 13:59:10 +000032#include <utility>
33#include <vector>
Misha Brukman7da1e6e2004-10-10 23:34:50 +000034#include "../MachineCodeForInstruction.h"
35#include "../SparcV9TmpInstr.h"
36#include "../SparcV9Internals.h"
37#include "../SparcV9RegisterInfo.h"
Tanya Lattnerd14b8372004-03-01 02:50:01 +000038using namespace llvm;
39
40/// Create ModuloSchedulingPass
41///
42FunctionPass *llvm::createModuloSchedulingPass(TargetMachine & targ) {
43 DEBUG(std::cerr << "Created ModuloSchedulingPass\n");
44 return new ModuloSchedulingPass(targ);
45}
46
Tanya Lattner0a88d2d2004-07-30 23:36:10 +000047
48//Graph Traits for printing out the dependence graph
Tanya Lattnerd14b8372004-03-01 02:50:01 +000049template<typename GraphType>
50static void WriteGraphToFile(std::ostream &O, const std::string &GraphName,
51 const GraphType &GT) {
52 std::string Filename = GraphName + ".dot";
53 O << "Writing '" << Filename << "'...";
54 std::ofstream F(Filename.c_str());
55
56 if (F.good())
57 WriteGraph(F, GT);
58 else
59 O << " error opening file for writing!";
60 O << "\n";
61};
Guochun Shif1c154f2003-03-27 17:57:44 +000062
Tanya Lattner0a88d2d2004-07-30 23:36:10 +000063//Graph Traits for printing out the dependence graph
Brian Gaeked0fde302003-11-11 22:41:34 +000064namespace llvm {
Tanya Lattnere1df2122004-11-22 20:41:24 +000065 Statistic<> ValidLoops("modulosched-validLoops", "Number of candidate loops modulo-scheduled");
66 Statistic<> MSLoops("modulosched-schedLoops", "Number of loops successfully modulo-scheduled");
67 Statistic<> IncreasedII("modulosched-increasedII", "Number of times we had to increase II");
Brian Gaeked0fde302003-11-11 22:41:34 +000068
Tanya Lattnerd14b8372004-03-01 02:50:01 +000069 template<>
70 struct DOTGraphTraits<MSchedGraph*> : public DefaultDOTGraphTraits {
71 static std::string getGraphName(MSchedGraph *F) {
72 return "Dependence Graph";
73 }
Guochun Shi8f1d4ab2003-06-08 23:16:07 +000074
Tanya Lattnerd14b8372004-03-01 02:50:01 +000075 static std::string getNodeLabel(MSchedGraphNode *Node, MSchedGraph *Graph) {
76 if (Node->getInst()) {
77 std::stringstream ss;
78 ss << *(Node->getInst());
79 return ss.str(); //((MachineInstr*)Node->getInst());
80 }
81 else
82 return "No Inst";
83 }
84 static std::string getEdgeSourceLabel(MSchedGraphNode *Node,
85 MSchedGraphNode::succ_iterator I) {
86 //Label each edge with the type of dependence
87 std::string edgelabel = "";
88 switch (I.getEdge().getDepOrderType()) {
89
90 case MSchedGraphEdge::TrueDep:
91 edgelabel = "True";
92 break;
93
94 case MSchedGraphEdge::AntiDep:
95 edgelabel = "Anti";
96 break;
97
98 case MSchedGraphEdge::OutputDep:
99 edgelabel = "Output";
100 break;
101
102 default:
103 edgelabel = "Unknown";
104 break;
105 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000106
107 //FIXME
108 int iteDiff = I.getEdge().getIteDiff();
109 std::string intStr = "(IteDiff: ";
110 intStr += itostr(iteDiff);
111
112 intStr += ")";
113 edgelabel += intStr;
114
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000115 return edgelabel;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000116 }
Guochun Shif1c154f2003-03-27 17:57:44 +0000117 };
Guochun Shif1c154f2003-03-27 17:57:44 +0000118}
Tanya Lattner4f839cc2003-08-28 17:12:14 +0000119
Misha Brukmanaa41c3c2003-10-10 17:41:32 +0000120/// ModuloScheduling::runOnFunction - main transformation entry point
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000121/// The Swing Modulo Schedule algorithm has three basic steps:
122/// 1) Computation and Analysis of the dependence graph
123/// 2) Ordering of the nodes
124/// 3) Scheduling
125///
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000126bool ModuloSchedulingPass::runOnFunction(Function &F) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000127
Tanya Lattner4f839cc2003-08-28 17:12:14 +0000128 bool Changed = false;
Tanya Lattnerced82222004-11-16 21:31:37 +0000129 int numMS = 0;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000130
Tanya Lattner420025b2004-10-10 22:44:35 +0000131 DEBUG(std::cerr << "Creating ModuloSchedGraph for each valid BasicBlock in " + F.getName() + "\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000132
133 //Get MachineFunction
134 MachineFunction &MF = MachineFunction::get(&F);
Tanya Lattner260652a2004-10-30 00:39:07 +0000135
136
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000137 //Worklist
138 std::vector<MachineBasicBlock*> Worklist;
139
140 //Iterate over BasicBlocks and put them into our worklist if they are valid
141 for (MachineFunction::iterator BI = MF.begin(); BI != MF.end(); ++BI)
Tanya Lattnere1df2122004-11-22 20:41:24 +0000142 if(MachineBBisValid(BI)) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000143 Worklist.push_back(&*BI);
Tanya Lattnere1df2122004-11-22 20:41:24 +0000144 ++ValidLoops;
145 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000146
Tanya Lattner80f08552004-11-02 21:04:56 +0000147 defaultInst = 0;
148
Tanya Lattner420025b2004-10-10 22:44:35 +0000149 DEBUG(if(Worklist.size() == 0) std::cerr << "No single basic block loops in function to ModuloSchedule\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000150
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000151 //Iterate over the worklist and perform scheduling
152 for(std::vector<MachineBasicBlock*>::iterator BI = Worklist.begin(),
153 BE = Worklist.end(); BI != BE; ++BI) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000154
Tanya Lattnerced82222004-11-16 21:31:37 +0000155 CreateDefMap(*BI);
156
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000157 MSchedGraph *MSG = new MSchedGraph(*BI, target);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000158
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000159 //Write Graph out to file
160 DEBUG(WriteGraphToFile(std::cerr, F.getName(), MSG));
161
162 //Print out BB for debugging
Tanya Lattner420025b2004-10-10 22:44:35 +0000163 DEBUG(std::cerr << "ModuloScheduling BB: \n"; (*BI)->print(std::cerr));
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000164
165 //Calculate Resource II
166 int ResMII = calculateResMII(*BI);
167
168 //Calculate Recurrence II
169 int RecMII = calculateRecMII(MSG, ResMII);
170
171 //Our starting initiation interval is the maximum of RecMII and ResMII
172 II = std::max(RecMII, ResMII);
173
174 //Print out II, RecMII, and ResMII
Tanya Lattner260652a2004-10-30 00:39:07 +0000175 DEBUG(std::cerr << "II starts out as " << II << " ( RecMII=" << RecMII << " and ResMII=" << ResMII << ")\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000176
Tanya Lattner260652a2004-10-30 00:39:07 +0000177 //Dump node properties if in debug mode
178 DEBUG(for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(),
179 E = nodeToAttributesMap.end(); I !=E; ++I) {
180 std::cerr << "Node: " << *(I->first) << " ASAP: " << I->second.ASAP << " ALAP: "
181 << I->second.ALAP << " MOB: " << I->second.MOB << " Depth: " << I->second.depth
182 << " Height: " << I->second.height << "\n";
183 });
184
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000185 //Calculate Node Properties
186 calculateNodeAttributes(MSG, ResMII);
187
188 //Dump node properties if in debug mode
189 DEBUG(for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(),
190 E = nodeToAttributesMap.end(); I !=E; ++I) {
191 std::cerr << "Node: " << *(I->first) << " ASAP: " << I->second.ASAP << " ALAP: "
192 << I->second.ALAP << " MOB: " << I->second.MOB << " Depth: " << I->second.depth
193 << " Height: " << I->second.height << "\n";
194 });
195
196 //Put nodes in order to schedule them
197 computePartialOrder();
198
199 //Dump out partial order
Tanya Lattner260652a2004-10-30 00:39:07 +0000200 DEBUG(for(std::vector<std::set<MSchedGraphNode*> >::iterator I = partialOrder.begin(),
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000201 E = partialOrder.end(); I !=E; ++I) {
202 std::cerr << "Start set in PO\n";
Tanya Lattner260652a2004-10-30 00:39:07 +0000203 for(std::set<MSchedGraphNode*>::iterator J = I->begin(), JE = I->end(); J != JE; ++J)
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000204 std::cerr << "PO:" << **J << "\n";
205 });
206
207 //Place nodes in final order
208 orderNodes();
209
210 //Dump out order of nodes
211 DEBUG(for(std::vector<MSchedGraphNode*>::iterator I = FinalNodeOrder.begin(), E = FinalNodeOrder.end(); I != E; ++I) {
212 std::cerr << "FO:" << **I << "\n";
213 });
214
215 //Finally schedule nodes
216 computeSchedule();
217
218 //Print out final schedule
219 DEBUG(schedule.print(std::cerr));
220
Tanya Lattner260652a2004-10-30 00:39:07 +0000221 //Final scheduling step is to reconstruct the loop only if we actual have
222 //stage > 0
Tanya Lattnerced82222004-11-16 21:31:37 +0000223 if(schedule.getMaxStage() != 0) {
Tanya Lattner260652a2004-10-30 00:39:07 +0000224 reconstructLoop(*BI);
Tanya Lattnere1df2122004-11-22 20:41:24 +0000225 ++MSLoops;
Tanya Lattnerced82222004-11-16 21:31:37 +0000226 Changed = true;
227 }
Tanya Lattner260652a2004-10-30 00:39:07 +0000228 else
229 DEBUG(std::cerr << "Max stage is 0, so no change in loop\n");
230
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000231 //Clear out our maps for the next basic block that is processed
232 nodeToAttributesMap.clear();
233 partialOrder.clear();
234 recurrenceList.clear();
235 FinalNodeOrder.clear();
236 schedule.clear();
Tanya Lattnerced82222004-11-16 21:31:37 +0000237 defMap.clear();
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000238 //Clean up. Nuke old MachineBB and llvmBB
239 //BasicBlock *llvmBB = (BasicBlock*) (*BI)->getBasicBlock();
240 //Function *parent = (Function*) llvmBB->getParent();
241 //Should't std::find work??
242 //parent->getBasicBlockList().erase(std::find(parent->getBasicBlockList().begin(), parent->getBasicBlockList().end(), *llvmBB));
243 //parent->getBasicBlockList().erase(llvmBB);
244
245 //delete(llvmBB);
246 //delete(*BI);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000247 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000248
Tanya Lattner4f839cc2003-08-28 17:12:14 +0000249 return Changed;
250}
Brian Gaeked0fde302003-11-11 22:41:34 +0000251
Tanya Lattnerced82222004-11-16 21:31:37 +0000252void ModuloSchedulingPass::CreateDefMap(MachineBasicBlock *BI) {
253 defaultInst = 0;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000254
Tanya Lattnerced82222004-11-16 21:31:37 +0000255 for(MachineBasicBlock::iterator I = BI->begin(), E = BI->end(); I != E; ++I) {
256 for(unsigned opNum = 0; opNum < I->getNumOperands(); ++opNum) {
257 const MachineOperand &mOp = I->getOperand(opNum);
258 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef()) {
Tanya Lattnere1df2122004-11-22 20:41:24 +0000259 //assert if this is the second def we have seen
260 DEBUG(std::cerr << "Putting " << *(mOp.getVRegValue()) << " into map\n");
261 assert(!defMap.count(mOp.getVRegValue()) && "Def already in the map");
262
Tanya Lattnerced82222004-11-16 21:31:37 +0000263 defMap[mOp.getVRegValue()] = &*I;
264 }
265
266 //See if we can use this Value* as our defaultInst
267 if(!defaultInst && mOp.getType() == MachineOperand::MO_VirtualRegister) {
268 Value *V = mOp.getVRegValue();
269 if(!isa<TmpInstruction>(V) && !isa<Argument>(V) && !isa<Constant>(V) && !isa<PHINode>(V))
270 defaultInst = (Instruction*) V;
271 }
272 }
273 }
Tanya Lattnere1df2122004-11-22 20:41:24 +0000274
Tanya Lattnerced82222004-11-16 21:31:37 +0000275 assert(defaultInst && "We must have a default instruction to use as our main point to add to machine code for instruction\n");
276
277}
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000278/// This function checks if a Machine Basic Block is valid for modulo
279/// scheduling. This means that it has no control flow (if/else or
280/// calls) in the block. Currently ModuloScheduling only works on
281/// single basic block loops.
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000282bool ModuloSchedulingPass::MachineBBisValid(const MachineBasicBlock *BI) {
283
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000284 bool isLoop = false;
285
286 //Check first if its a valid loop
287 for(succ_const_iterator I = succ_begin(BI->getBasicBlock()),
288 E = succ_end(BI->getBasicBlock()); I != E; ++I) {
289 if (*I == BI->getBasicBlock()) // has single block loop
290 isLoop = true;
291 }
292
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000293 if(!isLoop)
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000294 return false;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000295
Tanya Lattnere1df2122004-11-22 20:41:24 +0000296 //Check size of our basic block.. make sure we have more then just the terminator in it
297 if(BI->getBasicBlock()->size() == 1)
298 return false;
299
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000300 //Get Target machine instruction info
301 const TargetInstrInfo *TMI = target.getInstrInfo();
302
303 //Check each instruction and look for calls
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000304 for(MachineBasicBlock::const_iterator I = BI->begin(), E = BI->end(); I != E; ++I) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000305 //Get opcode to check instruction type
306 MachineOpCode OC = I->getOpcode();
307 if(TMI->isCall(OC))
308 return false;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000309 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000310 return true;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000311}
312
313//ResMII is calculated by determining the usage count for each resource
314//and using the maximum.
315//FIXME: In future there should be a way to get alternative resources
316//for each instruction
317int ModuloSchedulingPass::calculateResMII(const MachineBasicBlock *BI) {
318
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000319 const TargetInstrInfo *mii = target.getInstrInfo();
320 const TargetSchedInfo *msi = target.getSchedInfo();
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000321
322 int ResMII = 0;
323
324 //Map to keep track of usage count of each resource
325 std::map<unsigned, unsigned> resourceUsageCount;
326
327 for(MachineBasicBlock::const_iterator I = BI->begin(), E = BI->end(); I != E; ++I) {
328
329 //Get resource usage for this instruction
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000330 InstrRUsage rUsage = msi->getInstrRUsage(I->getOpcode());
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000331 std::vector<std::vector<resourceId_t> > resources = rUsage.resourcesByCycle;
332
333 //Loop over resources in each cycle and increments their usage count
334 for(unsigned i=0; i < resources.size(); ++i)
335 for(unsigned j=0; j < resources[i].size(); ++j) {
336 if( resourceUsageCount.find(resources[i][j]) == resourceUsageCount.end()) {
337 resourceUsageCount[resources[i][j]] = 1;
338 }
339 else {
340 resourceUsageCount[resources[i][j]] = resourceUsageCount[resources[i][j]] + 1;
341 }
342 }
343 }
344
345 //Find maximum usage count
346
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000347 //Get max number of instructions that can be issued at once. (FIXME)
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000348 int issueSlots = msi->maxNumIssueTotal;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000349
350 for(std::map<unsigned,unsigned>::iterator RB = resourceUsageCount.begin(), RE = resourceUsageCount.end(); RB != RE; ++RB) {
Tanya Lattner4cffb582004-05-26 06:27:18 +0000351
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000352 //Get the total number of the resources in our cpu
Tanya Lattner4cffb582004-05-26 06:27:18 +0000353 int resourceNum = CPUResource::getCPUResource(RB->first)->maxNumUsers;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000354
355 //Get total usage count for this resources
356 unsigned usageCount = RB->second;
357
358 //Divide the usage count by either the max number we can issue or the number of
359 //resources (whichever is its upper bound)
360 double finalUsageCount;
Tanya Lattner4cffb582004-05-26 06:27:18 +0000361 if( resourceNum <= issueSlots)
362 finalUsageCount = ceil(1.0 * usageCount / resourceNum);
363 else
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000364 finalUsageCount = ceil(1.0 * usageCount / issueSlots);
365
366
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000367 //Only keep track of the max
368 ResMII = std::max( (int) finalUsageCount, ResMII);
369
370 }
371
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000372 return ResMII;
373
374}
375
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000376/// calculateRecMII - Calculates the value of the highest recurrence
377/// By value we mean the total latency
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000378int ModuloSchedulingPass::calculateRecMII(MSchedGraph *graph, int MII) {
379 std::vector<MSchedGraphNode*> vNodes;
380 //Loop over all nodes in the graph
381 for(MSchedGraph::iterator I = graph->begin(), E = graph->end(); I != E; ++I) {
382 findAllReccurrences(I->second, vNodes, MII);
383 vNodes.clear();
384 }
385
386 int RecMII = 0;
387
388 for(std::set<std::pair<int, std::vector<MSchedGraphNode*> > >::iterator I = recurrenceList.begin(), E=recurrenceList.end(); I !=E; ++I) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000389 DEBUG(for(std::vector<MSchedGraphNode*>::const_iterator N = I->second.begin(), NE = I->second.end(); N != NE; ++N) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000390 std::cerr << **N << "\n";
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000391 });
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000392 RecMII = std::max(RecMII, I->first);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000393 }
394
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000395 return MII;
396}
397
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000398/// calculateNodeAttributes - The following properties are calculated for
399/// each node in the dependence graph: ASAP, ALAP, Depth, Height, and
400/// MOB.
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000401void ModuloSchedulingPass::calculateNodeAttributes(MSchedGraph *graph, int MII) {
402
Tanya Lattner260652a2004-10-30 00:39:07 +0000403 assert(nodeToAttributesMap.empty() && "Node attribute map was not cleared");
404
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000405 //Loop over the nodes and add them to the map
406 for(MSchedGraph::iterator I = graph->begin(), E = graph->end(); I != E; ++I) {
Tanya Lattner260652a2004-10-30 00:39:07 +0000407
408 DEBUG(std::cerr << "Inserting node into attribute map: " << *I->second << "\n");
409
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000410 //Assert if its already in the map
Tanya Lattner260652a2004-10-30 00:39:07 +0000411 assert(nodeToAttributesMap.count(I->second) == 0 &&
412 "Node attributes are already in the map");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000413
414 //Put into the map with default attribute values
415 nodeToAttributesMap[I->second] = MSNodeAttributes();
416 }
417
418 //Create set to deal with reccurrences
419 std::set<MSchedGraphNode*> visitedNodes;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000420
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000421 //Now Loop over map and calculate the node attributes
422 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000423 calculateASAP(I->first, MII, (MSchedGraphNode*) 0);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000424 visitedNodes.clear();
425 }
426
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000427 int maxASAP = findMaxASAP();
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000428 //Calculate ALAP which depends on ASAP being totally calculated
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000429 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
430 calculateALAP(I->first, MII, maxASAP, (MSchedGraphNode*) 0);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000431 visitedNodes.clear();
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000432 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000433
434 //Calculate MOB which depends on ASAP being totally calculated, also do depth and height
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000435 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
436 (I->second).MOB = std::max(0,(I->second).ALAP - (I->second).ASAP);
437
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000438 DEBUG(std::cerr << "MOB: " << (I->second).MOB << " (" << *(I->first) << ")\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000439 calculateDepth(I->first, (MSchedGraphNode*) 0);
440 calculateHeight(I->first, (MSchedGraphNode*) 0);
441 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000442
443
444}
445
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000446/// ignoreEdge - Checks to see if this edge of a recurrence should be ignored or not
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000447bool ModuloSchedulingPass::ignoreEdge(MSchedGraphNode *srcNode, MSchedGraphNode *destNode) {
448 if(destNode == 0 || srcNode ==0)
449 return false;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000450
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000451 bool findEdge = edgesToIgnore.count(std::make_pair(srcNode, destNode->getInEdgeNum(srcNode)));
Tanya Lattner4cffb582004-05-26 06:27:18 +0000452
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000453 return findEdge;
454}
455
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000456
457/// calculateASAP - Calculates the
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000458int ModuloSchedulingPass::calculateASAP(MSchedGraphNode *node, int MII, MSchedGraphNode *destNode) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000459
460 DEBUG(std::cerr << "Calculating ASAP for " << *node << "\n");
461
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000462 //Get current node attributes
463 MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
464
465 if(attributes.ASAP != -1)
466 return attributes.ASAP;
467
468 int maxPredValue = 0;
469
470 //Iterate over all of the predecessors and find max
471 for(MSchedGraphNode::pred_iterator P = node->pred_begin(), E = node->pred_end(); P != E; ++P) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000472
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000473 //Only process if we are not ignoring the edge
474 if(!ignoreEdge(*P, node)) {
475 int predASAP = -1;
476 predASAP = calculateASAP(*P, MII, node);
477
478 assert(predASAP != -1 && "ASAP has not been calculated");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000479 int iteDiff = node->getInEdge(*P).getIteDiff();
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000480
481 int currentPredValue = predASAP + (*P)->getLatency() - (iteDiff * MII);
482 DEBUG(std::cerr << "pred ASAP: " << predASAP << ", iteDiff: " << iteDiff << ", PredLatency: " << (*P)->getLatency() << ", Current ASAP pred: " << currentPredValue << "\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000483 maxPredValue = std::max(maxPredValue, currentPredValue);
484 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000485 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000486
487 attributes.ASAP = maxPredValue;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000488
489 DEBUG(std::cerr << "ASAP: " << attributes.ASAP << " (" << *node << ")\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000490
491 return maxPredValue;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000492}
493
494
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000495int ModuloSchedulingPass::calculateALAP(MSchedGraphNode *node, int MII,
496 int maxASAP, MSchedGraphNode *srcNode) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000497
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000498 DEBUG(std::cerr << "Calculating ALAP for " << *node << "\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000499
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000500 MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
501
502 if(attributes.ALAP != -1)
503 return attributes.ALAP;
504
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000505 if(node->hasSuccessors()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000506
507 //Trying to deal with the issue where the node has successors, but
508 //we are ignoring all of the edges to them. So this is my hack for
509 //now.. there is probably a more elegant way of doing this (FIXME)
510 bool processedOneEdge = false;
511
512 //FIXME, set to something high to start
513 int minSuccValue = 9999999;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000514
515 //Iterate over all of the predecessors and fine max
516 for(MSchedGraphNode::succ_iterator P = node->succ_begin(),
517 E = node->succ_end(); P != E; ++P) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000518
519 //Only process if we are not ignoring the edge
520 if(!ignoreEdge(node, *P)) {
521 processedOneEdge = true;
522 int succALAP = -1;
523 succALAP = calculateALAP(*P, MII, maxASAP, node);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000524
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000525 assert(succALAP != -1 && "Successors ALAP should have been caclulated");
526
527 int iteDiff = P.getEdge().getIteDiff();
528
529 int currentSuccValue = succALAP - node->getLatency() + iteDiff * MII;
530
531 DEBUG(std::cerr << "succ ALAP: " << succALAP << ", iteDiff: " << iteDiff << ", SuccLatency: " << (*P)->getLatency() << ", Current ALAP succ: " << currentSuccValue << "\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000532
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000533 minSuccValue = std::min(minSuccValue, currentSuccValue);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000534 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000535 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000536
537 if(processedOneEdge)
538 attributes.ALAP = minSuccValue;
539
540 else
541 attributes.ALAP = maxASAP;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000542 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000543 else
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000544 attributes.ALAP = maxASAP;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000545
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000546 DEBUG(std::cerr << "ALAP: " << attributes.ALAP << " (" << *node << ")\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000547
548 if(attributes.ALAP < 0)
549 attributes.ALAP = 0;
550
551 return attributes.ALAP;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000552}
553
554int ModuloSchedulingPass::findMaxASAP() {
555 int maxASAP = 0;
556
557 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(),
558 E = nodeToAttributesMap.end(); I != E; ++I)
559 maxASAP = std::max(maxASAP, I->second.ASAP);
560 return maxASAP;
561}
562
563
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000564int ModuloSchedulingPass::calculateHeight(MSchedGraphNode *node,MSchedGraphNode *srcNode) {
565
566 MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000567
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000568 if(attributes.height != -1)
569 return attributes.height;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000570
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000571 int maxHeight = 0;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000572
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000573 //Iterate over all of the predecessors and find max
574 for(MSchedGraphNode::succ_iterator P = node->succ_begin(),
575 E = node->succ_end(); P != E; ++P) {
576
577
578 if(!ignoreEdge(node, *P)) {
579 int succHeight = calculateHeight(*P, node);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000580
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000581 assert(succHeight != -1 && "Successors Height should have been caclulated");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000582
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000583 int currentHeight = succHeight + node->getLatency();
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000584 maxHeight = std::max(maxHeight, currentHeight);
585 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000586 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000587 attributes.height = maxHeight;
588 DEBUG(std::cerr << "Height: " << attributes.height << " (" << *node << ")\n");
589 return maxHeight;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000590}
591
592
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000593int ModuloSchedulingPass::calculateDepth(MSchedGraphNode *node,
594 MSchedGraphNode *destNode) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000595
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000596 MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000597
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000598 if(attributes.depth != -1)
599 return attributes.depth;
600
601 int maxDepth = 0;
602
603 //Iterate over all of the predecessors and fine max
604 for(MSchedGraphNode::pred_iterator P = node->pred_begin(), E = node->pred_end(); P != E; ++P) {
605
606 if(!ignoreEdge(*P, node)) {
607 int predDepth = -1;
608 predDepth = calculateDepth(*P, node);
609
610 assert(predDepth != -1 && "Predecessors ASAP should have been caclulated");
611
612 int currentDepth = predDepth + (*P)->getLatency();
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000613 maxDepth = std::max(maxDepth, currentDepth);
614 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000615 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000616 attributes.depth = maxDepth;
617
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000618 DEBUG(std::cerr << "Depth: " << attributes.depth << " (" << *node << "*)\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000619 return maxDepth;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000620}
621
622
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000623
624void ModuloSchedulingPass::addReccurrence(std::vector<MSchedGraphNode*> &recurrence, int II, MSchedGraphNode *srcBENode, MSchedGraphNode *destBENode) {
625 //Check to make sure that this recurrence is unique
626 bool same = false;
627
628
629 //Loop over all recurrences already in our list
630 for(std::set<std::pair<int, std::vector<MSchedGraphNode*> > >::iterator R = recurrenceList.begin(), RE = recurrenceList.end(); R != RE; ++R) {
631
632 bool all_same = true;
633 //First compare size
634 if(R->second.size() == recurrence.size()) {
635
636 for(std::vector<MSchedGraphNode*>::const_iterator node = R->second.begin(), end = R->second.end(); node != end; ++node) {
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000637 if(std::find(recurrence.begin(), recurrence.end(), *node) == recurrence.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000638 all_same = all_same && false;
639 break;
640 }
641 else
642 all_same = all_same && true;
643 }
644 if(all_same) {
645 same = true;
646 break;
647 }
648 }
649 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000650
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000651 if(!same) {
Tanya Lattner4cffb582004-05-26 06:27:18 +0000652 srcBENode = recurrence.back();
653 destBENode = recurrence.front();
654
655 //FIXME
656 if(destBENode->getInEdge(srcBENode).getIteDiff() == 0) {
657 //DEBUG(std::cerr << "NOT A BACKEDGE\n");
658 //find actual backedge HACK HACK
659 for(unsigned i=0; i< recurrence.size()-1; ++i) {
660 if(recurrence[i+1]->getInEdge(recurrence[i]).getIteDiff() == 1) {
661 srcBENode = recurrence[i];
662 destBENode = recurrence[i+1];
663 break;
664 }
665
666 }
667
668 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000669 DEBUG(std::cerr << "Back Edge to Remove: " << *srcBENode << " to " << *destBENode << "\n");
670 edgesToIgnore.insert(std::make_pair(srcBENode, destBENode->getInEdgeNum(srcBENode)));
671 recurrenceList.insert(std::make_pair(II, recurrence));
672 }
673
674}
675
676void ModuloSchedulingPass::findAllReccurrences(MSchedGraphNode *node,
677 std::vector<MSchedGraphNode*> &visitedNodes,
678 int II) {
679
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000680 if(std::find(visitedNodes.begin(), visitedNodes.end(), node) != visitedNodes.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000681 std::vector<MSchedGraphNode*> recurrence;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000682 bool first = true;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000683 int delay = 0;
684 int distance = 0;
685 int RecMII = II; //Starting value
686 MSchedGraphNode *last = node;
Chris Lattner46c2b3a2004-08-04 03:51:55 +0000687 MSchedGraphNode *srcBackEdge = 0;
688 MSchedGraphNode *destBackEdge = 0;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000689
690
691
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000692 for(std::vector<MSchedGraphNode*>::iterator I = visitedNodes.begin(), E = visitedNodes.end();
693 I !=E; ++I) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000694
695 if(*I == node)
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000696 first = false;
697 if(first)
698 continue;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000699
700 delay = delay + (*I)->getLatency();
701
702 if(*I != node) {
703 int diff = (*I)->getInEdge(last).getIteDiff();
704 distance += diff;
705 if(diff > 0) {
706 srcBackEdge = last;
707 destBackEdge = *I;
708 }
709 }
710
711 recurrence.push_back(*I);
712 last = *I;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000713 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000714
715
716
717 //Get final distance calc
718 distance += node->getInEdge(last).getIteDiff();
Tanya Lattnere1df2122004-11-22 20:41:24 +0000719 DEBUG(std::cerr << "Reccurrence Distance: " << distance << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000720
721 //Adjust II until we get close to the inequality delay - II*distance <= 0
722
723 int value = delay-(RecMII * distance);
724 int lastII = II;
725 while(value <= 0) {
726
727 lastII = RecMII;
728 RecMII--;
729 value = delay-(RecMII * distance);
730 }
731
732
733 DEBUG(std::cerr << "Final II for this recurrence: " << lastII << "\n");
734 addReccurrence(recurrence, lastII, srcBackEdge, destBackEdge);
735 assert(distance != 0 && "Recurrence distance should not be zero");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000736 return;
737 }
738
739 for(MSchedGraphNode::succ_iterator I = node->succ_begin(), E = node->succ_end(); I != E; ++I) {
740 visitedNodes.push_back(node);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000741 findAllReccurrences(*I, visitedNodes, II);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000742 visitedNodes.pop_back();
743 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000744}
745
746
747
748
749
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000750void ModuloSchedulingPass::computePartialOrder() {
751
752
753 //Loop over all recurrences and add to our partial order
754 //be sure to remove nodes that are already in the partial order in
755 //a different recurrence and don't add empty recurrences.
756 for(std::set<std::pair<int, std::vector<MSchedGraphNode*> > >::reverse_iterator I = recurrenceList.rbegin(), E=recurrenceList.rend(); I !=E; ++I) {
757
758 //Add nodes that connect this recurrence to the previous recurrence
759
760 //If this is the first recurrence in the partial order, add all predecessors
761 for(std::vector<MSchedGraphNode*>::const_iterator N = I->second.begin(), NE = I->second.end(); N != NE; ++N) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000762
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000763 }
764
765
Tanya Lattner260652a2004-10-30 00:39:07 +0000766 std::set<MSchedGraphNode*> new_recurrence;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000767 //Loop through recurrence and remove any nodes already in the partial order
768 for(std::vector<MSchedGraphNode*>::const_iterator N = I->second.begin(), NE = I->second.end(); N != NE; ++N) {
769 bool found = false;
Tanya Lattner260652a2004-10-30 00:39:07 +0000770 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(), PE = partialOrder.end(); PO != PE; ++PO) {
771 if(PO->count(*N))
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000772 found = true;
773 }
774 if(!found) {
Tanya Lattner260652a2004-10-30 00:39:07 +0000775 new_recurrence.insert(*N);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000776
777 if(partialOrder.size() == 0)
778 //For each predecessors, add it to this recurrence ONLY if it is not already in it
779 for(MSchedGraphNode::pred_iterator P = (*N)->pred_begin(),
780 PE = (*N)->pred_end(); P != PE; ++P) {
781
782 //Check if we are supposed to ignore this edge or not
783 if(!ignoreEdge(*P, *N))
784 //Check if already in this recurrence
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000785 if(std::find(I->second.begin(), I->second.end(), *P) == I->second.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000786 //Also need to check if in partial order
787 bool predFound = false;
Tanya Lattner260652a2004-10-30 00:39:07 +0000788 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(), PEND = partialOrder.end(); PO != PEND; ++PO) {
789 if(PO->count(*P))
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000790 predFound = true;
791 }
792
793 if(!predFound)
Tanya Lattner260652a2004-10-30 00:39:07 +0000794 if(!new_recurrence.count(*P))
795 new_recurrence.insert(*P);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000796
797 }
798 }
799 }
800 }
801
802
803 if(new_recurrence.size() > 0)
804 partialOrder.push_back(new_recurrence);
805 }
806
807 //Add any nodes that are not already in the partial order
Tanya Lattner260652a2004-10-30 00:39:07 +0000808 //Add them in a set, one set per connected component
809 std::set<MSchedGraphNode*> lastNodes;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000810 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
811 bool found = false;
812 //Check if its already in our partial order, if not add it to the final vector
Tanya Lattner260652a2004-10-30 00:39:07 +0000813 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(), PE = partialOrder.end(); PO != PE; ++PO) {
814 if(PO->count(I->first))
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000815 found = true;
816 }
817 if(!found)
Tanya Lattner260652a2004-10-30 00:39:07 +0000818 lastNodes.insert(I->first);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000819 }
820
Tanya Lattner260652a2004-10-30 00:39:07 +0000821 //Break up remaining nodes that are not in the partial order
822 //into their connected compoenents
823 while(lastNodes.size() > 0) {
824 std::set<MSchedGraphNode*> ccSet;
825 connectedComponentSet(*(lastNodes.begin()),ccSet, lastNodes);
826 if(ccSet.size() > 0)
827 partialOrder.push_back(ccSet);
828 }
829 //if(lastNodes.size() > 0)
830 //partialOrder.push_back(lastNodes);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000831
832}
833
834
Tanya Lattner260652a2004-10-30 00:39:07 +0000835void ModuloSchedulingPass::connectedComponentSet(MSchedGraphNode *node, std::set<MSchedGraphNode*> &ccSet, std::set<MSchedGraphNode*> &lastNodes) {
836
837 //Add to final set
838 if( !ccSet.count(node) && lastNodes.count(node)) {
839 lastNodes.erase(node);
840 ccSet.insert(node);
841 }
842 else
843 return;
844
845 //Loop over successors and recurse if we have not seen this node before
846 for(MSchedGraphNode::succ_iterator node_succ = node->succ_begin(), end=node->succ_end(); node_succ != end; ++node_succ) {
847 connectedComponentSet(*node_succ, ccSet, lastNodes);
848 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000849
Tanya Lattner260652a2004-10-30 00:39:07 +0000850}
851
852void ModuloSchedulingPass::predIntersect(std::set<MSchedGraphNode*> &CurrentSet, std::set<MSchedGraphNode*> &IntersectResult) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000853
854 for(unsigned j=0; j < FinalNodeOrder.size(); ++j) {
855 for(MSchedGraphNode::pred_iterator P = FinalNodeOrder[j]->pred_begin(),
856 E = FinalNodeOrder[j]->pred_end(); P != E; ++P) {
857
858 //Check if we are supposed to ignore this edge or not
859 if(ignoreEdge(*P,FinalNodeOrder[j]))
860 continue;
861
Tanya Lattner260652a2004-10-30 00:39:07 +0000862 if(CurrentSet.count(*P))
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000863 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), *P) == FinalNodeOrder.end())
Tanya Lattner260652a2004-10-30 00:39:07 +0000864 IntersectResult.insert(*P);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000865 }
866 }
867}
868
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000869
Tanya Lattner260652a2004-10-30 00:39:07 +0000870
871
872
873void ModuloSchedulingPass::succIntersect(std::set<MSchedGraphNode*> &CurrentSet, std::set<MSchedGraphNode*> &IntersectResult) {
874
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000875 for(unsigned j=0; j < FinalNodeOrder.size(); ++j) {
876 for(MSchedGraphNode::succ_iterator P = FinalNodeOrder[j]->succ_begin(),
877 E = FinalNodeOrder[j]->succ_end(); P != E; ++P) {
878
879 //Check if we are supposed to ignore this edge or not
880 if(ignoreEdge(FinalNodeOrder[j],*P))
881 continue;
882
Tanya Lattner260652a2004-10-30 00:39:07 +0000883 if(CurrentSet.count(*P))
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000884 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), *P) == FinalNodeOrder.end())
Tanya Lattner260652a2004-10-30 00:39:07 +0000885 IntersectResult.insert(*P);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000886 }
887 }
888}
889
Tanya Lattner260652a2004-10-30 00:39:07 +0000890void dumpIntersection(std::set<MSchedGraphNode*> &IntersectCurrent) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000891 std::cerr << "Intersection (";
Tanya Lattner260652a2004-10-30 00:39:07 +0000892 for(std::set<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(), E = IntersectCurrent.end(); I != E; ++I)
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000893 std::cerr << **I << ", ";
894 std::cerr << ")\n";
895}
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000896
897
898
899void ModuloSchedulingPass::orderNodes() {
900
901 int BOTTOM_UP = 0;
902 int TOP_DOWN = 1;
903
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000904 //Set default order
905 int order = BOTTOM_UP;
906
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000907
908 //Loop over all the sets and place them in the final node order
Tanya Lattner260652a2004-10-30 00:39:07 +0000909 for(std::vector<std::set<MSchedGraphNode*> >::iterator CurrentSet = partialOrder.begin(), E= partialOrder.end(); CurrentSet != E; ++CurrentSet) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000910
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000911 DEBUG(std::cerr << "Processing set in S\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000912 DEBUG(dumpIntersection(*CurrentSet));
913
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000914 //Result of intersection
Tanya Lattner260652a2004-10-30 00:39:07 +0000915 std::set<MSchedGraphNode*> IntersectCurrent;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000916
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000917 predIntersect(*CurrentSet, IntersectCurrent);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000918
919 //If the intersection of predecessor and current set is not empty
920 //sort nodes bottom up
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000921 if(IntersectCurrent.size() != 0) {
922 DEBUG(std::cerr << "Final Node Order Predecessors and Current Set interesection is NOT empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000923 order = BOTTOM_UP;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000924 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000925 //If empty, use successors
926 else {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000927 DEBUG(std::cerr << "Final Node Order Predecessors and Current Set interesection is empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000928
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000929 succIntersect(*CurrentSet, IntersectCurrent);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000930
931 //sort top-down
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000932 if(IntersectCurrent.size() != 0) {
933 DEBUG(std::cerr << "Final Node Order Successors and Current Set interesection is NOT empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000934 order = TOP_DOWN;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000935 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000936 else {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000937 DEBUG(std::cerr << "Final Node Order Successors and Current Set interesection is empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000938 //Find node with max ASAP in current Set
939 MSchedGraphNode *node;
940 int maxASAP = 0;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000941 DEBUG(std::cerr << "Using current set of size " << CurrentSet->size() << "to find max ASAP\n");
Tanya Lattner260652a2004-10-30 00:39:07 +0000942 for(std::set<MSchedGraphNode*>::iterator J = CurrentSet->begin(), JE = CurrentSet->end(); J != JE; ++J) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000943 //Get node attributes
Tanya Lattner260652a2004-10-30 00:39:07 +0000944 MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*J)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000945 //assert(nodeAttr != nodeToAttributesMap.end() && "Node not in attributes map!");
Tanya Lattner260652a2004-10-30 00:39:07 +0000946
947 if(maxASAP <= nodeAttr.ASAP) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000948 maxASAP = nodeAttr.ASAP;
Tanya Lattner260652a2004-10-30 00:39:07 +0000949 node = *J;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000950 }
951 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000952 assert(node != 0 && "In node ordering node should not be null");
Tanya Lattner260652a2004-10-30 00:39:07 +0000953 IntersectCurrent.insert(node);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000954 order = BOTTOM_UP;
955 }
956 }
957
958 //Repeat until all nodes are put into the final order from current set
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000959 while(IntersectCurrent.size() > 0) {
960
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000961 if(order == TOP_DOWN) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000962 DEBUG(std::cerr << "Order is TOP DOWN\n");
963
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000964 while(IntersectCurrent.size() > 0) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000965 DEBUG(std::cerr << "Intersection is not empty, so find heighest height\n");
966
967 int MOB = 0;
968 int height = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +0000969 MSchedGraphNode *highestHeightNode = *(IntersectCurrent.begin());
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000970
971 //Find node in intersection with highest heigh and lowest MOB
Tanya Lattner260652a2004-10-30 00:39:07 +0000972 for(std::set<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(),
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000973 E = IntersectCurrent.end(); I != E; ++I) {
974
975 //Get current nodes properties
976 MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*I)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000977
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000978 if(height < nodeAttr.height) {
979 highestHeightNode = *I;
980 height = nodeAttr.height;
981 MOB = nodeAttr.MOB;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000982 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000983 else if(height == nodeAttr.height) {
984 if(MOB > nodeAttr.height) {
985 highestHeightNode = *I;
986 height = nodeAttr.height;
987 MOB = nodeAttr.MOB;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000988 }
989 }
990 }
991
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000992 //Append our node with greatest height to the NodeOrder
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000993 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), highestHeightNode) == FinalNodeOrder.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000994 DEBUG(std::cerr << "Adding node to Final Order: " << *highestHeightNode << "\n");
995 FinalNodeOrder.push_back(highestHeightNode);
996 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000997
998 //Remove V from IntersectOrder
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000999 IntersectCurrent.erase(std::find(IntersectCurrent.begin(),
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001000 IntersectCurrent.end(), highestHeightNode));
1001
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001002
1003 //Intersect V's successors with CurrentSet
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001004 for(MSchedGraphNode::succ_iterator P = highestHeightNode->succ_begin(),
1005 E = highestHeightNode->succ_end(); P != E; ++P) {
1006 //if(lower_bound(CurrentSet->begin(),
1007 // CurrentSet->end(), *P) != CurrentSet->end()) {
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001008 if(std::find(CurrentSet->begin(), CurrentSet->end(), *P) != CurrentSet->end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001009 if(ignoreEdge(highestHeightNode, *P))
1010 continue;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001011 //If not already in Intersect, add
Tanya Lattner260652a2004-10-30 00:39:07 +00001012 if(!IntersectCurrent.count(*P))
1013 IntersectCurrent.insert(*P);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001014 }
1015 }
1016 } //End while loop over Intersect Size
1017
1018 //Change direction
1019 order = BOTTOM_UP;
1020
1021 //Reset Intersect to reflect changes in OrderNodes
1022 IntersectCurrent.clear();
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001023 predIntersect(*CurrentSet, IntersectCurrent);
1024
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001025 } //End If TOP_DOWN
1026
1027 //Begin if BOTTOM_UP
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001028 else {
1029 DEBUG(std::cerr << "Order is BOTTOM UP\n");
1030 while(IntersectCurrent.size() > 0) {
1031 DEBUG(std::cerr << "Intersection of size " << IntersectCurrent.size() << ", finding highest depth\n");
1032
1033 //dump intersection
1034 DEBUG(dumpIntersection(IntersectCurrent));
1035 //Get node with highest depth, if a tie, use one with lowest
1036 //MOB
1037 int MOB = 0;
1038 int depth = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +00001039 MSchedGraphNode *highestDepthNode = *(IntersectCurrent.begin());
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001040
Tanya Lattner260652a2004-10-30 00:39:07 +00001041 for(std::set<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(),
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001042 E = IntersectCurrent.end(); I != E; ++I) {
1043 //Find node attribute in graph
1044 MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*I)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001045
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001046 if(depth < nodeAttr.depth) {
1047 highestDepthNode = *I;
1048 depth = nodeAttr.depth;
1049 MOB = nodeAttr.MOB;
1050 }
1051 else if(depth == nodeAttr.depth) {
1052 if(MOB > nodeAttr.MOB) {
1053 highestDepthNode = *I;
1054 depth = nodeAttr.depth;
1055 MOB = nodeAttr.MOB;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001056 }
1057 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001058 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001059
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001060
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001061
1062 //Append highest depth node to the NodeOrder
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001063 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), highestDepthNode) == FinalNodeOrder.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001064 DEBUG(std::cerr << "Adding node to Final Order: " << *highestDepthNode << "\n");
1065 FinalNodeOrder.push_back(highestDepthNode);
1066 }
1067 //Remove heightestDepthNode from IntersectOrder
Tanya Lattner260652a2004-10-30 00:39:07 +00001068 IntersectCurrent.erase(highestDepthNode);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001069
1070
1071 //Intersect heightDepthNode's pred with CurrentSet
1072 for(MSchedGraphNode::pred_iterator P = highestDepthNode->pred_begin(),
1073 E = highestDepthNode->pred_end(); P != E; ++P) {
Tanya Lattner260652a2004-10-30 00:39:07 +00001074 if(CurrentSet->count(*P)) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001075 if(ignoreEdge(*P, highestDepthNode))
1076 continue;
1077
1078 //If not already in Intersect, add
Tanya Lattner260652a2004-10-30 00:39:07 +00001079 if(!IntersectCurrent.count(*P))
1080 IntersectCurrent.insert(*P);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001081 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001082 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001083
1084 } //End while loop over Intersect Size
1085
1086 //Change order
1087 order = TOP_DOWN;
1088
1089 //Reset IntersectCurrent to reflect changes in OrderNodes
1090 IntersectCurrent.clear();
1091 succIntersect(*CurrentSet, IntersectCurrent);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001092 } //End if BOTTOM_DOWN
1093
Tanya Lattner420025b2004-10-10 22:44:35 +00001094 DEBUG(std::cerr << "Current Intersection Size: " << IntersectCurrent.size() << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001095 }
1096 //End Wrapping while loop
Tanya Lattner420025b2004-10-10 22:44:35 +00001097 DEBUG(std::cerr << "Ending Size of Current Set: " << CurrentSet->size() << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001098 }//End for over all sets of nodes
Tanya Lattner420025b2004-10-10 22:44:35 +00001099
1100 //FIXME: As the algorithm stands it will NEVER add an instruction such as ba (with no
1101 //data dependencies) to the final order. We add this manually. It will always be
1102 //in the last set of S since its not part of a recurrence
1103 //Loop over all the sets and place them in the final node order
Tanya Lattner260652a2004-10-30 00:39:07 +00001104 std::vector<std::set<MSchedGraphNode*> > ::reverse_iterator LastSet = partialOrder.rbegin();
1105 for(std::set<MSchedGraphNode*>::iterator CurrentNode = LastSet->begin(), LastNode = LastSet->end();
Tanya Lattner420025b2004-10-10 22:44:35 +00001106 CurrentNode != LastNode; ++CurrentNode) {
1107 if((*CurrentNode)->getInst()->getOpcode() == V9::BA)
1108 FinalNodeOrder.push_back(*CurrentNode);
1109 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001110 //Return final Order
1111 //return FinalNodeOrder;
1112}
1113
1114void ModuloSchedulingPass::computeSchedule() {
1115
1116 bool success = false;
1117
Tanya Lattner260652a2004-10-30 00:39:07 +00001118 //FIXME: Should be set to max II of the original loop
1119 //Cap II in order to prevent infinite loop
1120 int capII = 30;
1121
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001122 while(!success) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001123
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001124 //Loop over the final node order and process each node
1125 for(std::vector<MSchedGraphNode*>::iterator I = FinalNodeOrder.begin(),
1126 E = FinalNodeOrder.end(); I != E; ++I) {
1127
1128 //CalculateEarly and Late start
1129 int EarlyStart = -1;
1130 int LateStart = 99999; //Set to something higher then we would ever expect (FIXME)
1131 bool hasSucc = false;
1132 bool hasPred = false;
Tanya Lattner4cffb582004-05-26 06:27:18 +00001133
1134 if(!(*I)->isBranch()) {
1135 //Loop over nodes in the schedule and determine if they are predecessors
1136 //or successors of the node we are trying to schedule
1137 for(MSSchedule::schedule_iterator nodesByCycle = schedule.begin(), nodesByCycleEnd = schedule.end();
1138 nodesByCycle != nodesByCycleEnd; ++nodesByCycle) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001139
Tanya Lattner4cffb582004-05-26 06:27:18 +00001140 //For this cycle, get the vector of nodes schedule and loop over it
1141 for(std::vector<MSchedGraphNode*>::iterator schedNode = nodesByCycle->second.begin(), SNE = nodesByCycle->second.end(); schedNode != SNE; ++schedNode) {
1142
1143 if((*I)->isPredecessor(*schedNode)) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001144 if(!ignoreEdge(*schedNode, *I)) {
1145 int diff = (*I)->getInEdge(*schedNode).getIteDiff();
Tanya Lattner4cffb582004-05-26 06:27:18 +00001146 int ES_Temp = nodesByCycle->first + (*schedNode)->getLatency() - diff * II;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001147 DEBUG(std::cerr << "Diff: " << diff << " Cycle: " << nodesByCycle->first << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001148 DEBUG(std::cerr << "Temp EarlyStart: " << ES_Temp << " Prev EarlyStart: " << EarlyStart << "\n");
1149 EarlyStart = std::max(EarlyStart, ES_Temp);
1150 hasPred = true;
1151 }
1152 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001153 if((*I)->isSuccessor(*schedNode)) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001154 if(!ignoreEdge(*I,*schedNode)) {
1155 int diff = (*schedNode)->getInEdge(*I).getIteDiff();
Tanya Lattner4cffb582004-05-26 06:27:18 +00001156 int LS_Temp = nodesByCycle->first - (*I)->getLatency() + diff * II;
1157 DEBUG(std::cerr << "Diff: " << diff << " Cycle: " << nodesByCycle->first << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001158 DEBUG(std::cerr << "Temp LateStart: " << LS_Temp << " Prev LateStart: " << LateStart << "\n");
1159 LateStart = std::min(LateStart, LS_Temp);
1160 hasSucc = true;
1161 }
1162 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001163 }
1164 }
1165 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001166 else {
1167 //WARNING: HACK! FIXME!!!!
Tanya Lattner420025b2004-10-10 22:44:35 +00001168 if((*I)->getInst()->getOpcode() == V9::BA) {
1169 EarlyStart = II-1;
1170 LateStart = II-1;
1171 }
1172 else {
1173 EarlyStart = II-1;
1174 LateStart = II-1;
1175 assert( (EarlyStart >= 0) && (LateStart >=0) && "EarlyStart and LateStart must be greater then 0");
1176 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001177 hasPred = 1;
1178 hasSucc = 1;
1179 }
1180
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001181
1182 DEBUG(std::cerr << "Has Successors: " << hasSucc << ", Has Pred: " << hasPred << "\n");
1183 DEBUG(std::cerr << "EarlyStart: " << EarlyStart << ", LateStart: " << LateStart << "\n");
1184
1185 //Check if the node has no pred or successors and set Early Start to its ASAP
1186 if(!hasSucc && !hasPred)
1187 EarlyStart = nodeToAttributesMap.find(*I)->second.ASAP;
1188
1189 //Now, try to schedule this node depending upon its pred and successor in the schedule
1190 //already
1191 if(!hasSucc && hasPred)
1192 success = scheduleNode(*I, EarlyStart, (EarlyStart + II -1));
1193 else if(!hasPred && hasSucc)
1194 success = scheduleNode(*I, LateStart, (LateStart - II +1));
1195 else if(hasPred && hasSucc)
1196 success = scheduleNode(*I, EarlyStart, std::min(LateStart, (EarlyStart + II -1)));
1197 else
1198 success = scheduleNode(*I, EarlyStart, EarlyStart + II - 1);
1199
1200 if(!success) {
Tanya Lattnere1df2122004-11-22 20:41:24 +00001201 ++IncreasedII;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001202 ++II;
1203 schedule.clear();
1204 break;
1205 }
1206
1207 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001208
Tanya Lattner260652a2004-10-30 00:39:07 +00001209 if(success) {
1210 DEBUG(std::cerr << "Constructing Schedule Kernel\n");
1211 success = schedule.constructKernel(II);
1212 DEBUG(std::cerr << "Done Constructing Schedule Kernel\n");
1213 if(!success) {
Tanya Lattnere1df2122004-11-22 20:41:24 +00001214 ++IncreasedII;
Tanya Lattner260652a2004-10-30 00:39:07 +00001215 ++II;
1216 schedule.clear();
1217 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001218 }
Tanya Lattner260652a2004-10-30 00:39:07 +00001219
1220 assert(II < capII && "The II should not exceed the original loop number of cycles");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001221 }
1222}
1223
1224
1225bool ModuloSchedulingPass::scheduleNode(MSchedGraphNode *node,
1226 int start, int end) {
1227 bool success = false;
1228
1229 DEBUG(std::cerr << *node << " (Start Cycle: " << start << ", End Cycle: " << end << ")\n");
1230
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001231 //Make sure start and end are not negative
Tanya Lattner260652a2004-10-30 00:39:07 +00001232 if(start < 0) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001233 start = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +00001234
1235 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001236 if(end < 0)
1237 end = 0;
1238
1239 bool forward = true;
1240 if(start > end)
1241 forward = false;
1242
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001243 bool increaseSC = true;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001244 int cycle = start ;
1245
1246
1247 while(increaseSC) {
1248
1249 increaseSC = false;
1250
Tanya Lattner4cffb582004-05-26 06:27:18 +00001251 increaseSC = schedule.insert(node, cycle);
1252
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001253 if(!increaseSC)
1254 return true;
1255
1256 //Increment cycle to try again
1257 if(forward) {
1258 ++cycle;
1259 DEBUG(std::cerr << "Increase cycle: " << cycle << "\n");
1260 if(cycle > end)
1261 return false;
1262 }
1263 else {
1264 --cycle;
1265 DEBUG(std::cerr << "Decrease cycle: " << cycle << "\n");
1266 if(cycle < end)
1267 return false;
1268 }
1269 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001270
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001271 return success;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001272}
Tanya Lattner4cffb582004-05-26 06:27:18 +00001273
Tanya Lattner420025b2004-10-10 22:44:35 +00001274void ModuloSchedulingPass::writePrologues(std::vector<MachineBasicBlock *> &prologues, MachineBasicBlock *origBB, std::vector<BasicBlock*> &llvm_prologues, std::map<const Value*, std::pair<const MSchedGraphNode*, int> > &valuesToSave, std::map<Value*, std::map<int, Value*> > &newValues, std::map<Value*, MachineBasicBlock*> &newValLocation) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00001275
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001276 //Keep a map to easily know whats in the kernel
Tanya Lattner4cffb582004-05-26 06:27:18 +00001277 std::map<int, std::set<const MachineInstr*> > inKernel;
1278 int maxStageCount = 0;
1279
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001280 MSchedGraphNode *branch = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +00001281 MSchedGraphNode *BAbranch = 0;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001282
Tanya Lattnere1df2122004-11-22 20:41:24 +00001283 schedule.print(std::cerr);
1284
Tanya Lattner4cffb582004-05-26 06:27:18 +00001285 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
1286 maxStageCount = std::max(maxStageCount, I->second);
1287
1288 //Ignore the branch, we will handle this separately
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001289 if(I->first->isBranch()) {
Tanya Lattnera6457502004-10-14 06:04:28 +00001290 if (I->first->getInst()->getOpcode() != V9::BA)
Tanya Lattner420025b2004-10-10 22:44:35 +00001291 branch = I->first;
Tanya Lattner260652a2004-10-30 00:39:07 +00001292 else
1293 BAbranch = I->first;
1294
Tanya Lattner4cffb582004-05-26 06:27:18 +00001295 continue;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001296 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001297
1298 //Put int the map so we know what instructions in each stage are in the kernel
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001299 DEBUG(std::cerr << "Inserting instruction " << *(I->first->getInst()) << " into map at stage " << I->second << "\n");
1300 inKernel[I->second].insert(I->first->getInst());
Tanya Lattner4cffb582004-05-26 06:27:18 +00001301 }
1302
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001303 //Get target information to look at machine operands
1304 const TargetInstrInfo *mii = target.getInstrInfo();
1305
1306 //Now write the prologues
1307 for(int i = 0; i < maxStageCount; ++i) {
1308 BasicBlock *llvmBB = new BasicBlock("PROLOGUE", (Function*) (origBB->getBasicBlock()->getParent()));
Tanya Lattner4cffb582004-05-26 06:27:18 +00001309 MachineBasicBlock *machineBB = new MachineBasicBlock(llvmBB);
1310
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001311 DEBUG(std::cerr << "i=" << i << "\n");
1312 for(int j = 0; j <= i; ++j) {
1313 for(MachineBasicBlock::const_iterator MI = origBB->begin(), ME = origBB->end(); ME != MI; ++MI) {
1314 if(inKernel[j].count(&*MI)) {
Tanya Lattner420025b2004-10-10 22:44:35 +00001315 MachineInstr *instClone = MI->clone();
1316 machineBB->push_back(instClone);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001317
Tanya Lattner420025b2004-10-10 22:44:35 +00001318 DEBUG(std::cerr << "Cloning: " << *MI << "\n");
1319
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001320 Instruction *tmp;
1321
1322 //After cloning, we may need to save the value that this instruction defines
1323 for(unsigned opNum=0; opNum < MI->getNumOperands(); ++opNum) {
1324 //get machine operand
Tanya Lattner420025b2004-10-10 22:44:35 +00001325 const MachineOperand &mOp = instClone->getOperand(opNum);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001326 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef()) {
1327
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001328 //Check if this is a value we should save
1329 if(valuesToSave.count(mOp.getVRegValue())) {
1330 //Save copy in tmpInstruction
1331 tmp = new TmpInstruction(mOp.getVRegValue());
1332
Tanya Lattner80f08552004-11-02 21:04:56 +00001333 //Add TmpInstruction to safe LLVM Instruction MCFI
1334 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001335 tempMvec.addTemp((Value*) tmp);
1336
Tanya Lattner420025b2004-10-10 22:44:35 +00001337 DEBUG(std::cerr << "Value: " << *(mOp.getVRegValue()) << " New Value: " << *tmp << " Stage: " << i << "\n");
1338
1339 newValues[mOp.getVRegValue()][i]= tmp;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001340 newValLocation[tmp] = machineBB;
1341
Tanya Lattner420025b2004-10-10 22:44:35 +00001342 DEBUG(std::cerr << "Machine Instr Operands: " << *(mOp.getVRegValue()) << ", 0, " << *tmp << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001343
1344 //Create machine instruction and put int machineBB
1345 MachineInstr *saveValue = BuildMI(machineBB, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
1346
1347 DEBUG(std::cerr << "Created new machine instr: " << *saveValue << "\n");
1348 }
1349 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001350
1351 //We may also need to update the value that we use if its from an earlier prologue
1352 if(j != 0) {
1353 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse()) {
1354 if(newValues.count(mOp.getVRegValue()))
1355 if(newValues[mOp.getVRegValue()].count(j-1)) {
1356 DEBUG(std::cerr << "Replaced this value: " << mOp.getVRegValue() << " With:" << (newValues[mOp.getVRegValue()][i-1]) << "\n");
1357 //Update the operand with the right value
1358 instClone->getOperand(opNum).setValueReg(newValues[mOp.getVRegValue()][i-1]);
1359 }
1360 }
1361 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001362 }
1363 }
Tanya Lattner20890832004-05-28 20:14:12 +00001364 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001365 }
1366
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001367
1368 //Stick in branch at the end
1369 machineBB->push_back(branch->getInst()->clone());
Tanya Lattner420025b2004-10-10 22:44:35 +00001370
Tanya Lattner260652a2004-10-30 00:39:07 +00001371 //Add nop
1372 BuildMI(machineBB, V9::NOP, 0);
1373
1374 //Stick in branch at the end
1375 machineBB->push_back(BAbranch->getInst()->clone());
1376
1377 //Add nop
1378 BuildMI(machineBB, V9::NOP, 0);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001379
1380 (((MachineBasicBlock*)origBB)->getParent())->getBasicBlockList().push_back(machineBB);
Tanya Lattner4cffb582004-05-26 06:27:18 +00001381 prologues.push_back(machineBB);
1382 llvm_prologues.push_back(llvmBB);
1383 }
1384}
1385
Tanya Lattner420025b2004-10-10 22:44:35 +00001386void ModuloSchedulingPass::writeEpilogues(std::vector<MachineBasicBlock *> &epilogues, const MachineBasicBlock *origBB, std::vector<BasicBlock*> &llvm_epilogues, std::map<const Value*, std::pair<const MSchedGraphNode*, int> > &valuesToSave, std::map<Value*, std::map<int, Value*> > &newValues,std::map<Value*, MachineBasicBlock*> &newValLocation, std::map<Value*, std::map<int, Value*> > &kernelPHIs ) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001387
Tanya Lattner20890832004-05-28 20:14:12 +00001388 std::map<int, std::set<const MachineInstr*> > inKernel;
Tanya Lattner420025b2004-10-10 22:44:35 +00001389
Tanya Lattner20890832004-05-28 20:14:12 +00001390 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
Tanya Lattner20890832004-05-28 20:14:12 +00001391
1392 //Ignore the branch, we will handle this separately
1393 if(I->first->isBranch())
1394 continue;
1395
1396 //Put int the map so we know what instructions in each stage are in the kernel
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001397 inKernel[I->second].insert(I->first->getInst());
Tanya Lattner20890832004-05-28 20:14:12 +00001398 }
1399
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001400 std::map<Value*, Value*> valPHIs;
1401
Tanya Lattner420025b2004-10-10 22:44:35 +00001402 //some debug stuff, will remove later
1403 DEBUG(for(std::map<Value*, std::map<int, Value*> >::iterator V = newValues.begin(), E = newValues.end(); V !=E; ++V) {
1404 std::cerr << "Old Value: " << *(V->first) << "\n";
1405 for(std::map<int, Value*>::iterator I = V->second.begin(), IE = V->second.end(); I != IE; ++I)
1406 std::cerr << "Stage: " << I->first << " Value: " << *(I->second) << "\n";
1407 });
1408
1409 //some debug stuff, will remove later
1410 DEBUG(for(std::map<Value*, std::map<int, Value*> >::iterator V = kernelPHIs.begin(), E = kernelPHIs.end(); V !=E; ++V) {
1411 std::cerr << "Old Value: " << *(V->first) << "\n";
1412 for(std::map<int, Value*>::iterator I = V->second.begin(), IE = V->second.end(); I != IE; ++I)
1413 std::cerr << "Stage: " << I->first << " Value: " << *(I->second) << "\n";
1414 });
1415
Tanya Lattner20890832004-05-28 20:14:12 +00001416 //Now write the epilogues
Tanya Lattner420025b2004-10-10 22:44:35 +00001417 for(int i = schedule.getMaxStage()-1; i >= 0; --i) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001418 BasicBlock *llvmBB = new BasicBlock("EPILOGUE", (Function*) (origBB->getBasicBlock()->getParent()));
Tanya Lattner20890832004-05-28 20:14:12 +00001419 MachineBasicBlock *machineBB = new MachineBasicBlock(llvmBB);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001420
Tanya Lattner420025b2004-10-10 22:44:35 +00001421 DEBUG(std::cerr << " Epilogue #: " << i << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001422
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001423
Tanya Lattnera6457502004-10-14 06:04:28 +00001424 std::map<Value*, int> inEpilogue;
Tanya Lattner420025b2004-10-10 22:44:35 +00001425
1426 for(MachineBasicBlock::const_iterator MI = origBB->begin(), ME = origBB->end(); ME != MI; ++MI) {
1427 for(int j=schedule.getMaxStage(); j > i; --j) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001428 if(inKernel[j].count(&*MI)) {
1429 DEBUG(std::cerr << "Cloning instruction " << *MI << "\n");
1430 MachineInstr *clone = MI->clone();
1431
1432 //Update operands that need to use the result from the phi
Tanya Lattner420025b2004-10-10 22:44:35 +00001433 for(unsigned opNum=0; opNum < clone->getNumOperands(); ++opNum) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001434 //get machine operand
Tanya Lattner420025b2004-10-10 22:44:35 +00001435 const MachineOperand &mOp = clone->getOperand(opNum);
Tanya Lattner420025b2004-10-10 22:44:35 +00001436
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001437 if((mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse())) {
Tanya Lattner420025b2004-10-10 22:44:35 +00001438
1439 DEBUG(std::cerr << "Writing PHI for " << *(mOp.getVRegValue()) << "\n");
Tanya Lattnera6457502004-10-14 06:04:28 +00001440
1441 //If this is the last instructions for the max iterations ago, don't update operands
1442 if(inEpilogue.count(mOp.getVRegValue()))
1443 if(inEpilogue[mOp.getVRegValue()] == i)
1444 continue;
Tanya Lattner420025b2004-10-10 22:44:35 +00001445
1446 //Quickly write appropriate phis for this operand
1447 if(newValues.count(mOp.getVRegValue())) {
1448 if(newValues[mOp.getVRegValue()].count(i)) {
1449 Instruction *tmp = new TmpInstruction(newValues[mOp.getVRegValue()][i]);
Tanya Lattnera6457502004-10-14 06:04:28 +00001450
1451 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00001452 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001453 tempMvec.addTemp((Value*) tmp);
1454
Tanya Lattner420025b2004-10-10 22:44:35 +00001455 MachineInstr *saveValue = BuildMI(machineBB, V9::PHI, 3).addReg(newValues[mOp.getVRegValue()][i]).addReg(kernelPHIs[mOp.getVRegValue()][i]).addRegDef(tmp);
1456 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
1457 valPHIs[mOp.getVRegValue()] = tmp;
1458 }
1459 }
1460
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001461 if(valPHIs.count(mOp.getVRegValue())) {
1462 //Update the operand in the cloned instruction
Tanya Lattner420025b2004-10-10 22:44:35 +00001463 clone->getOperand(opNum).setValueReg(valPHIs[mOp.getVRegValue()]);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001464 }
1465 }
Tanya Lattnera6457502004-10-14 06:04:28 +00001466 else if((mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef())) {
1467 inEpilogue[mOp.getVRegValue()] = i;
1468 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001469 }
1470 machineBB->push_back(clone);
1471 }
1472 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001473 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001474
Tanya Lattner20890832004-05-28 20:14:12 +00001475 (((MachineBasicBlock*)origBB)->getParent())->getBasicBlockList().push_back(machineBB);
1476 epilogues.push_back(machineBB);
1477 llvm_epilogues.push_back(llvmBB);
Tanya Lattner420025b2004-10-10 22:44:35 +00001478
1479 DEBUG(std::cerr << "EPILOGUE #" << i << "\n");
1480 DEBUG(machineBB->print(std::cerr));
Tanya Lattner20890832004-05-28 20:14:12 +00001481 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001482}
1483
Tanya Lattner420025b2004-10-10 22:44:35 +00001484void ModuloSchedulingPass::writeKernel(BasicBlock *llvmBB, MachineBasicBlock *machineBB, std::map<const Value*, std::pair<const MSchedGraphNode*, int> > &valuesToSave, std::map<Value*, std::map<int, Value*> > &newValues, std::map<Value*, MachineBasicBlock*> &newValLocation, std::map<Value*, std::map<int, Value*> > &kernelPHIs) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001485
1486 //Keep track of operands that are read and saved from a previous iteration. The new clone
1487 //instruction will use the result of the phi instead.
1488 std::map<Value*, Value*> finalPHIValue;
1489 std::map<Value*, Value*> kernelValue;
1490
1491 //Create TmpInstructions for the final phis
1492 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
1493
Tanya Lattner420025b2004-10-10 22:44:35 +00001494 DEBUG(std::cerr << "Stage: " << I->second << " Inst: " << *(I->first->getInst()) << "\n";);
1495
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001496 //Clone instruction
1497 const MachineInstr *inst = I->first->getInst();
1498 MachineInstr *instClone = inst->clone();
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001499
Tanya Lattner420025b2004-10-10 22:44:35 +00001500 //Insert into machine basic block
1501 machineBB->push_back(instClone);
1502
Tanya Lattnerced82222004-11-16 21:31:37 +00001503 DEBUG(std::cerr << "Cloned Inst: " << *instClone << "\n");
1504
Tanya Lattnera6457502004-10-14 06:04:28 +00001505 if(I->first->isBranch()) {
1506 //Add kernel noop
1507 BuildMI(machineBB, V9::NOP, 0);
1508 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001509
1510 //Loop over Machine Operands
1511 for(unsigned i=0; i < inst->getNumOperands(); ++i) {
1512 //get machine operand
1513 const MachineOperand &mOp = inst->getOperand(i);
1514
1515 if(I->second != 0) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001516 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse()) {
Tanya Lattner420025b2004-10-10 22:44:35 +00001517
1518 //Check to see where this operand is defined if this instruction is from max stage
1519 if(I->second == schedule.getMaxStage()) {
1520 DEBUG(std::cerr << "VREG: " << *(mOp.getVRegValue()) << "\n");
1521 }
1522
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001523 //If its in the value saved, we need to create a temp instruction and use that instead
1524 if(valuesToSave.count(mOp.getVRegValue())) {
Tanya Lattnerced82222004-11-16 21:31:37 +00001525
1526 //Check if we already have a final PHI value for this
1527 if(!finalPHIValue.count(mOp.getVRegValue())) {
1528 TmpInstruction *tmp = new TmpInstruction(mOp.getVRegValue());
1529
1530 //Get machine code for this instruction
1531 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
1532 tempMvec.addTemp((Value*) tmp);
1533
1534 //Update the operand in the cloned instruction
1535 instClone->getOperand(i).setValueReg(tmp);
1536
1537 //save this as our final phi
1538 finalPHIValue[mOp.getVRegValue()] = tmp;
1539 newValLocation[tmp] = machineBB;
1540 }
1541 else {
1542 //Use the previous final phi value
1543 instClone->getOperand(i).setValueReg(finalPHIValue[mOp.getVRegValue()]);
1544 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001545 }
1546 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001547 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001548 if(I->second != schedule.getMaxStage()) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001549 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef()) {
1550 if(valuesToSave.count(mOp.getVRegValue())) {
1551
1552 TmpInstruction *tmp = new TmpInstruction(mOp.getVRegValue());
1553
Tanya Lattnera6457502004-10-14 06:04:28 +00001554 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00001555 MachineCodeForInstruction & tempVec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001556 tempVec.addTemp((Value*) tmp);
1557
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001558 //Create new machine instr and put in MBB
1559 MachineInstr *saveValue = BuildMI(machineBB, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
1560
1561 //Save for future cleanup
1562 kernelValue[mOp.getVRegValue()] = tmp;
1563 newValLocation[tmp] = machineBB;
Tanya Lattner420025b2004-10-10 22:44:35 +00001564 kernelPHIs[mOp.getVRegValue()][schedule.getMaxStage()-1] = tmp;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001565 }
1566 }
1567 }
1568 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001569
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001570 }
1571
Tanya Lattner420025b2004-10-10 22:44:35 +00001572 DEBUG(std::cerr << "KERNEL before PHIs\n");
1573 DEBUG(machineBB->print(std::cerr));
1574
1575
1576 //Loop over each value we need to generate phis for
1577 for(std::map<Value*, std::map<int, Value*> >::iterator V = newValues.begin(),
1578 E = newValues.end(); V != E; ++V) {
1579
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001580
1581 DEBUG(std::cerr << "Writing phi for" << *(V->first));
Tanya Lattner420025b2004-10-10 22:44:35 +00001582 DEBUG(std::cerr << "\nMap of Value* for this phi\n");
1583 DEBUG(for(std::map<int, Value*>::iterator I = V->second.begin(),
1584 IE = V->second.end(); I != IE; ++I) {
1585 std::cerr << "Stage: " << I->first;
1586 std::cerr << " Value: " << *(I->second) << "\n";
1587 });
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001588
Tanya Lattner420025b2004-10-10 22:44:35 +00001589 //If we only have one current iteration live, its safe to set lastPhi = to kernel value
1590 if(V->second.size() == 1) {
1591 assert(kernelValue[V->first] != 0 && "Kernel value* must exist to create phi");
1592 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(),V9::PHI, 3).addReg(V->second.begin()->second).addReg(kernelValue[V->first]).addRegDef(finalPHIValue[V->first]);
1593 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
1594 kernelPHIs[V->first][schedule.getMaxStage()-1] = kernelValue[V->first];
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001595 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001596 else {
1597
1598 //Keep track of last phi created.
1599 Instruction *lastPhi = 0;
1600
1601 unsigned count = 1;
1602 //Loop over the the map backwards to generate phis
1603 for(std::map<int, Value*>::reverse_iterator I = V->second.rbegin(), IE = V->second.rend();
1604 I != IE; ++I) {
1605
1606 if(count < (V->second).size()) {
1607 if(lastPhi == 0) {
1608 lastPhi = new TmpInstruction(I->second);
Tanya Lattnera6457502004-10-14 06:04:28 +00001609
1610 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00001611 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001612 tempMvec.addTemp((Value*) lastPhi);
1613
Tanya Lattner420025b2004-10-10 22:44:35 +00001614 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(), V9::PHI, 3).addReg(kernelValue[V->first]).addReg(I->second).addRegDef(lastPhi);
1615 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
1616 newValLocation[lastPhi] = machineBB;
1617 }
1618 else {
1619 Instruction *tmp = new TmpInstruction(I->second);
Tanya Lattnera6457502004-10-14 06:04:28 +00001620
1621 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00001622 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001623 tempMvec.addTemp((Value*) tmp);
1624
1625
Tanya Lattner420025b2004-10-10 22:44:35 +00001626 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(), V9::PHI, 3).addReg(lastPhi).addReg(I->second).addRegDef(tmp);
1627 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
1628 lastPhi = tmp;
1629 kernelPHIs[V->first][I->first] = lastPhi;
1630 newValLocation[lastPhi] = machineBB;
1631 }
1632 }
1633 //Final phi value
1634 else {
1635 //The resulting value must be the Value* we created earlier
1636 assert(lastPhi != 0 && "Last phi is NULL!\n");
1637 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(), V9::PHI, 3).addReg(lastPhi).addReg(I->second).addRegDef(finalPHIValue[V->first]);
1638 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
1639 kernelPHIs[V->first][I->first] = finalPHIValue[V->first];
1640 }
1641
1642 ++count;
1643 }
1644
1645 }
1646 }
1647
1648 DEBUG(std::cerr << "KERNEL after PHIs\n");
1649 DEBUG(machineBB->print(std::cerr));
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001650}
1651
Tanya Lattner420025b2004-10-10 22:44:35 +00001652
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001653void ModuloSchedulingPass::removePHIs(const MachineBasicBlock *origBB, std::vector<MachineBasicBlock *> &prologues, std::vector<MachineBasicBlock *> &epilogues, MachineBasicBlock *kernelBB, std::map<Value*, MachineBasicBlock*> &newValLocation) {
1654
1655 //Worklist to delete things
1656 std::vector<std::pair<MachineBasicBlock*, MachineBasicBlock::iterator> > worklist;
Tanya Lattnera6457502004-10-14 06:04:28 +00001657
1658 //Worklist of TmpInstructions that need to be added to a MCFI
1659 std::vector<Instruction*> addToMCFI;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001660
Tanya Lattnera6457502004-10-14 06:04:28 +00001661 //Worklist to add OR instructions to end of kernel so not to invalidate the iterator
1662 //std::vector<std::pair<Instruction*, Value*> > newORs;
1663
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001664 const TargetInstrInfo *TMI = target.getInstrInfo();
1665
1666 //Start with the kernel and for each phi insert a copy for the phi def and for each arg
1667 for(MachineBasicBlock::iterator I = kernelBB->begin(), E = kernelBB->end(); I != E; ++I) {
Tanya Lattnera6457502004-10-14 06:04:28 +00001668
Tanya Lattner80f08552004-11-02 21:04:56 +00001669 DEBUG(std::cerr << "Looking at Instr: " << *I << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001670 //Get op code and check if its a phi
Tanya Lattnera6457502004-10-14 06:04:28 +00001671 if(I->getOpcode() == V9::PHI) {
1672
1673 DEBUG(std::cerr << "Replacing PHI: " << *I << "\n");
1674 Instruction *tmp = 0;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001675
Tanya Lattnera6457502004-10-14 06:04:28 +00001676 for(unsigned i = 0; i < I->getNumOperands(); ++i) {
1677 //Get Operand
1678 const MachineOperand &mOp = I->getOperand(i);
1679 assert(mOp.getType() == MachineOperand::MO_VirtualRegister && "Should be a Value*\n");
1680
1681 if(!tmp) {
1682 tmp = new TmpInstruction(mOp.getVRegValue());
1683 addToMCFI.push_back(tmp);
1684 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001685
Tanya Lattnera6457502004-10-14 06:04:28 +00001686 //Now for all our arguments we read, OR to the new TmpInstruction that we created
1687 if(mOp.isUse()) {
1688 DEBUG(std::cerr << "Use: " << mOp << "\n");
1689 //Place a copy at the end of its BB but before the branches
1690 assert(newValLocation.count(mOp.getVRegValue()) && "We must know where this value is located\n");
1691 //Reverse iterate to find the branches, we can safely assume no instructions have been
1692 //put in the nop positions
1693 for(MachineBasicBlock::iterator inst = --(newValLocation[mOp.getVRegValue()])->end(), endBB = (newValLocation[mOp.getVRegValue()])->begin(); inst != endBB; --inst) {
1694 MachineOpCode opc = inst->getOpcode();
1695 if(TMI->isBranch(opc) || TMI->isNop(opc))
1696 continue;
1697 else {
1698 BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
1699 break;
1700 }
1701
1702 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001703
Tanya Lattnera6457502004-10-14 06:04:28 +00001704 }
1705 else {
1706 //Remove the phi and replace it with an OR
1707 DEBUG(std::cerr << "Def: " << mOp << "\n");
1708 //newORs.push_back(std::make_pair(tmp, mOp.getVRegValue()));
1709 BuildMI(*kernelBB, I, V9::ORr, 3).addReg(tmp).addImm(0).addRegDef(mOp.getVRegValue());
1710 worklist.push_back(std::make_pair(kernelBB, I));
1711 }
1712
1713 }
1714
1715 }
1716
Tanya Lattnera6457502004-10-14 06:04:28 +00001717
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001718 }
1719
Tanya Lattner80f08552004-11-02 21:04:56 +00001720 //Add TmpInstructions to some MCFI
1721 if(addToMCFI.size() > 0) {
1722 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
1723 for(unsigned x = 0; x < addToMCFI.size(); ++x) {
1724 tempMvec.addTemp(addToMCFI[x]);
1725 }
1726 addToMCFI.clear();
1727 }
1728
Tanya Lattnera6457502004-10-14 06:04:28 +00001729
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001730 //Remove phis from epilogue
1731 for(std::vector<MachineBasicBlock*>::iterator MB = epilogues.begin(), ME = epilogues.end(); MB != ME; ++MB) {
1732 for(MachineBasicBlock::iterator I = (*MB)->begin(), E = (*MB)->end(); I != E; ++I) {
Tanya Lattner80f08552004-11-02 21:04:56 +00001733
1734 DEBUG(std::cerr << "Looking at Instr: " << *I << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001735 //Get op code and check if its a phi
Brian Gaeke418379e2004-08-18 20:04:24 +00001736 if(I->getOpcode() == V9::PHI) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001737 Instruction *tmp = 0;
Tanya Lattnera6457502004-10-14 06:04:28 +00001738
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001739 for(unsigned i = 0; i < I->getNumOperands(); ++i) {
1740 //Get Operand
1741 const MachineOperand &mOp = I->getOperand(i);
1742 assert(mOp.getType() == MachineOperand::MO_VirtualRegister && "Should be a Value*\n");
1743
1744 if(!tmp) {
1745 tmp = new TmpInstruction(mOp.getVRegValue());
Tanya Lattnera6457502004-10-14 06:04:28 +00001746 addToMCFI.push_back(tmp);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001747 }
1748
1749 //Now for all our arguments we read, OR to the new TmpInstruction that we created
1750 if(mOp.isUse()) {
1751 DEBUG(std::cerr << "Use: " << mOp << "\n");
1752 //Place a copy at the end of its BB but before the branches
1753 assert(newValLocation.count(mOp.getVRegValue()) && "We must know where this value is located\n");
1754 //Reverse iterate to find the branches, we can safely assume no instructions have been
1755 //put in the nop positions
1756 for(MachineBasicBlock::iterator inst = --(newValLocation[mOp.getVRegValue()])->end(), endBB = (newValLocation[mOp.getVRegValue()])->begin(); inst != endBB; --inst) {
1757 MachineOpCode opc = inst->getOpcode();
1758 if(TMI->isBranch(opc) || TMI->isNop(opc))
1759 continue;
1760 else {
1761 BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
1762 break;
1763 }
1764
1765 }
Tanya Lattnera6457502004-10-14 06:04:28 +00001766
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001767 }
1768 else {
1769 //Remove the phi and replace it with an OR
1770 DEBUG(std::cerr << "Def: " << mOp << "\n");
1771 BuildMI(**MB, I, V9::ORr, 3).addReg(tmp).addImm(0).addRegDef(mOp.getVRegValue());
1772 worklist.push_back(std::make_pair(*MB,I));
1773 }
1774
1775 }
1776 }
Tanya Lattnera6457502004-10-14 06:04:28 +00001777
Tanya Lattner80f08552004-11-02 21:04:56 +00001778
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001779 }
1780 }
1781
Tanya Lattner80f08552004-11-02 21:04:56 +00001782
1783 if(addToMCFI.size() > 0) {
1784 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
1785 for(unsigned x = 0; x < addToMCFI.size(); ++x) {
1786 tempMvec.addTemp(addToMCFI[x]);
1787 }
1788 addToMCFI.clear();
1789 }
1790
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001791 //Delete the phis
1792 for(std::vector<std::pair<MachineBasicBlock*, MachineBasicBlock::iterator> >::iterator I = worklist.begin(), E = worklist.end(); I != E; ++I) {
Tanya Lattnera6457502004-10-14 06:04:28 +00001793
1794 DEBUG(std::cerr << "Deleting PHI " << *I->second << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001795 I->first->erase(I->second);
1796
1797 }
1798
Tanya Lattnera6457502004-10-14 06:04:28 +00001799
1800 assert((addToMCFI.size() == 0) && "We should have added all TmpInstructions to some MachineCodeForInstruction");
Tanya Lattner20890832004-05-28 20:14:12 +00001801}
1802
1803
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001804void ModuloSchedulingPass::reconstructLoop(MachineBasicBlock *BB) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00001805
Tanya Lattner420025b2004-10-10 22:44:35 +00001806 DEBUG(std::cerr << "Reconstructing Loop\n");
1807
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001808 //First find the value *'s that we need to "save"
1809 std::map<const Value*, std::pair<const MSchedGraphNode*, int> > valuesToSave;
Tanya Lattner4cffb582004-05-26 06:27:18 +00001810
Tanya Lattner420025b2004-10-10 22:44:35 +00001811 //Keep track of instructions we have already seen and their stage because
1812 //we don't want to "save" values if they are used in the kernel immediately
1813 std::map<const MachineInstr*, int> lastInstrs;
1814
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001815 //Loop over kernel and only look at instructions from a stage > 0
1816 //Look at its operands and save values *'s that are read
Tanya Lattner4cffb582004-05-26 06:27:18 +00001817 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00001818
Tanya Lattner420025b2004-10-10 22:44:35 +00001819 if(I->second !=0) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00001820 //For this instruction, get the Value*'s that it reads and put them into the set.
1821 //Assert if there is an operand of another type that we need to save
1822 const MachineInstr *inst = I->first->getInst();
Tanya Lattner420025b2004-10-10 22:44:35 +00001823 lastInstrs[inst] = I->second;
1824
Tanya Lattner4cffb582004-05-26 06:27:18 +00001825 for(unsigned i=0; i < inst->getNumOperands(); ++i) {
1826 //get machine operand
1827 const MachineOperand &mOp = inst->getOperand(i);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001828
Tanya Lattner4cffb582004-05-26 06:27:18 +00001829 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse()) {
1830 //find the value in the map
Tanya Lattner420025b2004-10-10 22:44:35 +00001831 if (const Value* srcI = mOp.getVRegValue()) {
1832
Tanya Lattnerced82222004-11-16 21:31:37 +00001833 if(isa<Constant>(srcI) || isa<Argument>(srcI) || isa<PHINode>(srcI))
Tanya Lattner80f08552004-11-02 21:04:56 +00001834 continue;
1835
Tanya Lattner420025b2004-10-10 22:44:35 +00001836 //Before we declare this Value* one that we should save
1837 //make sure its def is not of the same stage as this instruction
1838 //because it will be consumed before its used
1839 Instruction *defInst = (Instruction*) srcI;
1840
1841 //Should we save this value?
1842 bool save = true;
1843
Tanya Lattnerced82222004-11-16 21:31:37 +00001844 //Continue if not in the def map, loop invariant code does not need to be saved
1845 if(!defMap.count(srcI))
1846 continue;
1847
Tanya Lattner80f08552004-11-02 21:04:56 +00001848 MachineInstr *defInstr = defMap[srcI];
1849
Tanya Lattnerced82222004-11-16 21:31:37 +00001850
Tanya Lattner80f08552004-11-02 21:04:56 +00001851 if(lastInstrs.count(defInstr)) {
Tanya Lattnerced82222004-11-16 21:31:37 +00001852 if(lastInstrs[defInstr] == I->second) {
Tanya Lattner80f08552004-11-02 21:04:56 +00001853 save = false;
Tanya Lattnerced82222004-11-16 21:31:37 +00001854
1855 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001856 }
Tanya Lattner80f08552004-11-02 21:04:56 +00001857
Tanya Lattner420025b2004-10-10 22:44:35 +00001858 if(save)
1859 valuesToSave[srcI] = std::make_pair(I->first, i);
1860 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001861 }
1862
1863 if(mOp.getType() != MachineOperand::MO_VirtualRegister && mOp.isUse()) {
1864 assert("Our assumption is wrong. We have another type of register that needs to be saved\n");
1865 }
1866 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001867 }
1868 }
1869
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001870 //The new loop will consist of one or more prologues, the kernel, and one or more epilogues.
1871
1872 //Map to keep track of old to new values
Tanya Lattner420025b2004-10-10 22:44:35 +00001873 std::map<Value*, std::map<int, Value*> > newValues;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001874
Tanya Lattner420025b2004-10-10 22:44:35 +00001875 //Map to keep track of old to new values in kernel
1876 std::map<Value*, std::map<int, Value*> > kernelPHIs;
1877
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001878 //Another map to keep track of what machine basic blocks these new value*s are in since
1879 //they have no llvm instruction equivalent
1880 std::map<Value*, MachineBasicBlock*> newValLocation;
1881
1882 std::vector<MachineBasicBlock*> prologues;
1883 std::vector<BasicBlock*> llvm_prologues;
1884
1885
1886 //Write prologue
1887 writePrologues(prologues, BB, llvm_prologues, valuesToSave, newValues, newValLocation);
Tanya Lattner420025b2004-10-10 22:44:35 +00001888
1889 //Print out epilogues and prologue
1890 DEBUG(for(std::vector<MachineBasicBlock*>::iterator I = prologues.begin(), E = prologues.end();
1891 I != E; ++I) {
1892 std::cerr << "PROLOGUE\n";
1893 (*I)->print(std::cerr);
1894 });
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001895
1896 BasicBlock *llvmKernelBB = new BasicBlock("Kernel", (Function*) (BB->getBasicBlock()->getParent()));
1897 MachineBasicBlock *machineKernelBB = new MachineBasicBlock(llvmKernelBB);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001898 (((MachineBasicBlock*)BB)->getParent())->getBasicBlockList().push_back(machineKernelBB);
Tanya Lattner420025b2004-10-10 22:44:35 +00001899 writeKernel(llvmKernelBB, machineKernelBB, valuesToSave, newValues, newValLocation, kernelPHIs);
1900
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001901
1902 std::vector<MachineBasicBlock*> epilogues;
1903 std::vector<BasicBlock*> llvm_epilogues;
1904
1905 //Write epilogues
Tanya Lattner420025b2004-10-10 22:44:35 +00001906 writeEpilogues(epilogues, BB, llvm_epilogues, valuesToSave, newValues, newValLocation, kernelPHIs);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001907
1908
1909 const TargetInstrInfo *TMI = target.getInstrInfo();
1910
1911 //Fix up machineBB and llvmBB branches
1912 for(unsigned I = 0; I < prologues.size(); ++I) {
1913
1914 MachineInstr *branch = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +00001915 MachineInstr *branch2 = 0;
1916
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001917 //Find terminator since getFirstTerminator does not work!
1918 for(MachineBasicBlock::reverse_iterator mInst = prologues[I]->rbegin(), mInstEnd = prologues[I]->rend(); mInst != mInstEnd; ++mInst) {
1919 MachineOpCode OC = mInst->getOpcode();
1920 if(TMI->isBranch(OC)) {
Tanya Lattner260652a2004-10-30 00:39:07 +00001921 if(mInst->getOpcode() == V9::BA)
1922 branch2 = &*mInst;
1923 else
1924 branch = &*mInst;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001925 DEBUG(std::cerr << *mInst << "\n");
Tanya Lattner260652a2004-10-30 00:39:07 +00001926 if(branch !=0 && branch2 !=0)
1927 break;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001928 }
1929 }
1930
Tanya Lattner260652a2004-10-30 00:39:07 +00001931 //Update branch1
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001932 for(unsigned opNum = 0; opNum < branch->getNumOperands(); ++opNum) {
1933 MachineOperand &mOp = branch->getOperand(opNum);
1934 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
Tanya Lattner260652a2004-10-30 00:39:07 +00001935 //Check if we are branching to the kernel, if not branch to epilogue
1936 if(mOp.getVRegValue() == BB->getBasicBlock()) {
1937 if(I == prologues.size()-1)
1938 mOp.setValueReg(llvmKernelBB);
1939 else
1940 mOp.setValueReg(llvm_prologues[I+1]);
1941 }
1942 else
1943 mOp.setValueReg(llvm_epilogues[(llvm_epilogues.size()-1-I)]);
1944 }
1945 }
1946
1947 //Update branch1
1948 for(unsigned opNum = 0; opNum < branch2->getNumOperands(); ++opNum) {
1949 MachineOperand &mOp = branch2->getOperand(opNum);
1950 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
1951 //Check if we are branching to the kernel, if not branch to epilogue
1952 if(mOp.getVRegValue() == BB->getBasicBlock()) {
1953 if(I == prologues.size()-1)
1954 mOp.setValueReg(llvmKernelBB);
1955 else
1956 mOp.setValueReg(llvm_prologues[I+1]);
1957 }
1958 else
1959 mOp.setValueReg(llvm_epilogues[(llvm_epilogues.size()-1-I)]);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001960 }
1961 }
1962
1963 //Update llvm basic block with our new branch instr
1964 DEBUG(std::cerr << BB->getBasicBlock()->getTerminator() << "\n");
1965 const BranchInst *branchVal = dyn_cast<BranchInst>(BB->getBasicBlock()->getTerminator());
Tanya Lattnera6457502004-10-14 06:04:28 +00001966 //TmpInstruction *tmp = new TmpInstruction(branchVal->getCondition());
1967
1968 //Add TmpInstruction to original branches MCFI
1969 //MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(branchVal);
1970 //tempMvec.addTemp((Value*) tmp);
1971
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001972 if(I == prologues.size()-1) {
1973 TerminatorInst *newBranch = new BranchInst(llvmKernelBB,
1974 llvm_epilogues[(llvm_epilogues.size()-1-I)],
Tanya Lattnera6457502004-10-14 06:04:28 +00001975 branchVal->getCondition(),
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001976 llvm_prologues[I]);
1977 }
1978 else
1979 TerminatorInst *newBranch = new BranchInst(llvm_prologues[I+1],
1980 llvm_epilogues[(llvm_epilogues.size()-1-I)],
Tanya Lattnera6457502004-10-14 06:04:28 +00001981 branchVal->getCondition(),
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001982 llvm_prologues[I]);
1983
1984 assert(branch != 0 && "There must be a terminator for this machine basic block!\n");
1985
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001986 }
1987
1988 //Fix up kernel machine branches
1989 MachineInstr *branch = 0;
Tanya Lattnera6457502004-10-14 06:04:28 +00001990 MachineInstr *BAbranch = 0;
1991
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001992 for(MachineBasicBlock::reverse_iterator mInst = machineKernelBB->rbegin(), mInstEnd = machineKernelBB->rend(); mInst != mInstEnd; ++mInst) {
1993 MachineOpCode OC = mInst->getOpcode();
1994 if(TMI->isBranch(OC)) {
Tanya Lattnera6457502004-10-14 06:04:28 +00001995 if(mInst->getOpcode() == V9::BA) {
1996 BAbranch = &*mInst;
1997 }
1998 else {
1999 branch = &*mInst;
2000 break;
2001 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002002 }
2003 }
2004
2005 assert(branch != 0 && "There must be a terminator for the kernel machine basic block!\n");
2006
2007 //Update kernel self loop branch
2008 for(unsigned opNum = 0; opNum < branch->getNumOperands(); ++opNum) {
2009 MachineOperand &mOp = branch->getOperand(opNum);
2010
2011 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2012 mOp.setValueReg(llvmKernelBB);
2013 }
2014 }
2015
Tanya Lattnera6457502004-10-14 06:04:28 +00002016 Value *origBAVal = 0;
2017
2018 //Update kernel BA branch
2019 for(unsigned opNum = 0; opNum < BAbranch->getNumOperands(); ++opNum) {
2020 MachineOperand &mOp = BAbranch->getOperand(opNum);
2021 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2022 origBAVal = mOp.getVRegValue();
2023 if(llvm_epilogues.size() > 0)
2024 mOp.setValueReg(llvm_epilogues[0]);
2025
2026 }
2027 }
2028
2029 assert((origBAVal != 0) && "Could not find original branch always value");
2030
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002031 //Update kernelLLVM branches
2032 const BranchInst *branchVal = dyn_cast<BranchInst>(BB->getBasicBlock()->getTerminator());
Tanya Lattnera6457502004-10-14 06:04:28 +00002033 //TmpInstruction *tmp = new TmpInstruction(branchVal->getCondition());
2034
2035 //Add TmpInstruction to original branches MCFI
2036 //MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(branchVal);
2037 //tempMvec.addTemp((Value*) tmp);
2038
Tanya Lattner260652a2004-10-30 00:39:07 +00002039 assert(llvm_epilogues.size() != 0 && "We must have epilogues!");
2040
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002041 TerminatorInst *newBranch = new BranchInst(llvmKernelBB,
2042 llvm_epilogues[0],
Tanya Lattnera6457502004-10-14 06:04:28 +00002043 branchVal->getCondition(),
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002044 llvmKernelBB);
2045
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002046
2047 //Lastly add unconditional branches for the epilogues
2048 for(unsigned I = 0; I < epilogues.size(); ++I) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00002049
Tanya Lattnera6457502004-10-14 06:04:28 +00002050 //Now since we don't have fall throughs, add a unconditional branch to the next prologue
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002051 if(I != epilogues.size()-1) {
Tanya Lattner420025b2004-10-10 22:44:35 +00002052 BuildMI(epilogues[I], V9::BA, 1).addPCDisp(llvm_epilogues[I+1]);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002053 //Add unconditional branch to end of epilogue
2054 TerminatorInst *newBranch = new BranchInst(llvm_epilogues[I+1],
2055 llvm_epilogues[I]);
2056
Tanya Lattner4cffb582004-05-26 06:27:18 +00002057 }
Tanya Lattnera6457502004-10-14 06:04:28 +00002058 else {
2059 BuildMI(epilogues[I], V9::BA, 1).addPCDisp(origBAVal);
2060
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002061
Tanya Lattnera6457502004-10-14 06:04:28 +00002062 //Update last epilogue exit branch
2063 BranchInst *branchVal = (BranchInst*) dyn_cast<BranchInst>(BB->getBasicBlock()->getTerminator());
2064 //Find where we are supposed to branch to
2065 BasicBlock *nextBlock = 0;
2066 for(unsigned j=0; j <branchVal->getNumSuccessors(); ++j) {
2067 if(branchVal->getSuccessor(j) != BB->getBasicBlock())
2068 nextBlock = branchVal->getSuccessor(j);
2069 }
2070
2071 assert((nextBlock != 0) && "Next block should not be null!");
2072 TerminatorInst *newBranch = new BranchInst(nextBlock, llvm_epilogues[I]);
2073 }
2074 //Add one more nop!
2075 BuildMI(epilogues[I], V9::NOP, 0);
2076
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002077 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00002078
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002079 //FIX UP Machine BB entry!!
2080 //We are looking at the predecesor of our loop basic block and we want to change its ba instruction
2081
Tanya Lattner4cffb582004-05-26 06:27:18 +00002082
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002083 //Find all llvm basic blocks that branch to the loop entry and change to our first prologue.
2084 const BasicBlock *llvmBB = BB->getBasicBlock();
2085
Tanya Lattner260652a2004-10-30 00:39:07 +00002086 std::vector<const BasicBlock*>Preds (pred_begin(llvmBB), pred_end(llvmBB));
2087
2088 //for(pred_const_iterator P = pred_begin(llvmBB), PE = pred_end(llvmBB); P != PE; ++PE) {
2089 for(std::vector<const BasicBlock*>::iterator P = Preds.begin(), PE = Preds.end(); P != PE; ++P) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002090 if(*P == llvmBB)
2091 continue;
2092 else {
2093 DEBUG(std::cerr << "Found our entry BB\n");
2094 //Get the Terminator instruction for this basic block and print it out
2095 DEBUG(std::cerr << *((*P)->getTerminator()) << "\n");
2096 //Update the terminator
2097 TerminatorInst *term = ((BasicBlock*)*P)->getTerminator();
2098 for(unsigned i=0; i < term->getNumSuccessors(); ++i) {
2099 if(term->getSuccessor(i) == llvmBB) {
2100 DEBUG(std::cerr << "Replacing successor bb\n");
2101 if(llvm_prologues.size() > 0) {
2102 term->setSuccessor(i, llvm_prologues[0]);
2103 //Also update its corresponding machine instruction
2104 MachineCodeForInstruction & tempMvec =
2105 MachineCodeForInstruction::get(term);
2106 for (unsigned j = 0; j < tempMvec.size(); j++) {
2107 MachineInstr *temp = tempMvec[j];
2108 MachineOpCode opc = temp->getOpcode();
2109 if(TMI->isBranch(opc)) {
2110 DEBUG(std::cerr << *temp << "\n");
2111 //Update branch
2112 for(unsigned opNum = 0; opNum < temp->getNumOperands(); ++opNum) {
2113 MachineOperand &mOp = temp->getOperand(opNum);
2114 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2115 mOp.setValueReg(llvm_prologues[0]);
2116 }
2117 }
2118 }
2119 }
2120 }
2121 else {
2122 term->setSuccessor(i, llvmKernelBB);
2123 //Also update its corresponding machine instruction
2124 MachineCodeForInstruction & tempMvec =
2125 MachineCodeForInstruction::get(term);
2126 for (unsigned j = 0; j < tempMvec.size(); j++) {
2127 MachineInstr *temp = tempMvec[j];
2128 MachineOpCode opc = temp->getOpcode();
2129 if(TMI->isBranch(opc)) {
2130 DEBUG(std::cerr << *temp << "\n");
2131 //Update branch
2132 for(unsigned opNum = 0; opNum < temp->getNumOperands(); ++opNum) {
2133 MachineOperand &mOp = temp->getOperand(opNum);
2134 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2135 mOp.setValueReg(llvmKernelBB);
2136 }
2137 }
2138 }
2139 }
2140 }
2141 }
2142 }
2143 break;
2144 }
2145 }
2146
2147 removePHIs(BB, prologues, epilogues, machineKernelBB, newValLocation);
Tanya Lattner4cffb582004-05-26 06:27:18 +00002148
2149
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002150
2151 //Print out epilogues and prologue
2152 DEBUG(for(std::vector<MachineBasicBlock*>::iterator I = prologues.begin(), E = prologues.end();
2153 I != E; ++I) {
2154 std::cerr << "PROLOGUE\n";
2155 (*I)->print(std::cerr);
2156 });
2157
2158 DEBUG(std::cerr << "KERNEL\n");
2159 DEBUG(machineKernelBB->print(std::cerr));
2160
2161 DEBUG(for(std::vector<MachineBasicBlock*>::iterator I = epilogues.begin(), E = epilogues.end();
2162 I != E; ++I) {
2163 std::cerr << "EPILOGUE\n";
2164 (*I)->print(std::cerr);
2165 });
2166
2167
2168 DEBUG(std::cerr << "New Machine Function" << "\n");
2169 DEBUG(std::cerr << BB->getParent() << "\n");
2170
Tanya Lattner420025b2004-10-10 22:44:35 +00002171 //BB->getParent()->getBasicBlockList().erase(BB);
Tanya Lattner4cffb582004-05-26 06:27:18 +00002172
2173}
2174