blob: e39a9fbb28b80a825fb975dedb29c670e985fc58 [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() {
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000751
752 //Only push BA branches onto the final node order, we put other branches after it
753 //FIXME: Should we really be pushing branches on it a specific order instead of relying
754 //on BA being there?
755 std::vector<MSchedGraphNode*> otherBranch;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000756
757 //Loop over all recurrences and add to our partial order
758 //be sure to remove nodes that are already in the partial order in
759 //a different recurrence and don't add empty recurrences.
760 for(std::set<std::pair<int, std::vector<MSchedGraphNode*> > >::reverse_iterator I = recurrenceList.rbegin(), E=recurrenceList.rend(); I !=E; ++I) {
761
762 //Add nodes that connect this recurrence to the previous recurrence
763
764 //If this is the first recurrence in the partial order, add all predecessors
765 for(std::vector<MSchedGraphNode*>::const_iterator N = I->second.begin(), NE = I->second.end(); N != NE; ++N) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000766
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000767 }
768
769
Tanya Lattner260652a2004-10-30 00:39:07 +0000770 std::set<MSchedGraphNode*> new_recurrence;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000771 //Loop through recurrence and remove any nodes already in the partial order
772 for(std::vector<MSchedGraphNode*>::const_iterator N = I->second.begin(), NE = I->second.end(); N != NE; ++N) {
773 bool found = false;
Tanya Lattner260652a2004-10-30 00:39:07 +0000774 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(), PE = partialOrder.end(); PO != PE; ++PO) {
775 if(PO->count(*N))
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000776 found = true;
777 }
778 if(!found) {
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000779 if((*N)->isBranch()) {
780 if((*N)->getInst()->getOpcode() == V9::BA)
781 FinalNodeOrder.push_back(*N);
782 else
783 otherBranch.push_back(*N);
784 }
785 else
786 new_recurrence.insert(*N);
787 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000788 if(partialOrder.size() == 0)
789 //For each predecessors, add it to this recurrence ONLY if it is not already in it
790 for(MSchedGraphNode::pred_iterator P = (*N)->pred_begin(),
791 PE = (*N)->pred_end(); P != PE; ++P) {
792
793 //Check if we are supposed to ignore this edge or not
794 if(!ignoreEdge(*P, *N))
795 //Check if already in this recurrence
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000796 if(std::find(I->second.begin(), I->second.end(), *P) == I->second.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000797 //Also need to check if in partial order
798 bool predFound = false;
Tanya Lattner260652a2004-10-30 00:39:07 +0000799 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(), PEND = partialOrder.end(); PO != PEND; ++PO) {
800 if(PO->count(*P))
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000801 predFound = true;
802 }
803
804 if(!predFound)
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000805 if(!new_recurrence.count(*P)) {
806 if((*P)->isBranch()) {
807 if((*P)->getInst()->getOpcode() == V9::BA)
808 FinalNodeOrder.push_back(*P);
809 else
810 otherBranch.push_back(*P);
811 }
812 else
813 new_recurrence.insert(*P);
814
815 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000816 }
817 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000818 }
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000819
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000820 if(new_recurrence.size() > 0)
821 partialOrder.push_back(new_recurrence);
822 }
823
824 //Add any nodes that are not already in the partial order
Tanya Lattner260652a2004-10-30 00:39:07 +0000825 //Add them in a set, one set per connected component
826 std::set<MSchedGraphNode*> lastNodes;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000827 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
828 bool found = false;
829 //Check if its already in our partial order, if not add it to the final vector
Tanya Lattner260652a2004-10-30 00:39:07 +0000830 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(), PE = partialOrder.end(); PO != PE; ++PO) {
831 if(PO->count(I->first))
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000832 found = true;
833 }
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000834 if(!found) {
835 if(I->first->isBranch()) {
836 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), I->first) == FinalNodeOrder.end())
837 if((I->first)->getInst()->getOpcode() == V9::BA)
838 FinalNodeOrder.push_back(I->first);
839 else
840 otherBranch.push_back(I->first);
841 }
842 else
843 lastNodes.insert(I->first);
844 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000845 }
846
Tanya Lattner260652a2004-10-30 00:39:07 +0000847 //Break up remaining nodes that are not in the partial order
848 //into their connected compoenents
849 while(lastNodes.size() > 0) {
850 std::set<MSchedGraphNode*> ccSet;
851 connectedComponentSet(*(lastNodes.begin()),ccSet, lastNodes);
852 if(ccSet.size() > 0)
853 partialOrder.push_back(ccSet);
854 }
855 //if(lastNodes.size() > 0)
856 //partialOrder.push_back(lastNodes);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000857
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000858 //Clean up branches by putting them in final order
859 for(std::vector<MSchedGraphNode*>::iterator I = otherBranch.begin(), E = otherBranch.end(); I != E; ++I)
860 FinalNodeOrder.push_back(*I);
861
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000862}
863
864
Tanya Lattner260652a2004-10-30 00:39:07 +0000865void ModuloSchedulingPass::connectedComponentSet(MSchedGraphNode *node, std::set<MSchedGraphNode*> &ccSet, std::set<MSchedGraphNode*> &lastNodes) {
866
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000867//Add to final set
868if( !ccSet.count(node) && lastNodes.count(node)) {
Tanya Lattner260652a2004-10-30 00:39:07 +0000869 lastNodes.erase(node);
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000870if(node->isBranch())
871 FinalNodeOrder.push_back(node);
872 else
873 ccSet.insert(node);
Tanya Lattner260652a2004-10-30 00:39:07 +0000874 }
875 else
876 return;
877
878 //Loop over successors and recurse if we have not seen this node before
879 for(MSchedGraphNode::succ_iterator node_succ = node->succ_begin(), end=node->succ_end(); node_succ != end; ++node_succ) {
880 connectedComponentSet(*node_succ, ccSet, lastNodes);
881 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000882
Tanya Lattner260652a2004-10-30 00:39:07 +0000883}
884
885void ModuloSchedulingPass::predIntersect(std::set<MSchedGraphNode*> &CurrentSet, std::set<MSchedGraphNode*> &IntersectResult) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000886
887 for(unsigned j=0; j < FinalNodeOrder.size(); ++j) {
888 for(MSchedGraphNode::pred_iterator P = FinalNodeOrder[j]->pred_begin(),
889 E = FinalNodeOrder[j]->pred_end(); P != E; ++P) {
890
891 //Check if we are supposed to ignore this edge or not
892 if(ignoreEdge(*P,FinalNodeOrder[j]))
893 continue;
894
Tanya Lattner260652a2004-10-30 00:39:07 +0000895 if(CurrentSet.count(*P))
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000896 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), *P) == FinalNodeOrder.end())
Tanya Lattner260652a2004-10-30 00:39:07 +0000897 IntersectResult.insert(*P);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000898 }
899 }
900}
901
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000902
Tanya Lattner260652a2004-10-30 00:39:07 +0000903
904
905
906void ModuloSchedulingPass::succIntersect(std::set<MSchedGraphNode*> &CurrentSet, std::set<MSchedGraphNode*> &IntersectResult) {
907
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000908 for(unsigned j=0; j < FinalNodeOrder.size(); ++j) {
909 for(MSchedGraphNode::succ_iterator P = FinalNodeOrder[j]->succ_begin(),
910 E = FinalNodeOrder[j]->succ_end(); P != E; ++P) {
911
912 //Check if we are supposed to ignore this edge or not
913 if(ignoreEdge(FinalNodeOrder[j],*P))
914 continue;
915
Tanya Lattner260652a2004-10-30 00:39:07 +0000916 if(CurrentSet.count(*P))
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000917 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), *P) == FinalNodeOrder.end())
Tanya Lattner260652a2004-10-30 00:39:07 +0000918 IntersectResult.insert(*P);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000919 }
920 }
921}
922
Tanya Lattner260652a2004-10-30 00:39:07 +0000923void dumpIntersection(std::set<MSchedGraphNode*> &IntersectCurrent) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000924 std::cerr << "Intersection (";
Tanya Lattner260652a2004-10-30 00:39:07 +0000925 for(std::set<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(), E = IntersectCurrent.end(); I != E; ++I)
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000926 std::cerr << **I << ", ";
927 std::cerr << ")\n";
928}
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000929
930
931
932void ModuloSchedulingPass::orderNodes() {
933
934 int BOTTOM_UP = 0;
935 int TOP_DOWN = 1;
936
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000937 //Set default order
938 int order = BOTTOM_UP;
939
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000940
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000941 //Loop over all the sets and place them in the final node order
Tanya Lattner260652a2004-10-30 00:39:07 +0000942 for(std::vector<std::set<MSchedGraphNode*> >::iterator CurrentSet = partialOrder.begin(), E= partialOrder.end(); CurrentSet != E; ++CurrentSet) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000943
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000944 DEBUG(std::cerr << "Processing set in S\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000945 DEBUG(dumpIntersection(*CurrentSet));
946
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000947 //Result of intersection
Tanya Lattner260652a2004-10-30 00:39:07 +0000948 std::set<MSchedGraphNode*> IntersectCurrent;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000949
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000950 predIntersect(*CurrentSet, IntersectCurrent);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000951
952 //If the intersection of predecessor and current set is not empty
953 //sort nodes bottom up
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000954 if(IntersectCurrent.size() != 0) {
955 DEBUG(std::cerr << "Final Node Order Predecessors and Current Set interesection is NOT empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000956 order = BOTTOM_UP;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000957 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000958 //If empty, use successors
959 else {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000960 DEBUG(std::cerr << "Final Node Order Predecessors and Current Set interesection is empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000961
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000962 succIntersect(*CurrentSet, IntersectCurrent);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000963
964 //sort top-down
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000965 if(IntersectCurrent.size() != 0) {
966 DEBUG(std::cerr << "Final Node Order Successors and Current Set interesection is NOT empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000967 order = TOP_DOWN;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000968 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000969 else {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000970 DEBUG(std::cerr << "Final Node Order Successors and Current Set interesection is empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000971 //Find node with max ASAP in current Set
972 MSchedGraphNode *node;
973 int maxASAP = 0;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000974 DEBUG(std::cerr << "Using current set of size " << CurrentSet->size() << "to find max ASAP\n");
Tanya Lattner260652a2004-10-30 00:39:07 +0000975 for(std::set<MSchedGraphNode*>::iterator J = CurrentSet->begin(), JE = CurrentSet->end(); J != JE; ++J) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000976 //Get node attributes
Tanya Lattner260652a2004-10-30 00:39:07 +0000977 MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*J)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000978 //assert(nodeAttr != nodeToAttributesMap.end() && "Node not in attributes map!");
Tanya Lattner260652a2004-10-30 00:39:07 +0000979
980 if(maxASAP <= nodeAttr.ASAP) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000981 maxASAP = nodeAttr.ASAP;
Tanya Lattner260652a2004-10-30 00:39:07 +0000982 node = *J;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000983 }
984 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000985 assert(node != 0 && "In node ordering node should not be null");
Tanya Lattner260652a2004-10-30 00:39:07 +0000986 IntersectCurrent.insert(node);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000987 order = BOTTOM_UP;
988 }
989 }
990
991 //Repeat until all nodes are put into the final order from current set
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000992 while(IntersectCurrent.size() > 0) {
993
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000994 if(order == TOP_DOWN) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000995 DEBUG(std::cerr << "Order is TOP DOWN\n");
996
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000997 while(IntersectCurrent.size() > 0) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000998 DEBUG(std::cerr << "Intersection is not empty, so find heighest height\n");
999
1000 int MOB = 0;
1001 int height = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +00001002 MSchedGraphNode *highestHeightNode = *(IntersectCurrent.begin());
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001003
1004 //Find node in intersection with highest heigh and lowest MOB
Tanya Lattner260652a2004-10-30 00:39:07 +00001005 for(std::set<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(),
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001006 E = IntersectCurrent.end(); I != E; ++I) {
1007
1008 //Get current nodes properties
1009 MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*I)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001010
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001011 if(height < nodeAttr.height) {
1012 highestHeightNode = *I;
1013 height = nodeAttr.height;
1014 MOB = nodeAttr.MOB;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001015 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001016 else if(height == nodeAttr.height) {
1017 if(MOB > nodeAttr.height) {
1018 highestHeightNode = *I;
1019 height = nodeAttr.height;
1020 MOB = nodeAttr.MOB;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001021 }
1022 }
1023 }
1024
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001025 //Append our node with greatest height to the NodeOrder
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001026 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), highestHeightNode) == FinalNodeOrder.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001027 DEBUG(std::cerr << "Adding node to Final Order: " << *highestHeightNode << "\n");
1028 FinalNodeOrder.push_back(highestHeightNode);
1029 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001030
1031 //Remove V from IntersectOrder
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001032 IntersectCurrent.erase(std::find(IntersectCurrent.begin(),
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001033 IntersectCurrent.end(), highestHeightNode));
1034
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001035
1036 //Intersect V's successors with CurrentSet
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001037 for(MSchedGraphNode::succ_iterator P = highestHeightNode->succ_begin(),
1038 E = highestHeightNode->succ_end(); P != E; ++P) {
1039 //if(lower_bound(CurrentSet->begin(),
1040 // CurrentSet->end(), *P) != CurrentSet->end()) {
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001041 if(std::find(CurrentSet->begin(), CurrentSet->end(), *P) != CurrentSet->end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001042 if(ignoreEdge(highestHeightNode, *P))
1043 continue;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001044 //If not already in Intersect, add
Tanya Lattner260652a2004-10-30 00:39:07 +00001045 if(!IntersectCurrent.count(*P))
1046 IntersectCurrent.insert(*P);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001047 }
1048 }
1049 } //End while loop over Intersect Size
1050
1051 //Change direction
1052 order = BOTTOM_UP;
1053
1054 //Reset Intersect to reflect changes in OrderNodes
1055 IntersectCurrent.clear();
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001056 predIntersect(*CurrentSet, IntersectCurrent);
1057
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001058 } //End If TOP_DOWN
1059
1060 //Begin if BOTTOM_UP
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001061 else {
1062 DEBUG(std::cerr << "Order is BOTTOM UP\n");
1063 while(IntersectCurrent.size() > 0) {
1064 DEBUG(std::cerr << "Intersection of size " << IntersectCurrent.size() << ", finding highest depth\n");
1065
1066 //dump intersection
1067 DEBUG(dumpIntersection(IntersectCurrent));
1068 //Get node with highest depth, if a tie, use one with lowest
1069 //MOB
1070 int MOB = 0;
1071 int depth = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +00001072 MSchedGraphNode *highestDepthNode = *(IntersectCurrent.begin());
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001073
Tanya Lattner260652a2004-10-30 00:39:07 +00001074 for(std::set<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(),
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001075 E = IntersectCurrent.end(); I != E; ++I) {
1076 //Find node attribute in graph
1077 MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*I)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001078
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001079 if(depth < nodeAttr.depth) {
1080 highestDepthNode = *I;
1081 depth = nodeAttr.depth;
1082 MOB = nodeAttr.MOB;
1083 }
1084 else if(depth == nodeAttr.depth) {
1085 if(MOB > nodeAttr.MOB) {
1086 highestDepthNode = *I;
1087 depth = nodeAttr.depth;
1088 MOB = nodeAttr.MOB;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001089 }
1090 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001091 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001092
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001093
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001094
1095 //Append highest depth node to the NodeOrder
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001096 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), highestDepthNode) == FinalNodeOrder.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001097 DEBUG(std::cerr << "Adding node to Final Order: " << *highestDepthNode << "\n");
1098 FinalNodeOrder.push_back(highestDepthNode);
1099 }
1100 //Remove heightestDepthNode from IntersectOrder
Tanya Lattner260652a2004-10-30 00:39:07 +00001101 IntersectCurrent.erase(highestDepthNode);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001102
1103
1104 //Intersect heightDepthNode's pred with CurrentSet
1105 for(MSchedGraphNode::pred_iterator P = highestDepthNode->pred_begin(),
1106 E = highestDepthNode->pred_end(); P != E; ++P) {
Tanya Lattner260652a2004-10-30 00:39:07 +00001107 if(CurrentSet->count(*P)) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001108 if(ignoreEdge(*P, highestDepthNode))
1109 continue;
1110
1111 //If not already in Intersect, add
Tanya Lattner260652a2004-10-30 00:39:07 +00001112 if(!IntersectCurrent.count(*P))
1113 IntersectCurrent.insert(*P);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001114 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001115 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001116
1117 } //End while loop over Intersect Size
1118
1119 //Change order
1120 order = TOP_DOWN;
1121
1122 //Reset IntersectCurrent to reflect changes in OrderNodes
1123 IntersectCurrent.clear();
1124 succIntersect(*CurrentSet, IntersectCurrent);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001125 } //End if BOTTOM_DOWN
1126
Tanya Lattner420025b2004-10-10 22:44:35 +00001127 DEBUG(std::cerr << "Current Intersection Size: " << IntersectCurrent.size() << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001128 }
1129 //End Wrapping while loop
Tanya Lattner420025b2004-10-10 22:44:35 +00001130 DEBUG(std::cerr << "Ending Size of Current Set: " << CurrentSet->size() << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001131 }//End for over all sets of nodes
Tanya Lattner420025b2004-10-10 22:44:35 +00001132
1133 //FIXME: As the algorithm stands it will NEVER add an instruction such as ba (with no
1134 //data dependencies) to the final order. We add this manually. It will always be
1135 //in the last set of S since its not part of a recurrence
1136 //Loop over all the sets and place them in the final node order
Tanya Lattner260652a2004-10-30 00:39:07 +00001137 std::vector<std::set<MSchedGraphNode*> > ::reverse_iterator LastSet = partialOrder.rbegin();
1138 for(std::set<MSchedGraphNode*>::iterator CurrentNode = LastSet->begin(), LastNode = LastSet->end();
Tanya Lattner420025b2004-10-10 22:44:35 +00001139 CurrentNode != LastNode; ++CurrentNode) {
1140 if((*CurrentNode)->getInst()->getOpcode() == V9::BA)
1141 FinalNodeOrder.push_back(*CurrentNode);
1142 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001143 //Return final Order
1144 //return FinalNodeOrder;
1145}
1146
1147void ModuloSchedulingPass::computeSchedule() {
1148
1149 bool success = false;
1150
Tanya Lattner260652a2004-10-30 00:39:07 +00001151 //FIXME: Should be set to max II of the original loop
1152 //Cap II in order to prevent infinite loop
1153 int capII = 30;
1154
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001155 while(!success) {
Tanya Lattnera6ec8f52004-11-24 01:49:10 +00001156
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001157 //Loop over the final node order and process each node
1158 for(std::vector<MSchedGraphNode*>::iterator I = FinalNodeOrder.begin(),
1159 E = FinalNodeOrder.end(); I != E; ++I) {
1160
1161 //CalculateEarly and Late start
1162 int EarlyStart = -1;
1163 int LateStart = 99999; //Set to something higher then we would ever expect (FIXME)
1164 bool hasSucc = false;
1165 bool hasPred = false;
Tanya Lattner4cffb582004-05-26 06:27:18 +00001166
1167 if(!(*I)->isBranch()) {
1168 //Loop over nodes in the schedule and determine if they are predecessors
1169 //or successors of the node we are trying to schedule
1170 for(MSSchedule::schedule_iterator nodesByCycle = schedule.begin(), nodesByCycleEnd = schedule.end();
1171 nodesByCycle != nodesByCycleEnd; ++nodesByCycle) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001172
Tanya Lattner4cffb582004-05-26 06:27:18 +00001173 //For this cycle, get the vector of nodes schedule and loop over it
1174 for(std::vector<MSchedGraphNode*>::iterator schedNode = nodesByCycle->second.begin(), SNE = nodesByCycle->second.end(); schedNode != SNE; ++schedNode) {
1175
1176 if((*I)->isPredecessor(*schedNode)) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001177 if(!ignoreEdge(*schedNode, *I)) {
1178 int diff = (*I)->getInEdge(*schedNode).getIteDiff();
Tanya Lattner4cffb582004-05-26 06:27:18 +00001179 int ES_Temp = nodesByCycle->first + (*schedNode)->getLatency() - diff * II;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001180 DEBUG(std::cerr << "Diff: " << diff << " Cycle: " << nodesByCycle->first << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001181 DEBUG(std::cerr << "Temp EarlyStart: " << ES_Temp << " Prev EarlyStart: " << EarlyStart << "\n");
1182 EarlyStart = std::max(EarlyStart, ES_Temp);
1183 hasPred = true;
1184 }
1185 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001186 if((*I)->isSuccessor(*schedNode)) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001187 if(!ignoreEdge(*I,*schedNode)) {
1188 int diff = (*schedNode)->getInEdge(*I).getIteDiff();
Tanya Lattner4cffb582004-05-26 06:27:18 +00001189 int LS_Temp = nodesByCycle->first - (*I)->getLatency() + diff * II;
1190 DEBUG(std::cerr << "Diff: " << diff << " Cycle: " << nodesByCycle->first << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001191 DEBUG(std::cerr << "Temp LateStart: " << LS_Temp << " Prev LateStart: " << LateStart << "\n");
1192 LateStart = std::min(LateStart, LS_Temp);
1193 hasSucc = true;
1194 }
1195 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001196 }
1197 }
1198 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001199 else {
1200 //WARNING: HACK! FIXME!!!!
Tanya Lattner420025b2004-10-10 22:44:35 +00001201 if((*I)->getInst()->getOpcode() == V9::BA) {
1202 EarlyStart = II-1;
1203 LateStart = II-1;
1204 }
1205 else {
Tanya Lattnera6ec8f52004-11-24 01:49:10 +00001206 EarlyStart = II-2;
1207 LateStart = 0;
Tanya Lattner420025b2004-10-10 22:44:35 +00001208 assert( (EarlyStart >= 0) && (LateStart >=0) && "EarlyStart and LateStart must be greater then 0");
1209 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001210 hasPred = 1;
1211 hasSucc = 1;
1212 }
1213
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001214
1215 DEBUG(std::cerr << "Has Successors: " << hasSucc << ", Has Pred: " << hasPred << "\n");
1216 DEBUG(std::cerr << "EarlyStart: " << EarlyStart << ", LateStart: " << LateStart << "\n");
1217
1218 //Check if the node has no pred or successors and set Early Start to its ASAP
1219 if(!hasSucc && !hasPred)
1220 EarlyStart = nodeToAttributesMap.find(*I)->second.ASAP;
1221
1222 //Now, try to schedule this node depending upon its pred and successor in the schedule
1223 //already
1224 if(!hasSucc && hasPred)
1225 success = scheduleNode(*I, EarlyStart, (EarlyStart + II -1));
1226 else if(!hasPred && hasSucc)
1227 success = scheduleNode(*I, LateStart, (LateStart - II +1));
1228 else if(hasPred && hasSucc)
1229 success = scheduleNode(*I, EarlyStart, std::min(LateStart, (EarlyStart + II -1)));
1230 else
1231 success = scheduleNode(*I, EarlyStart, EarlyStart + II - 1);
1232
1233 if(!success) {
Tanya Lattnere1df2122004-11-22 20:41:24 +00001234 ++IncreasedII;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001235 ++II;
1236 schedule.clear();
1237 break;
1238 }
1239
1240 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001241
Tanya Lattner260652a2004-10-30 00:39:07 +00001242 if(success) {
1243 DEBUG(std::cerr << "Constructing Schedule Kernel\n");
1244 success = schedule.constructKernel(II);
1245 DEBUG(std::cerr << "Done Constructing Schedule Kernel\n");
1246 if(!success) {
Tanya Lattnere1df2122004-11-22 20:41:24 +00001247 ++IncreasedII;
Tanya Lattner260652a2004-10-30 00:39:07 +00001248 ++II;
1249 schedule.clear();
1250 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001251 }
Tanya Lattner260652a2004-10-30 00:39:07 +00001252
1253 assert(II < capII && "The II should not exceed the original loop number of cycles");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001254 }
1255}
1256
1257
1258bool ModuloSchedulingPass::scheduleNode(MSchedGraphNode *node,
1259 int start, int end) {
1260 bool success = false;
1261
1262 DEBUG(std::cerr << *node << " (Start Cycle: " << start << ", End Cycle: " << end << ")\n");
1263
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001264 //Make sure start and end are not negative
Tanya Lattner260652a2004-10-30 00:39:07 +00001265 if(start < 0) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001266 start = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +00001267
1268 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001269 if(end < 0)
1270 end = 0;
1271
1272 bool forward = true;
1273 if(start > end)
1274 forward = false;
1275
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001276 bool increaseSC = true;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001277 int cycle = start ;
1278
1279
1280 while(increaseSC) {
1281
1282 increaseSC = false;
1283
Tanya Lattner4cffb582004-05-26 06:27:18 +00001284 increaseSC = schedule.insert(node, cycle);
1285
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001286 if(!increaseSC)
1287 return true;
1288
1289 //Increment cycle to try again
1290 if(forward) {
1291 ++cycle;
1292 DEBUG(std::cerr << "Increase cycle: " << cycle << "\n");
1293 if(cycle > end)
1294 return false;
1295 }
1296 else {
1297 --cycle;
1298 DEBUG(std::cerr << "Decrease cycle: " << cycle << "\n");
1299 if(cycle < end)
1300 return false;
1301 }
1302 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001303
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001304 return success;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001305}
Tanya Lattner4cffb582004-05-26 06:27:18 +00001306
Tanya Lattner420025b2004-10-10 22:44:35 +00001307void 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 +00001308
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001309 //Keep a map to easily know whats in the kernel
Tanya Lattner4cffb582004-05-26 06:27:18 +00001310 std::map<int, std::set<const MachineInstr*> > inKernel;
1311 int maxStageCount = 0;
1312
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001313 MSchedGraphNode *branch = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +00001314 MSchedGraphNode *BAbranch = 0;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001315
Tanya Lattnere1df2122004-11-22 20:41:24 +00001316 schedule.print(std::cerr);
1317
Tanya Lattner4cffb582004-05-26 06:27:18 +00001318 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
1319 maxStageCount = std::max(maxStageCount, I->second);
1320
1321 //Ignore the branch, we will handle this separately
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001322 if(I->first->isBranch()) {
Tanya Lattnera6457502004-10-14 06:04:28 +00001323 if (I->first->getInst()->getOpcode() != V9::BA)
Tanya Lattner420025b2004-10-10 22:44:35 +00001324 branch = I->first;
Tanya Lattner260652a2004-10-30 00:39:07 +00001325 else
1326 BAbranch = I->first;
1327
Tanya Lattner4cffb582004-05-26 06:27:18 +00001328 continue;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001329 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001330
1331 //Put int the map so we know what instructions in each stage are in the kernel
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001332 DEBUG(std::cerr << "Inserting instruction " << *(I->first->getInst()) << " into map at stage " << I->second << "\n");
1333 inKernel[I->second].insert(I->first->getInst());
Tanya Lattner4cffb582004-05-26 06:27:18 +00001334 }
1335
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001336 //Get target information to look at machine operands
1337 const TargetInstrInfo *mii = target.getInstrInfo();
1338
1339 //Now write the prologues
1340 for(int i = 0; i < maxStageCount; ++i) {
1341 BasicBlock *llvmBB = new BasicBlock("PROLOGUE", (Function*) (origBB->getBasicBlock()->getParent()));
Tanya Lattner4cffb582004-05-26 06:27:18 +00001342 MachineBasicBlock *machineBB = new MachineBasicBlock(llvmBB);
1343
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001344 DEBUG(std::cerr << "i=" << i << "\n");
1345 for(int j = 0; j <= i; ++j) {
1346 for(MachineBasicBlock::const_iterator MI = origBB->begin(), ME = origBB->end(); ME != MI; ++MI) {
1347 if(inKernel[j].count(&*MI)) {
Tanya Lattner420025b2004-10-10 22:44:35 +00001348 MachineInstr *instClone = MI->clone();
1349 machineBB->push_back(instClone);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001350
Tanya Lattner420025b2004-10-10 22:44:35 +00001351 DEBUG(std::cerr << "Cloning: " << *MI << "\n");
1352
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001353 Instruction *tmp;
1354
1355 //After cloning, we may need to save the value that this instruction defines
1356 for(unsigned opNum=0; opNum < MI->getNumOperands(); ++opNum) {
1357 //get machine operand
Tanya Lattner420025b2004-10-10 22:44:35 +00001358 const MachineOperand &mOp = instClone->getOperand(opNum);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001359 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef()) {
1360
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001361 //Check if this is a value we should save
1362 if(valuesToSave.count(mOp.getVRegValue())) {
1363 //Save copy in tmpInstruction
1364 tmp = new TmpInstruction(mOp.getVRegValue());
1365
Tanya Lattner80f08552004-11-02 21:04:56 +00001366 //Add TmpInstruction to safe LLVM Instruction MCFI
1367 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001368 tempMvec.addTemp((Value*) tmp);
1369
Tanya Lattner420025b2004-10-10 22:44:35 +00001370 DEBUG(std::cerr << "Value: " << *(mOp.getVRegValue()) << " New Value: " << *tmp << " Stage: " << i << "\n");
1371
1372 newValues[mOp.getVRegValue()][i]= tmp;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001373 newValLocation[tmp] = machineBB;
1374
Tanya Lattner420025b2004-10-10 22:44:35 +00001375 DEBUG(std::cerr << "Machine Instr Operands: " << *(mOp.getVRegValue()) << ", 0, " << *tmp << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001376
1377 //Create machine instruction and put int machineBB
1378 MachineInstr *saveValue = BuildMI(machineBB, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
1379
1380 DEBUG(std::cerr << "Created new machine instr: " << *saveValue << "\n");
1381 }
1382 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001383
1384 //We may also need to update the value that we use if its from an earlier prologue
1385 if(j != 0) {
1386 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse()) {
1387 if(newValues.count(mOp.getVRegValue()))
1388 if(newValues[mOp.getVRegValue()].count(j-1)) {
1389 DEBUG(std::cerr << "Replaced this value: " << mOp.getVRegValue() << " With:" << (newValues[mOp.getVRegValue()][i-1]) << "\n");
1390 //Update the operand with the right value
1391 instClone->getOperand(opNum).setValueReg(newValues[mOp.getVRegValue()][i-1]);
1392 }
1393 }
1394 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001395 }
1396 }
Tanya Lattner20890832004-05-28 20:14:12 +00001397 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001398 }
1399
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001400
1401 //Stick in branch at the end
1402 machineBB->push_back(branch->getInst()->clone());
Tanya Lattner420025b2004-10-10 22:44:35 +00001403
Tanya Lattner260652a2004-10-30 00:39:07 +00001404 //Add nop
1405 BuildMI(machineBB, V9::NOP, 0);
1406
1407 //Stick in branch at the end
1408 machineBB->push_back(BAbranch->getInst()->clone());
1409
1410 //Add nop
1411 BuildMI(machineBB, V9::NOP, 0);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001412
1413 (((MachineBasicBlock*)origBB)->getParent())->getBasicBlockList().push_back(machineBB);
Tanya Lattner4cffb582004-05-26 06:27:18 +00001414 prologues.push_back(machineBB);
1415 llvm_prologues.push_back(llvmBB);
1416 }
1417}
1418
Tanya Lattner420025b2004-10-10 22:44:35 +00001419void 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 +00001420
Tanya Lattner20890832004-05-28 20:14:12 +00001421 std::map<int, std::set<const MachineInstr*> > inKernel;
Tanya Lattner420025b2004-10-10 22:44:35 +00001422
Tanya Lattner20890832004-05-28 20:14:12 +00001423 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
Tanya Lattner20890832004-05-28 20:14:12 +00001424
1425 //Ignore the branch, we will handle this separately
1426 if(I->first->isBranch())
1427 continue;
1428
1429 //Put int the map so we know what instructions in each stage are in the kernel
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001430 inKernel[I->second].insert(I->first->getInst());
Tanya Lattner20890832004-05-28 20:14:12 +00001431 }
1432
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001433 std::map<Value*, Value*> valPHIs;
1434
Tanya Lattner420025b2004-10-10 22:44:35 +00001435 //some debug stuff, will remove later
1436 DEBUG(for(std::map<Value*, std::map<int, Value*> >::iterator V = newValues.begin(), E = newValues.end(); V !=E; ++V) {
1437 std::cerr << "Old Value: " << *(V->first) << "\n";
1438 for(std::map<int, Value*>::iterator I = V->second.begin(), IE = V->second.end(); I != IE; ++I)
1439 std::cerr << "Stage: " << I->first << " Value: " << *(I->second) << "\n";
1440 });
1441
1442 //some debug stuff, will remove later
1443 DEBUG(for(std::map<Value*, std::map<int, Value*> >::iterator V = kernelPHIs.begin(), E = kernelPHIs.end(); V !=E; ++V) {
1444 std::cerr << "Old Value: " << *(V->first) << "\n";
1445 for(std::map<int, Value*>::iterator I = V->second.begin(), IE = V->second.end(); I != IE; ++I)
1446 std::cerr << "Stage: " << I->first << " Value: " << *(I->second) << "\n";
1447 });
1448
Tanya Lattner20890832004-05-28 20:14:12 +00001449 //Now write the epilogues
Tanya Lattner420025b2004-10-10 22:44:35 +00001450 for(int i = schedule.getMaxStage()-1; i >= 0; --i) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001451 BasicBlock *llvmBB = new BasicBlock("EPILOGUE", (Function*) (origBB->getBasicBlock()->getParent()));
Tanya Lattner20890832004-05-28 20:14:12 +00001452 MachineBasicBlock *machineBB = new MachineBasicBlock(llvmBB);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001453
Tanya Lattner420025b2004-10-10 22:44:35 +00001454 DEBUG(std::cerr << " Epilogue #: " << i << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001455
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001456
Tanya Lattnera6457502004-10-14 06:04:28 +00001457 std::map<Value*, int> inEpilogue;
Tanya Lattner420025b2004-10-10 22:44:35 +00001458
1459 for(MachineBasicBlock::const_iterator MI = origBB->begin(), ME = origBB->end(); ME != MI; ++MI) {
1460 for(int j=schedule.getMaxStage(); j > i; --j) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001461 if(inKernel[j].count(&*MI)) {
1462 DEBUG(std::cerr << "Cloning instruction " << *MI << "\n");
1463 MachineInstr *clone = MI->clone();
1464
1465 //Update operands that need to use the result from the phi
Tanya Lattner420025b2004-10-10 22:44:35 +00001466 for(unsigned opNum=0; opNum < clone->getNumOperands(); ++opNum) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001467 //get machine operand
Tanya Lattner420025b2004-10-10 22:44:35 +00001468 const MachineOperand &mOp = clone->getOperand(opNum);
Tanya Lattner420025b2004-10-10 22:44:35 +00001469
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001470 if((mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse())) {
Tanya Lattner420025b2004-10-10 22:44:35 +00001471
1472 DEBUG(std::cerr << "Writing PHI for " << *(mOp.getVRegValue()) << "\n");
Tanya Lattnera6457502004-10-14 06:04:28 +00001473
1474 //If this is the last instructions for the max iterations ago, don't update operands
1475 if(inEpilogue.count(mOp.getVRegValue()))
1476 if(inEpilogue[mOp.getVRegValue()] == i)
1477 continue;
Tanya Lattner420025b2004-10-10 22:44:35 +00001478
1479 //Quickly write appropriate phis for this operand
1480 if(newValues.count(mOp.getVRegValue())) {
1481 if(newValues[mOp.getVRegValue()].count(i)) {
1482 Instruction *tmp = new TmpInstruction(newValues[mOp.getVRegValue()][i]);
Tanya Lattnera6457502004-10-14 06:04:28 +00001483
1484 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00001485 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001486 tempMvec.addTemp((Value*) tmp);
1487
Tanya Lattner420025b2004-10-10 22:44:35 +00001488 MachineInstr *saveValue = BuildMI(machineBB, V9::PHI, 3).addReg(newValues[mOp.getVRegValue()][i]).addReg(kernelPHIs[mOp.getVRegValue()][i]).addRegDef(tmp);
1489 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
1490 valPHIs[mOp.getVRegValue()] = tmp;
1491 }
1492 }
1493
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001494 if(valPHIs.count(mOp.getVRegValue())) {
1495 //Update the operand in the cloned instruction
Tanya Lattner420025b2004-10-10 22:44:35 +00001496 clone->getOperand(opNum).setValueReg(valPHIs[mOp.getVRegValue()]);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001497 }
1498 }
Tanya Lattnera6457502004-10-14 06:04:28 +00001499 else if((mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef())) {
1500 inEpilogue[mOp.getVRegValue()] = i;
1501 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001502 }
1503 machineBB->push_back(clone);
1504 }
1505 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001506 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001507
Tanya Lattner20890832004-05-28 20:14:12 +00001508 (((MachineBasicBlock*)origBB)->getParent())->getBasicBlockList().push_back(machineBB);
1509 epilogues.push_back(machineBB);
1510 llvm_epilogues.push_back(llvmBB);
Tanya Lattner420025b2004-10-10 22:44:35 +00001511
1512 DEBUG(std::cerr << "EPILOGUE #" << i << "\n");
1513 DEBUG(machineBB->print(std::cerr));
Tanya Lattner20890832004-05-28 20:14:12 +00001514 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001515}
1516
Tanya Lattner420025b2004-10-10 22:44:35 +00001517void 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 +00001518
1519 //Keep track of operands that are read and saved from a previous iteration. The new clone
1520 //instruction will use the result of the phi instead.
1521 std::map<Value*, Value*> finalPHIValue;
1522 std::map<Value*, Value*> kernelValue;
1523
1524 //Create TmpInstructions for the final phis
1525 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
1526
Tanya Lattner420025b2004-10-10 22:44:35 +00001527 DEBUG(std::cerr << "Stage: " << I->second << " Inst: " << *(I->first->getInst()) << "\n";);
1528
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001529 //Clone instruction
1530 const MachineInstr *inst = I->first->getInst();
1531 MachineInstr *instClone = inst->clone();
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001532
Tanya Lattner420025b2004-10-10 22:44:35 +00001533 //Insert into machine basic block
1534 machineBB->push_back(instClone);
1535
Tanya Lattnerced82222004-11-16 21:31:37 +00001536 DEBUG(std::cerr << "Cloned Inst: " << *instClone << "\n");
1537
Tanya Lattnera6457502004-10-14 06:04:28 +00001538 if(I->first->isBranch()) {
1539 //Add kernel noop
1540 BuildMI(machineBB, V9::NOP, 0);
1541 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001542
1543 //Loop over Machine Operands
1544 for(unsigned i=0; i < inst->getNumOperands(); ++i) {
1545 //get machine operand
1546 const MachineOperand &mOp = inst->getOperand(i);
1547
1548 if(I->second != 0) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001549 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse()) {
Tanya Lattner420025b2004-10-10 22:44:35 +00001550
1551 //Check to see where this operand is defined if this instruction is from max stage
1552 if(I->second == schedule.getMaxStage()) {
1553 DEBUG(std::cerr << "VREG: " << *(mOp.getVRegValue()) << "\n");
1554 }
1555
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001556 //If its in the value saved, we need to create a temp instruction and use that instead
1557 if(valuesToSave.count(mOp.getVRegValue())) {
Tanya Lattnerced82222004-11-16 21:31:37 +00001558
1559 //Check if we already have a final PHI value for this
1560 if(!finalPHIValue.count(mOp.getVRegValue())) {
1561 TmpInstruction *tmp = new TmpInstruction(mOp.getVRegValue());
1562
1563 //Get machine code for this instruction
1564 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
1565 tempMvec.addTemp((Value*) tmp);
1566
1567 //Update the operand in the cloned instruction
1568 instClone->getOperand(i).setValueReg(tmp);
1569
1570 //save this as our final phi
1571 finalPHIValue[mOp.getVRegValue()] = tmp;
1572 newValLocation[tmp] = machineBB;
1573 }
1574 else {
1575 //Use the previous final phi value
1576 instClone->getOperand(i).setValueReg(finalPHIValue[mOp.getVRegValue()]);
1577 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001578 }
1579 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001580 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001581 if(I->second != schedule.getMaxStage()) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001582 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef()) {
1583 if(valuesToSave.count(mOp.getVRegValue())) {
1584
1585 TmpInstruction *tmp = new TmpInstruction(mOp.getVRegValue());
1586
Tanya Lattnera6457502004-10-14 06:04:28 +00001587 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00001588 MachineCodeForInstruction & tempVec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001589 tempVec.addTemp((Value*) tmp);
1590
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001591 //Create new machine instr and put in MBB
1592 MachineInstr *saveValue = BuildMI(machineBB, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
1593
1594 //Save for future cleanup
1595 kernelValue[mOp.getVRegValue()] = tmp;
1596 newValLocation[tmp] = machineBB;
Tanya Lattner420025b2004-10-10 22:44:35 +00001597 kernelPHIs[mOp.getVRegValue()][schedule.getMaxStage()-1] = tmp;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001598 }
1599 }
1600 }
1601 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001602
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001603 }
1604
Tanya Lattner420025b2004-10-10 22:44:35 +00001605 DEBUG(std::cerr << "KERNEL before PHIs\n");
1606 DEBUG(machineBB->print(std::cerr));
1607
1608
1609 //Loop over each value we need to generate phis for
1610 for(std::map<Value*, std::map<int, Value*> >::iterator V = newValues.begin(),
1611 E = newValues.end(); V != E; ++V) {
1612
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001613
1614 DEBUG(std::cerr << "Writing phi for" << *(V->first));
Tanya Lattner420025b2004-10-10 22:44:35 +00001615 DEBUG(std::cerr << "\nMap of Value* for this phi\n");
1616 DEBUG(for(std::map<int, Value*>::iterator I = V->second.begin(),
1617 IE = V->second.end(); I != IE; ++I) {
1618 std::cerr << "Stage: " << I->first;
1619 std::cerr << " Value: " << *(I->second) << "\n";
1620 });
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001621
Tanya Lattner420025b2004-10-10 22:44:35 +00001622 //If we only have one current iteration live, its safe to set lastPhi = to kernel value
1623 if(V->second.size() == 1) {
1624 assert(kernelValue[V->first] != 0 && "Kernel value* must exist to create phi");
1625 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(),V9::PHI, 3).addReg(V->second.begin()->second).addReg(kernelValue[V->first]).addRegDef(finalPHIValue[V->first]);
1626 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
1627 kernelPHIs[V->first][schedule.getMaxStage()-1] = kernelValue[V->first];
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001628 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001629 else {
1630
1631 //Keep track of last phi created.
1632 Instruction *lastPhi = 0;
1633
1634 unsigned count = 1;
1635 //Loop over the the map backwards to generate phis
1636 for(std::map<int, Value*>::reverse_iterator I = V->second.rbegin(), IE = V->second.rend();
1637 I != IE; ++I) {
1638
1639 if(count < (V->second).size()) {
1640 if(lastPhi == 0) {
1641 lastPhi = new TmpInstruction(I->second);
Tanya Lattnera6457502004-10-14 06:04:28 +00001642
1643 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00001644 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001645 tempMvec.addTemp((Value*) lastPhi);
1646
Tanya Lattner420025b2004-10-10 22:44:35 +00001647 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(), V9::PHI, 3).addReg(kernelValue[V->first]).addReg(I->second).addRegDef(lastPhi);
1648 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
1649 newValLocation[lastPhi] = machineBB;
1650 }
1651 else {
1652 Instruction *tmp = new TmpInstruction(I->second);
Tanya Lattnera6457502004-10-14 06:04:28 +00001653
1654 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00001655 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001656 tempMvec.addTemp((Value*) tmp);
1657
1658
Tanya Lattner420025b2004-10-10 22:44:35 +00001659 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(), V9::PHI, 3).addReg(lastPhi).addReg(I->second).addRegDef(tmp);
1660 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
1661 lastPhi = tmp;
1662 kernelPHIs[V->first][I->first] = lastPhi;
1663 newValLocation[lastPhi] = machineBB;
1664 }
1665 }
1666 //Final phi value
1667 else {
1668 //The resulting value must be the Value* we created earlier
1669 assert(lastPhi != 0 && "Last phi is NULL!\n");
1670 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(), V9::PHI, 3).addReg(lastPhi).addReg(I->second).addRegDef(finalPHIValue[V->first]);
1671 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
1672 kernelPHIs[V->first][I->first] = finalPHIValue[V->first];
1673 }
1674
1675 ++count;
1676 }
1677
1678 }
1679 }
1680
1681 DEBUG(std::cerr << "KERNEL after PHIs\n");
1682 DEBUG(machineBB->print(std::cerr));
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001683}
1684
Tanya Lattner420025b2004-10-10 22:44:35 +00001685
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001686void ModuloSchedulingPass::removePHIs(const MachineBasicBlock *origBB, std::vector<MachineBasicBlock *> &prologues, std::vector<MachineBasicBlock *> &epilogues, MachineBasicBlock *kernelBB, std::map<Value*, MachineBasicBlock*> &newValLocation) {
1687
1688 //Worklist to delete things
1689 std::vector<std::pair<MachineBasicBlock*, MachineBasicBlock::iterator> > worklist;
Tanya Lattnera6457502004-10-14 06:04:28 +00001690
1691 //Worklist of TmpInstructions that need to be added to a MCFI
1692 std::vector<Instruction*> addToMCFI;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001693
Tanya Lattnera6457502004-10-14 06:04:28 +00001694 //Worklist to add OR instructions to end of kernel so not to invalidate the iterator
1695 //std::vector<std::pair<Instruction*, Value*> > newORs;
1696
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001697 const TargetInstrInfo *TMI = target.getInstrInfo();
1698
1699 //Start with the kernel and for each phi insert a copy for the phi def and for each arg
1700 for(MachineBasicBlock::iterator I = kernelBB->begin(), E = kernelBB->end(); I != E; ++I) {
Tanya Lattnera6457502004-10-14 06:04:28 +00001701
Tanya Lattner80f08552004-11-02 21:04:56 +00001702 DEBUG(std::cerr << "Looking at Instr: " << *I << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001703 //Get op code and check if its a phi
Tanya Lattnera6457502004-10-14 06:04:28 +00001704 if(I->getOpcode() == V9::PHI) {
1705
1706 DEBUG(std::cerr << "Replacing PHI: " << *I << "\n");
1707 Instruction *tmp = 0;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001708
Tanya Lattnera6457502004-10-14 06:04:28 +00001709 for(unsigned i = 0; i < I->getNumOperands(); ++i) {
1710 //Get Operand
1711 const MachineOperand &mOp = I->getOperand(i);
1712 assert(mOp.getType() == MachineOperand::MO_VirtualRegister && "Should be a Value*\n");
1713
1714 if(!tmp) {
1715 tmp = new TmpInstruction(mOp.getVRegValue());
1716 addToMCFI.push_back(tmp);
1717 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001718
Tanya Lattnera6457502004-10-14 06:04:28 +00001719 //Now for all our arguments we read, OR to the new TmpInstruction that we created
1720 if(mOp.isUse()) {
1721 DEBUG(std::cerr << "Use: " << mOp << "\n");
1722 //Place a copy at the end of its BB but before the branches
1723 assert(newValLocation.count(mOp.getVRegValue()) && "We must know where this value is located\n");
1724 //Reverse iterate to find the branches, we can safely assume no instructions have been
1725 //put in the nop positions
1726 for(MachineBasicBlock::iterator inst = --(newValLocation[mOp.getVRegValue()])->end(), endBB = (newValLocation[mOp.getVRegValue()])->begin(); inst != endBB; --inst) {
1727 MachineOpCode opc = inst->getOpcode();
1728 if(TMI->isBranch(opc) || TMI->isNop(opc))
1729 continue;
1730 else {
1731 BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
1732 break;
1733 }
1734
1735 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001736
Tanya Lattnera6457502004-10-14 06:04:28 +00001737 }
1738 else {
1739 //Remove the phi and replace it with an OR
1740 DEBUG(std::cerr << "Def: " << mOp << "\n");
1741 //newORs.push_back(std::make_pair(tmp, mOp.getVRegValue()));
1742 BuildMI(*kernelBB, I, V9::ORr, 3).addReg(tmp).addImm(0).addRegDef(mOp.getVRegValue());
1743 worklist.push_back(std::make_pair(kernelBB, I));
1744 }
1745
1746 }
1747
1748 }
1749
Tanya Lattnera6457502004-10-14 06:04:28 +00001750
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001751 }
1752
Tanya Lattner80f08552004-11-02 21:04:56 +00001753 //Add TmpInstructions to some MCFI
1754 if(addToMCFI.size() > 0) {
1755 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
1756 for(unsigned x = 0; x < addToMCFI.size(); ++x) {
1757 tempMvec.addTemp(addToMCFI[x]);
1758 }
1759 addToMCFI.clear();
1760 }
1761
Tanya Lattnera6457502004-10-14 06:04:28 +00001762
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001763 //Remove phis from epilogue
1764 for(std::vector<MachineBasicBlock*>::iterator MB = epilogues.begin(), ME = epilogues.end(); MB != ME; ++MB) {
1765 for(MachineBasicBlock::iterator I = (*MB)->begin(), E = (*MB)->end(); I != E; ++I) {
Tanya Lattner80f08552004-11-02 21:04:56 +00001766
1767 DEBUG(std::cerr << "Looking at Instr: " << *I << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001768 //Get op code and check if its a phi
Brian Gaeke418379e2004-08-18 20:04:24 +00001769 if(I->getOpcode() == V9::PHI) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001770 Instruction *tmp = 0;
Tanya Lattnera6457502004-10-14 06:04:28 +00001771
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001772 for(unsigned i = 0; i < I->getNumOperands(); ++i) {
1773 //Get Operand
1774 const MachineOperand &mOp = I->getOperand(i);
1775 assert(mOp.getType() == MachineOperand::MO_VirtualRegister && "Should be a Value*\n");
1776
1777 if(!tmp) {
1778 tmp = new TmpInstruction(mOp.getVRegValue());
Tanya Lattnera6457502004-10-14 06:04:28 +00001779 addToMCFI.push_back(tmp);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001780 }
1781
1782 //Now for all our arguments we read, OR to the new TmpInstruction that we created
1783 if(mOp.isUse()) {
1784 DEBUG(std::cerr << "Use: " << mOp << "\n");
1785 //Place a copy at the end of its BB but before the branches
1786 assert(newValLocation.count(mOp.getVRegValue()) && "We must know where this value is located\n");
1787 //Reverse iterate to find the branches, we can safely assume no instructions have been
1788 //put in the nop positions
1789 for(MachineBasicBlock::iterator inst = --(newValLocation[mOp.getVRegValue()])->end(), endBB = (newValLocation[mOp.getVRegValue()])->begin(); inst != endBB; --inst) {
1790 MachineOpCode opc = inst->getOpcode();
1791 if(TMI->isBranch(opc) || TMI->isNop(opc))
1792 continue;
1793 else {
1794 BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
1795 break;
1796 }
1797
1798 }
Tanya Lattnera6457502004-10-14 06:04:28 +00001799
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001800 }
1801 else {
1802 //Remove the phi and replace it with an OR
1803 DEBUG(std::cerr << "Def: " << mOp << "\n");
1804 BuildMI(**MB, I, V9::ORr, 3).addReg(tmp).addImm(0).addRegDef(mOp.getVRegValue());
1805 worklist.push_back(std::make_pair(*MB,I));
1806 }
1807
1808 }
1809 }
Tanya Lattnera6457502004-10-14 06:04:28 +00001810
Tanya Lattner80f08552004-11-02 21:04:56 +00001811
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001812 }
1813 }
1814
Tanya Lattner80f08552004-11-02 21:04:56 +00001815
1816 if(addToMCFI.size() > 0) {
1817 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
1818 for(unsigned x = 0; x < addToMCFI.size(); ++x) {
1819 tempMvec.addTemp(addToMCFI[x]);
1820 }
1821 addToMCFI.clear();
1822 }
1823
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001824 //Delete the phis
1825 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 +00001826
1827 DEBUG(std::cerr << "Deleting PHI " << *I->second << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001828 I->first->erase(I->second);
1829
1830 }
1831
Tanya Lattnera6457502004-10-14 06:04:28 +00001832
1833 assert((addToMCFI.size() == 0) && "We should have added all TmpInstructions to some MachineCodeForInstruction");
Tanya Lattner20890832004-05-28 20:14:12 +00001834}
1835
1836
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001837void ModuloSchedulingPass::reconstructLoop(MachineBasicBlock *BB) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00001838
Tanya Lattner420025b2004-10-10 22:44:35 +00001839 DEBUG(std::cerr << "Reconstructing Loop\n");
1840
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001841 //First find the value *'s that we need to "save"
1842 std::map<const Value*, std::pair<const MSchedGraphNode*, int> > valuesToSave;
Tanya Lattner4cffb582004-05-26 06:27:18 +00001843
Tanya Lattner420025b2004-10-10 22:44:35 +00001844 //Keep track of instructions we have already seen and their stage because
1845 //we don't want to "save" values if they are used in the kernel immediately
1846 std::map<const MachineInstr*, int> lastInstrs;
1847
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001848 //Loop over kernel and only look at instructions from a stage > 0
1849 //Look at its operands and save values *'s that are read
Tanya Lattner4cffb582004-05-26 06:27:18 +00001850 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00001851
Tanya Lattner420025b2004-10-10 22:44:35 +00001852 if(I->second !=0) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00001853 //For this instruction, get the Value*'s that it reads and put them into the set.
1854 //Assert if there is an operand of another type that we need to save
1855 const MachineInstr *inst = I->first->getInst();
Tanya Lattner420025b2004-10-10 22:44:35 +00001856 lastInstrs[inst] = I->second;
1857
Tanya Lattner4cffb582004-05-26 06:27:18 +00001858 for(unsigned i=0; i < inst->getNumOperands(); ++i) {
1859 //get machine operand
1860 const MachineOperand &mOp = inst->getOperand(i);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001861
Tanya Lattner4cffb582004-05-26 06:27:18 +00001862 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse()) {
1863 //find the value in the map
Tanya Lattner420025b2004-10-10 22:44:35 +00001864 if (const Value* srcI = mOp.getVRegValue()) {
1865
Tanya Lattnerced82222004-11-16 21:31:37 +00001866 if(isa<Constant>(srcI) || isa<Argument>(srcI) || isa<PHINode>(srcI))
Tanya Lattner80f08552004-11-02 21:04:56 +00001867 continue;
1868
Tanya Lattner420025b2004-10-10 22:44:35 +00001869 //Before we declare this Value* one that we should save
1870 //make sure its def is not of the same stage as this instruction
1871 //because it will be consumed before its used
1872 Instruction *defInst = (Instruction*) srcI;
1873
1874 //Should we save this value?
1875 bool save = true;
1876
Tanya Lattnerced82222004-11-16 21:31:37 +00001877 //Continue if not in the def map, loop invariant code does not need to be saved
1878 if(!defMap.count(srcI))
1879 continue;
1880
Tanya Lattner80f08552004-11-02 21:04:56 +00001881 MachineInstr *defInstr = defMap[srcI];
1882
Tanya Lattnerced82222004-11-16 21:31:37 +00001883
Tanya Lattner80f08552004-11-02 21:04:56 +00001884 if(lastInstrs.count(defInstr)) {
Tanya Lattnerced82222004-11-16 21:31:37 +00001885 if(lastInstrs[defInstr] == I->second) {
Tanya Lattner80f08552004-11-02 21:04:56 +00001886 save = false;
Tanya Lattnerced82222004-11-16 21:31:37 +00001887
1888 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001889 }
Tanya Lattner80f08552004-11-02 21:04:56 +00001890
Tanya Lattner420025b2004-10-10 22:44:35 +00001891 if(save)
1892 valuesToSave[srcI] = std::make_pair(I->first, i);
1893 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001894 }
1895
1896 if(mOp.getType() != MachineOperand::MO_VirtualRegister && mOp.isUse()) {
1897 assert("Our assumption is wrong. We have another type of register that needs to be saved\n");
1898 }
1899 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001900 }
1901 }
1902
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001903 //The new loop will consist of one or more prologues, the kernel, and one or more epilogues.
1904
1905 //Map to keep track of old to new values
Tanya Lattner420025b2004-10-10 22:44:35 +00001906 std::map<Value*, std::map<int, Value*> > newValues;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001907
Tanya Lattner420025b2004-10-10 22:44:35 +00001908 //Map to keep track of old to new values in kernel
1909 std::map<Value*, std::map<int, Value*> > kernelPHIs;
1910
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001911 //Another map to keep track of what machine basic blocks these new value*s are in since
1912 //they have no llvm instruction equivalent
1913 std::map<Value*, MachineBasicBlock*> newValLocation;
1914
1915 std::vector<MachineBasicBlock*> prologues;
1916 std::vector<BasicBlock*> llvm_prologues;
1917
1918
1919 //Write prologue
1920 writePrologues(prologues, BB, llvm_prologues, valuesToSave, newValues, newValLocation);
Tanya Lattner420025b2004-10-10 22:44:35 +00001921
1922 //Print out epilogues and prologue
1923 DEBUG(for(std::vector<MachineBasicBlock*>::iterator I = prologues.begin(), E = prologues.end();
1924 I != E; ++I) {
1925 std::cerr << "PROLOGUE\n";
1926 (*I)->print(std::cerr);
1927 });
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001928
1929 BasicBlock *llvmKernelBB = new BasicBlock("Kernel", (Function*) (BB->getBasicBlock()->getParent()));
1930 MachineBasicBlock *machineKernelBB = new MachineBasicBlock(llvmKernelBB);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001931 (((MachineBasicBlock*)BB)->getParent())->getBasicBlockList().push_back(machineKernelBB);
Tanya Lattner420025b2004-10-10 22:44:35 +00001932 writeKernel(llvmKernelBB, machineKernelBB, valuesToSave, newValues, newValLocation, kernelPHIs);
1933
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001934
1935 std::vector<MachineBasicBlock*> epilogues;
1936 std::vector<BasicBlock*> llvm_epilogues;
1937
1938 //Write epilogues
Tanya Lattner420025b2004-10-10 22:44:35 +00001939 writeEpilogues(epilogues, BB, llvm_epilogues, valuesToSave, newValues, newValLocation, kernelPHIs);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001940
1941
1942 const TargetInstrInfo *TMI = target.getInstrInfo();
1943
1944 //Fix up machineBB and llvmBB branches
1945 for(unsigned I = 0; I < prologues.size(); ++I) {
1946
1947 MachineInstr *branch = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +00001948 MachineInstr *branch2 = 0;
1949
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001950 //Find terminator since getFirstTerminator does not work!
1951 for(MachineBasicBlock::reverse_iterator mInst = prologues[I]->rbegin(), mInstEnd = prologues[I]->rend(); mInst != mInstEnd; ++mInst) {
1952 MachineOpCode OC = mInst->getOpcode();
1953 if(TMI->isBranch(OC)) {
Tanya Lattner260652a2004-10-30 00:39:07 +00001954 if(mInst->getOpcode() == V9::BA)
1955 branch2 = &*mInst;
1956 else
1957 branch = &*mInst;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001958 DEBUG(std::cerr << *mInst << "\n");
Tanya Lattner260652a2004-10-30 00:39:07 +00001959 if(branch !=0 && branch2 !=0)
1960 break;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001961 }
1962 }
1963
Tanya Lattner260652a2004-10-30 00:39:07 +00001964 //Update branch1
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001965 for(unsigned opNum = 0; opNum < branch->getNumOperands(); ++opNum) {
1966 MachineOperand &mOp = branch->getOperand(opNum);
1967 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
Tanya Lattner260652a2004-10-30 00:39:07 +00001968 //Check if we are branching to the kernel, if not branch to epilogue
1969 if(mOp.getVRegValue() == BB->getBasicBlock()) {
1970 if(I == prologues.size()-1)
1971 mOp.setValueReg(llvmKernelBB);
1972 else
1973 mOp.setValueReg(llvm_prologues[I+1]);
1974 }
1975 else
1976 mOp.setValueReg(llvm_epilogues[(llvm_epilogues.size()-1-I)]);
1977 }
1978 }
1979
1980 //Update branch1
1981 for(unsigned opNum = 0; opNum < branch2->getNumOperands(); ++opNum) {
1982 MachineOperand &mOp = branch2->getOperand(opNum);
1983 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
1984 //Check if we are branching to the kernel, if not branch to epilogue
1985 if(mOp.getVRegValue() == BB->getBasicBlock()) {
1986 if(I == prologues.size()-1)
1987 mOp.setValueReg(llvmKernelBB);
1988 else
1989 mOp.setValueReg(llvm_prologues[I+1]);
1990 }
1991 else
1992 mOp.setValueReg(llvm_epilogues[(llvm_epilogues.size()-1-I)]);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001993 }
1994 }
1995
1996 //Update llvm basic block with our new branch instr
1997 DEBUG(std::cerr << BB->getBasicBlock()->getTerminator() << "\n");
1998 const BranchInst *branchVal = dyn_cast<BranchInst>(BB->getBasicBlock()->getTerminator());
Tanya Lattnera6457502004-10-14 06:04:28 +00001999 //TmpInstruction *tmp = new TmpInstruction(branchVal->getCondition());
2000
2001 //Add TmpInstruction to original branches MCFI
2002 //MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(branchVal);
2003 //tempMvec.addTemp((Value*) tmp);
2004
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002005 if(I == prologues.size()-1) {
2006 TerminatorInst *newBranch = new BranchInst(llvmKernelBB,
2007 llvm_epilogues[(llvm_epilogues.size()-1-I)],
Tanya Lattnera6457502004-10-14 06:04:28 +00002008 branchVal->getCondition(),
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002009 llvm_prologues[I]);
2010 }
2011 else
2012 TerminatorInst *newBranch = new BranchInst(llvm_prologues[I+1],
2013 llvm_epilogues[(llvm_epilogues.size()-1-I)],
Tanya Lattnera6457502004-10-14 06:04:28 +00002014 branchVal->getCondition(),
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002015 llvm_prologues[I]);
2016
2017 assert(branch != 0 && "There must be a terminator for this machine basic block!\n");
2018
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002019 }
2020
2021 //Fix up kernel machine branches
2022 MachineInstr *branch = 0;
Tanya Lattnera6457502004-10-14 06:04:28 +00002023 MachineInstr *BAbranch = 0;
2024
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002025 for(MachineBasicBlock::reverse_iterator mInst = machineKernelBB->rbegin(), mInstEnd = machineKernelBB->rend(); mInst != mInstEnd; ++mInst) {
2026 MachineOpCode OC = mInst->getOpcode();
2027 if(TMI->isBranch(OC)) {
Tanya Lattnera6457502004-10-14 06:04:28 +00002028 if(mInst->getOpcode() == V9::BA) {
2029 BAbranch = &*mInst;
2030 }
2031 else {
2032 branch = &*mInst;
2033 break;
2034 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002035 }
2036 }
2037
2038 assert(branch != 0 && "There must be a terminator for the kernel machine basic block!\n");
2039
2040 //Update kernel self loop branch
2041 for(unsigned opNum = 0; opNum < branch->getNumOperands(); ++opNum) {
2042 MachineOperand &mOp = branch->getOperand(opNum);
2043
2044 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2045 mOp.setValueReg(llvmKernelBB);
2046 }
2047 }
2048
Tanya Lattnera6457502004-10-14 06:04:28 +00002049 Value *origBAVal = 0;
2050
2051 //Update kernel BA branch
2052 for(unsigned opNum = 0; opNum < BAbranch->getNumOperands(); ++opNum) {
2053 MachineOperand &mOp = BAbranch->getOperand(opNum);
2054 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2055 origBAVal = mOp.getVRegValue();
2056 if(llvm_epilogues.size() > 0)
2057 mOp.setValueReg(llvm_epilogues[0]);
2058
2059 }
2060 }
2061
2062 assert((origBAVal != 0) && "Could not find original branch always value");
2063
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002064 //Update kernelLLVM branches
2065 const BranchInst *branchVal = dyn_cast<BranchInst>(BB->getBasicBlock()->getTerminator());
Tanya Lattnera6457502004-10-14 06:04:28 +00002066 //TmpInstruction *tmp = new TmpInstruction(branchVal->getCondition());
2067
2068 //Add TmpInstruction to original branches MCFI
2069 //MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(branchVal);
2070 //tempMvec.addTemp((Value*) tmp);
2071
Tanya Lattner260652a2004-10-30 00:39:07 +00002072 assert(llvm_epilogues.size() != 0 && "We must have epilogues!");
2073
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002074 TerminatorInst *newBranch = new BranchInst(llvmKernelBB,
2075 llvm_epilogues[0],
Tanya Lattnera6457502004-10-14 06:04:28 +00002076 branchVal->getCondition(),
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002077 llvmKernelBB);
2078
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002079
2080 //Lastly add unconditional branches for the epilogues
2081 for(unsigned I = 0; I < epilogues.size(); ++I) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00002082
Tanya Lattnera6457502004-10-14 06:04:28 +00002083 //Now since we don't have fall throughs, add a unconditional branch to the next prologue
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002084 if(I != epilogues.size()-1) {
Tanya Lattner420025b2004-10-10 22:44:35 +00002085 BuildMI(epilogues[I], V9::BA, 1).addPCDisp(llvm_epilogues[I+1]);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002086 //Add unconditional branch to end of epilogue
2087 TerminatorInst *newBranch = new BranchInst(llvm_epilogues[I+1],
2088 llvm_epilogues[I]);
2089
Tanya Lattner4cffb582004-05-26 06:27:18 +00002090 }
Tanya Lattnera6457502004-10-14 06:04:28 +00002091 else {
2092 BuildMI(epilogues[I], V9::BA, 1).addPCDisp(origBAVal);
2093
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002094
Tanya Lattnera6457502004-10-14 06:04:28 +00002095 //Update last epilogue exit branch
2096 BranchInst *branchVal = (BranchInst*) dyn_cast<BranchInst>(BB->getBasicBlock()->getTerminator());
2097 //Find where we are supposed to branch to
2098 BasicBlock *nextBlock = 0;
2099 for(unsigned j=0; j <branchVal->getNumSuccessors(); ++j) {
2100 if(branchVal->getSuccessor(j) != BB->getBasicBlock())
2101 nextBlock = branchVal->getSuccessor(j);
2102 }
2103
2104 assert((nextBlock != 0) && "Next block should not be null!");
2105 TerminatorInst *newBranch = new BranchInst(nextBlock, llvm_epilogues[I]);
2106 }
2107 //Add one more nop!
2108 BuildMI(epilogues[I], V9::NOP, 0);
2109
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002110 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00002111
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002112 //FIX UP Machine BB entry!!
2113 //We are looking at the predecesor of our loop basic block and we want to change its ba instruction
2114
Tanya Lattner4cffb582004-05-26 06:27:18 +00002115
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002116 //Find all llvm basic blocks that branch to the loop entry and change to our first prologue.
2117 const BasicBlock *llvmBB = BB->getBasicBlock();
2118
Tanya Lattner260652a2004-10-30 00:39:07 +00002119 std::vector<const BasicBlock*>Preds (pred_begin(llvmBB), pred_end(llvmBB));
2120
2121 //for(pred_const_iterator P = pred_begin(llvmBB), PE = pred_end(llvmBB); P != PE; ++PE) {
2122 for(std::vector<const BasicBlock*>::iterator P = Preds.begin(), PE = Preds.end(); P != PE; ++P) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002123 if(*P == llvmBB)
2124 continue;
2125 else {
2126 DEBUG(std::cerr << "Found our entry BB\n");
2127 //Get the Terminator instruction for this basic block and print it out
2128 DEBUG(std::cerr << *((*P)->getTerminator()) << "\n");
2129 //Update the terminator
2130 TerminatorInst *term = ((BasicBlock*)*P)->getTerminator();
2131 for(unsigned i=0; i < term->getNumSuccessors(); ++i) {
2132 if(term->getSuccessor(i) == llvmBB) {
2133 DEBUG(std::cerr << "Replacing successor bb\n");
2134 if(llvm_prologues.size() > 0) {
2135 term->setSuccessor(i, llvm_prologues[0]);
2136 //Also update its corresponding machine instruction
2137 MachineCodeForInstruction & tempMvec =
2138 MachineCodeForInstruction::get(term);
2139 for (unsigned j = 0; j < tempMvec.size(); j++) {
2140 MachineInstr *temp = tempMvec[j];
2141 MachineOpCode opc = temp->getOpcode();
2142 if(TMI->isBranch(opc)) {
2143 DEBUG(std::cerr << *temp << "\n");
2144 //Update branch
2145 for(unsigned opNum = 0; opNum < temp->getNumOperands(); ++opNum) {
2146 MachineOperand &mOp = temp->getOperand(opNum);
2147 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2148 mOp.setValueReg(llvm_prologues[0]);
2149 }
2150 }
2151 }
2152 }
2153 }
2154 else {
2155 term->setSuccessor(i, llvmKernelBB);
2156 //Also update its corresponding machine instruction
2157 MachineCodeForInstruction & tempMvec =
2158 MachineCodeForInstruction::get(term);
2159 for (unsigned j = 0; j < tempMvec.size(); j++) {
2160 MachineInstr *temp = tempMvec[j];
2161 MachineOpCode opc = temp->getOpcode();
2162 if(TMI->isBranch(opc)) {
2163 DEBUG(std::cerr << *temp << "\n");
2164 //Update branch
2165 for(unsigned opNum = 0; opNum < temp->getNumOperands(); ++opNum) {
2166 MachineOperand &mOp = temp->getOperand(opNum);
2167 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2168 mOp.setValueReg(llvmKernelBB);
2169 }
2170 }
2171 }
2172 }
2173 }
2174 }
2175 }
2176 break;
2177 }
2178 }
2179
2180 removePHIs(BB, prologues, epilogues, machineKernelBB, newValLocation);
Tanya Lattner4cffb582004-05-26 06:27:18 +00002181
2182
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002183
2184 //Print out epilogues and prologue
2185 DEBUG(for(std::vector<MachineBasicBlock*>::iterator I = prologues.begin(), E = prologues.end();
2186 I != E; ++I) {
2187 std::cerr << "PROLOGUE\n";
2188 (*I)->print(std::cerr);
2189 });
2190
2191 DEBUG(std::cerr << "KERNEL\n");
2192 DEBUG(machineKernelBB->print(std::cerr));
2193
2194 DEBUG(for(std::vector<MachineBasicBlock*>::iterator I = epilogues.begin(), E = epilogues.end();
2195 I != E; ++I) {
2196 std::cerr << "EPILOGUE\n";
2197 (*I)->print(std::cerr);
2198 });
2199
2200
2201 DEBUG(std::cerr << "New Machine Function" << "\n");
2202 DEBUG(std::cerr << BB->getParent() << "\n");
2203
Tanya Lattner420025b2004-10-10 22:44:35 +00002204 //BB->getParent()->getBasicBlockList().erase(BB);
Tanya Lattner4cffb582004-05-26 06:27:18 +00002205
2206}
2207