blob: 985743d8e8b36da94e18f6e9d50e6f94600ee2ac [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"
Tanya Lattnerdb40cf12005-02-10 17:02:58 +000026#include "llvm/ADT/SCCIterator.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000027#include "llvm/ADT/StringExtras.h"
Tanya Lattnere1df2122004-11-22 20:41:24 +000028#include "llvm/ADT/Statistic.h"
Tanya Lattnerdb40cf12005-02-10 17:02:58 +000029#include "llvm/Support/Timer.h"
Misha Brukman82fd8d82004-08-02 13:59:10 +000030#include <cmath>
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +000031#include <algorithm>
Tanya Lattnerd14b8372004-03-01 02:50:01 +000032#include <fstream>
33#include <sstream>
Misha Brukman82fd8d82004-08-02 13:59:10 +000034#include <utility>
35#include <vector>
Misha Brukman7da1e6e2004-10-10 23:34:50 +000036#include "../MachineCodeForInstruction.h"
37#include "../SparcV9TmpInstr.h"
38#include "../SparcV9Internals.h"
39#include "../SparcV9RegisterInfo.h"
Tanya Lattnerd14b8372004-03-01 02:50:01 +000040using namespace llvm;
41
42/// Create ModuloSchedulingPass
43///
44FunctionPass *llvm::createModuloSchedulingPass(TargetMachine & targ) {
45 DEBUG(std::cerr << "Created ModuloSchedulingPass\n");
46 return new ModuloSchedulingPass(targ);
47}
48
Tanya Lattner0a88d2d2004-07-30 23:36:10 +000049
50//Graph Traits for printing out the dependence graph
Tanya Lattnerd14b8372004-03-01 02:50:01 +000051template<typename GraphType>
52static void WriteGraphToFile(std::ostream &O, const std::string &GraphName,
53 const GraphType &GT) {
54 std::string Filename = GraphName + ".dot";
55 O << "Writing '" << Filename << "'...";
56 std::ofstream F(Filename.c_str());
57
58 if (F.good())
59 WriteGraph(F, GT);
60 else
61 O << " error opening file for writing!";
62 O << "\n";
63};
Guochun Shif1c154f2003-03-27 17:57:44 +000064
Tanya Lattnerdb40cf12005-02-10 17:02:58 +000065
66#if 1
67#define TIME_REGION(VARNAME, DESC) \
68 NamedRegionTimer VARNAME(DESC)
69#else
70#define TIME_REGION(VARNAME, DESC)
71#endif
72
73
Tanya Lattner0a88d2d2004-07-30 23:36:10 +000074//Graph Traits for printing out the dependence graph
Brian Gaeked0fde302003-11-11 22:41:34 +000075namespace llvm {
Tanya Lattnere1df2122004-11-22 20:41:24 +000076 Statistic<> ValidLoops("modulosched-validLoops", "Number of candidate loops modulo-scheduled");
77 Statistic<> MSLoops("modulosched-schedLoops", "Number of loops successfully modulo-scheduled");
78 Statistic<> IncreasedII("modulosched-increasedII", "Number of times we had to increase II");
Tanya Lattnerdb40cf12005-02-10 17:02:58 +000079 Statistic<> SingleBBLoops("modulosched-singeBBLoops", "Number of single basic block loops");
Tanya Lattnerdb1680b2005-02-16 04:00:59 +000080 Statistic<> NoSched("modulosched-noSched", "No schedule");
81 Statistic<> SameStage("modulosched-sameStage", "Max stage is 0");
Brian Gaeked0fde302003-11-11 22:41:34 +000082
Tanya Lattnerd14b8372004-03-01 02:50:01 +000083 template<>
84 struct DOTGraphTraits<MSchedGraph*> : public DefaultDOTGraphTraits {
85 static std::string getGraphName(MSchedGraph *F) {
86 return "Dependence Graph";
87 }
Guochun Shi8f1d4ab2003-06-08 23:16:07 +000088
Tanya Lattnerd14b8372004-03-01 02:50:01 +000089 static std::string getNodeLabel(MSchedGraphNode *Node, MSchedGraph *Graph) {
90 if (Node->getInst()) {
91 std::stringstream ss;
92 ss << *(Node->getInst());
93 return ss.str(); //((MachineInstr*)Node->getInst());
94 }
95 else
96 return "No Inst";
97 }
98 static std::string getEdgeSourceLabel(MSchedGraphNode *Node,
99 MSchedGraphNode::succ_iterator I) {
100 //Label each edge with the type of dependence
101 std::string edgelabel = "";
102 switch (I.getEdge().getDepOrderType()) {
103
104 case MSchedGraphEdge::TrueDep:
105 edgelabel = "True";
106 break;
107
108 case MSchedGraphEdge::AntiDep:
109 edgelabel = "Anti";
110 break;
111
112 case MSchedGraphEdge::OutputDep:
113 edgelabel = "Output";
114 break;
115
116 default:
117 edgelabel = "Unknown";
118 break;
119 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000120
121 //FIXME
122 int iteDiff = I.getEdge().getIteDiff();
123 std::string intStr = "(IteDiff: ";
124 intStr += itostr(iteDiff);
125
126 intStr += ")";
127 edgelabel += intStr;
128
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000129 return edgelabel;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000130 }
Guochun Shif1c154f2003-03-27 17:57:44 +0000131 };
Guochun Shif1c154f2003-03-27 17:57:44 +0000132}
Tanya Lattner4f839cc2003-08-28 17:12:14 +0000133
Misha Brukmanaa41c3c2003-10-10 17:41:32 +0000134/// ModuloScheduling::runOnFunction - main transformation entry point
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000135/// The Swing Modulo Schedule algorithm has three basic steps:
136/// 1) Computation and Analysis of the dependence graph
137/// 2) Ordering of the nodes
138/// 3) Scheduling
139///
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000140bool ModuloSchedulingPass::runOnFunction(Function &F) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000141
Tanya Lattner4f839cc2003-08-28 17:12:14 +0000142 bool Changed = false;
Tanya Lattnerced82222004-11-16 21:31:37 +0000143 int numMS = 0;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000144
Tanya Lattner420025b2004-10-10 22:44:35 +0000145 DEBUG(std::cerr << "Creating ModuloSchedGraph for each valid BasicBlock in " + F.getName() + "\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000146
147 //Get MachineFunction
148 MachineFunction &MF = MachineFunction::get(&F);
Tanya Lattner260652a2004-10-30 00:39:07 +0000149
150
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000151 //Worklist
152 std::vector<MachineBasicBlock*> Worklist;
153
154 //Iterate over BasicBlocks and put them into our worklist if they are valid
155 for (MachineFunction::iterator BI = MF.begin(); BI != MF.end(); ++BI)
Tanya Lattnere1df2122004-11-22 20:41:24 +0000156 if(MachineBBisValid(BI)) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000157 Worklist.push_back(&*BI);
Tanya Lattnere1df2122004-11-22 20:41:24 +0000158 ++ValidLoops;
159 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000160
Tanya Lattner80f08552004-11-02 21:04:56 +0000161 defaultInst = 0;
162
Tanya Lattner420025b2004-10-10 22:44:35 +0000163 DEBUG(if(Worklist.size() == 0) std::cerr << "No single basic block loops in function to ModuloSchedule\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000164
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000165 //Iterate over the worklist and perform scheduling
166 for(std::vector<MachineBasicBlock*>::iterator BI = Worklist.begin(),
167 BE = Worklist.end(); BI != BE; ++BI) {
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000168
169 //Print out BB for debugging
170 DEBUG(std::cerr << "ModuloScheduling BB: \n"; (*BI)->print(std::cerr));
171
172 //Catch the odd case where we only have TmpInstructions and no real Value*s
173 if(!CreateDefMap(*BI)) {
174 //Clear out our maps for the next basic block that is processed
175 nodeToAttributesMap.clear();
176 partialOrder.clear();
177 recurrenceList.clear();
178 FinalNodeOrder.clear();
179 schedule.clear();
180 defMap.clear();
181 continue;
182 }
Tanya Lattnerced82222004-11-16 21:31:37 +0000183
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000184 MSchedGraph *MSG = new MSchedGraph(*BI, target);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000185
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000186 //Write Graph out to file
187 DEBUG(WriteGraphToFile(std::cerr, F.getName(), MSG));
188
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000189 //Calculate Resource II
190 int ResMII = calculateResMII(*BI);
191
192 //Calculate Recurrence II
193 int RecMII = calculateRecMII(MSG, ResMII);
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000194
195 DEBUG(std::cerr << "Number of reccurrences found: " << recurrenceList.size() << "\n");
196
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000197
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000198
199
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000200 //Our starting initiation interval is the maximum of RecMII and ResMII
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000201 II = std::max(RecMII, ResMII);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000202
203 //Print out II, RecMII, and ResMII
Tanya Lattner260652a2004-10-30 00:39:07 +0000204 DEBUG(std::cerr << "II starts out as " << II << " ( RecMII=" << RecMII << " and ResMII=" << ResMII << ")\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000205
Tanya Lattner260652a2004-10-30 00:39:07 +0000206 //Dump node properties if in debug mode
207 DEBUG(for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(),
208 E = nodeToAttributesMap.end(); I !=E; ++I) {
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000209 std::cerr << "Node: " << *(I->first) << " ASAP: " << I->second.ASAP << " ALAP: "
210 << I->second.ALAP << " MOB: " << I->second.MOB << " Depth: " << I->second.depth
211 << " Height: " << I->second.height << "\n";
212 });
Tanya Lattner260652a2004-10-30 00:39:07 +0000213
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000214 //Calculate Node Properties
215 calculateNodeAttributes(MSG, ResMII);
216
217 //Dump node properties if in debug mode
218 DEBUG(for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(),
219 E = nodeToAttributesMap.end(); I !=E; ++I) {
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000220 std::cerr << "Node: " << *(I->first) << " ASAP: " << I->second.ASAP << " ALAP: "
221 << I->second.ALAP << " MOB: " << I->second.MOB << " Depth: " << I->second.depth
222 << " Height: " << I->second.height << "\n";
223 });
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000224
225 //Put nodes in order to schedule them
226 computePartialOrder();
227
228 //Dump out partial order
Tanya Lattner260652a2004-10-30 00:39:07 +0000229 DEBUG(for(std::vector<std::set<MSchedGraphNode*> >::iterator I = partialOrder.begin(),
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000230 E = partialOrder.end(); I !=E; ++I) {
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000231 std::cerr << "Start set in PO\n";
232 for(std::set<MSchedGraphNode*>::iterator J = I->begin(), JE = I->end(); J != JE; ++J)
233 std::cerr << "PO:" << **J << "\n";
234 });
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000235
236 //Place nodes in final order
237 orderNodes();
238
239 //Dump out order of nodes
240 DEBUG(for(std::vector<MSchedGraphNode*>::iterator I = FinalNodeOrder.begin(), E = FinalNodeOrder.end(); I != E; ++I) {
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000241 std::cerr << "FO:" << **I << "\n";
242 });
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000243
244 //Finally schedule nodes
Tanya Lattnerad7654f2004-12-02 07:22:15 +0000245 bool haveSched = computeSchedule();
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000246
247 //Print out final schedule
248 DEBUG(schedule.print(std::cerr));
249
Tanya Lattner260652a2004-10-30 00:39:07 +0000250 //Final scheduling step is to reconstruct the loop only if we actual have
251 //stage > 0
Tanya Lattnerad7654f2004-12-02 07:22:15 +0000252 if(schedule.getMaxStage() != 0 && haveSched) {
Tanya Lattner260652a2004-10-30 00:39:07 +0000253 reconstructLoop(*BI);
Tanya Lattnere1df2122004-11-22 20:41:24 +0000254 ++MSLoops;
Tanya Lattnerced82222004-11-16 21:31:37 +0000255 Changed = true;
256 }
Tanya Lattnerdb1680b2005-02-16 04:00:59 +0000257 else {
258 if(!haveSched)
259 ++NoSched;
260 else
261 ++SameStage;
Tanya Lattnerad7654f2004-12-02 07:22:15 +0000262 DEBUG(std::cerr << "Max stage is 0, so no change in loop or reached cap\n");
Tanya Lattnerdb1680b2005-02-16 04:00:59 +0000263 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000264 //Clear out our maps for the next basic block that is processed
265 nodeToAttributesMap.clear();
266 partialOrder.clear();
267 recurrenceList.clear();
268 FinalNodeOrder.clear();
269 schedule.clear();
Tanya Lattnerced82222004-11-16 21:31:37 +0000270 defMap.clear();
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000271 //Clean up. Nuke old MachineBB and llvmBB
272 //BasicBlock *llvmBB = (BasicBlock*) (*BI)->getBasicBlock();
273 //Function *parent = (Function*) llvmBB->getParent();
274 //Should't std::find work??
275 //parent->getBasicBlockList().erase(std::find(parent->getBasicBlockList().begin(), parent->getBasicBlockList().end(), *llvmBB));
276 //parent->getBasicBlockList().erase(llvmBB);
277
278 //delete(llvmBB);
279 //delete(*BI);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000280 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000281
Tanya Lattner4f839cc2003-08-28 17:12:14 +0000282 return Changed;
283}
Brian Gaeked0fde302003-11-11 22:41:34 +0000284
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000285bool ModuloSchedulingPass::CreateDefMap(MachineBasicBlock *BI) {
Tanya Lattnerced82222004-11-16 21:31:37 +0000286 defaultInst = 0;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000287
Tanya Lattnerced82222004-11-16 21:31:37 +0000288 for(MachineBasicBlock::iterator I = BI->begin(), E = BI->end(); I != E; ++I) {
289 for(unsigned opNum = 0; opNum < I->getNumOperands(); ++opNum) {
290 const MachineOperand &mOp = I->getOperand(opNum);
291 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef()) {
Tanya Lattnere1df2122004-11-22 20:41:24 +0000292 //assert if this is the second def we have seen
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000293 //DEBUG(std::cerr << "Putting " << *(mOp.getVRegValue()) << " into map\n");
Tanya Lattnere1df2122004-11-22 20:41:24 +0000294 assert(!defMap.count(mOp.getVRegValue()) && "Def already in the map");
295
Tanya Lattnerced82222004-11-16 21:31:37 +0000296 defMap[mOp.getVRegValue()] = &*I;
297 }
298
299 //See if we can use this Value* as our defaultInst
300 if(!defaultInst && mOp.getType() == MachineOperand::MO_VirtualRegister) {
301 Value *V = mOp.getVRegValue();
302 if(!isa<TmpInstruction>(V) && !isa<Argument>(V) && !isa<Constant>(V) && !isa<PHINode>(V))
303 defaultInst = (Instruction*) V;
304 }
305 }
306 }
Tanya Lattnere1df2122004-11-22 20:41:24 +0000307
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000308 if(!defaultInst)
309 return false;
310
311 return true;
Tanya Lattnerced82222004-11-16 21:31:37 +0000312
313}
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000314/// This function checks if a Machine Basic Block is valid for modulo
315/// scheduling. This means that it has no control flow (if/else or
316/// calls) in the block. Currently ModuloScheduling only works on
317/// single basic block loops.
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000318bool ModuloSchedulingPass::MachineBBisValid(const MachineBasicBlock *BI) {
319
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000320 bool isLoop = false;
321
322 //Check first if its a valid loop
323 for(succ_const_iterator I = succ_begin(BI->getBasicBlock()),
324 E = succ_end(BI->getBasicBlock()); I != E; ++I) {
325 if (*I == BI->getBasicBlock()) // has single block loop
326 isLoop = true;
327 }
328
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000329 if(!isLoop)
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000330 return false;
Tanya Lattnerad7654f2004-12-02 07:22:15 +0000331
332 //Check that we have a conditional branch (avoiding MS infinite loops)
333 if(BranchInst *b = dyn_cast<BranchInst>(((BasicBlock*) BI->getBasicBlock())->getTerminator()))
334 if(b->isUnconditional())
335 return false;
336
Tanya Lattnere1df2122004-11-22 20:41:24 +0000337 //Check size of our basic block.. make sure we have more then just the terminator in it
338 if(BI->getBasicBlock()->size() == 1)
339 return false;
340
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000341
342 //Increase number of single basic block loops for stats
343 ++SingleBBLoops;
344
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000345 //Get Target machine instruction info
346 const TargetInstrInfo *TMI = target.getInstrInfo();
347
348 //Check each instruction and look for calls
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000349 for(MachineBasicBlock::const_iterator I = BI->begin(), E = BI->end(); I != E; ++I) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000350 //Get opcode to check instruction type
351 MachineOpCode OC = I->getOpcode();
352 if(TMI->isCall(OC))
353 return false;
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000354 //Look for conditional move
355 if(OC == V9::MOVRZr || OC == V9::MOVRZi || OC == V9::MOVRLEZr || OC == V9::MOVRLEZi
356 || OC == V9::MOVRLZr || OC == V9::MOVRLZi || OC == V9::MOVRNZr || OC == V9::MOVRNZi
357 || OC == V9::MOVRGZr || OC == V9::MOVRGZi || OC == V9::MOVRGEZr
358 || OC == V9::MOVRGEZi || OC == V9::MOVLEr || OC == V9::MOVLEi || OC == V9::MOVLEUr
359 || OC == V9::MOVLEUi || OC == V9::MOVFLEr || OC == V9::MOVFLEi
360 || OC == V9::MOVNEr || OC == V9::MOVNEi || OC == V9::MOVNEGr || OC == V9::MOVNEGi
361 || OC == V9::MOVFNEr || OC == V9::MOVFNEi)
362 return false;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000363 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000364 return true;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000365}
366
367//ResMII is calculated by determining the usage count for each resource
368//and using the maximum.
369//FIXME: In future there should be a way to get alternative resources
370//for each instruction
371int ModuloSchedulingPass::calculateResMII(const MachineBasicBlock *BI) {
372
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000373 TIME_REGION(X, "calculateResMII");
374
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000375 const TargetInstrInfo *mii = target.getInstrInfo();
376 const TargetSchedInfo *msi = target.getSchedInfo();
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000377
378 int ResMII = 0;
379
380 //Map to keep track of usage count of each resource
381 std::map<unsigned, unsigned> resourceUsageCount;
382
383 for(MachineBasicBlock::const_iterator I = BI->begin(), E = BI->end(); I != E; ++I) {
384
385 //Get resource usage for this instruction
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000386 InstrRUsage rUsage = msi->getInstrRUsage(I->getOpcode());
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000387 std::vector<std::vector<resourceId_t> > resources = rUsage.resourcesByCycle;
388
389 //Loop over resources in each cycle and increments their usage count
390 for(unsigned i=0; i < resources.size(); ++i)
391 for(unsigned j=0; j < resources[i].size(); ++j) {
392 if( resourceUsageCount.find(resources[i][j]) == resourceUsageCount.end()) {
393 resourceUsageCount[resources[i][j]] = 1;
394 }
395 else {
396 resourceUsageCount[resources[i][j]] = resourceUsageCount[resources[i][j]] + 1;
397 }
398 }
399 }
400
401 //Find maximum usage count
402
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000403 //Get max number of instructions that can be issued at once. (FIXME)
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000404 int issueSlots = msi->maxNumIssueTotal;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000405
406 for(std::map<unsigned,unsigned>::iterator RB = resourceUsageCount.begin(), RE = resourceUsageCount.end(); RB != RE; ++RB) {
Tanya Lattner4cffb582004-05-26 06:27:18 +0000407
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000408 //Get the total number of the resources in our cpu
Tanya Lattner4cffb582004-05-26 06:27:18 +0000409 int resourceNum = CPUResource::getCPUResource(RB->first)->maxNumUsers;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000410
411 //Get total usage count for this resources
412 unsigned usageCount = RB->second;
413
414 //Divide the usage count by either the max number we can issue or the number of
415 //resources (whichever is its upper bound)
416 double finalUsageCount;
Tanya Lattner4cffb582004-05-26 06:27:18 +0000417 if( resourceNum <= issueSlots)
418 finalUsageCount = ceil(1.0 * usageCount / resourceNum);
419 else
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000420 finalUsageCount = ceil(1.0 * usageCount / issueSlots);
421
422
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000423 //Only keep track of the max
424 ResMII = std::max( (int) finalUsageCount, ResMII);
425
426 }
427
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000428 return ResMII;
429
430}
431
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000432/// calculateRecMII - Calculates the value of the highest recurrence
433/// By value we mean the total latency
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000434int ModuloSchedulingPass::calculateRecMII(MSchedGraph *graph, int MII) {
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000435 /*std::vector<MSchedGraphNode*> vNodes;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000436 //Loop over all nodes in the graph
437 for(MSchedGraph::iterator I = graph->begin(), E = graph->end(); I != E; ++I) {
438 findAllReccurrences(I->second, vNodes, MII);
439 vNodes.clear();
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000440 }*/
441
442 TIME_REGION(X, "calculateRecMII");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000443
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000444 findAllCircuits(graph, MII);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000445 int RecMII = 0;
446
447 for(std::set<std::pair<int, std::vector<MSchedGraphNode*> > >::iterator I = recurrenceList.begin(), E=recurrenceList.end(); I !=E; ++I) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000448 RecMII = std::max(RecMII, I->first);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000449 }
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000450
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000451 return MII;
452}
453
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000454/// calculateNodeAttributes - The following properties are calculated for
455/// each node in the dependence graph: ASAP, ALAP, Depth, Height, and
456/// MOB.
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000457void ModuloSchedulingPass::calculateNodeAttributes(MSchedGraph *graph, int MII) {
458
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000459 TIME_REGION(X, "calculateNodeAttributes");
460
Tanya Lattner260652a2004-10-30 00:39:07 +0000461 assert(nodeToAttributesMap.empty() && "Node attribute map was not cleared");
462
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000463 //Loop over the nodes and add them to the map
464 for(MSchedGraph::iterator I = graph->begin(), E = graph->end(); I != E; ++I) {
Tanya Lattner260652a2004-10-30 00:39:07 +0000465
466 DEBUG(std::cerr << "Inserting node into attribute map: " << *I->second << "\n");
467
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000468 //Assert if its already in the map
Tanya Lattner260652a2004-10-30 00:39:07 +0000469 assert(nodeToAttributesMap.count(I->second) == 0 &&
470 "Node attributes are already in the map");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000471
472 //Put into the map with default attribute values
473 nodeToAttributesMap[I->second] = MSNodeAttributes();
474 }
475
476 //Create set to deal with reccurrences
477 std::set<MSchedGraphNode*> visitedNodes;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000478
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000479 //Now Loop over map and calculate the node attributes
480 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000481 calculateASAP(I->first, MII, (MSchedGraphNode*) 0);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000482 visitedNodes.clear();
483 }
484
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000485 int maxASAP = findMaxASAP();
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000486 //Calculate ALAP which depends on ASAP being totally calculated
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000487 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
488 calculateALAP(I->first, MII, maxASAP, (MSchedGraphNode*) 0);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000489 visitedNodes.clear();
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000490 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000491
492 //Calculate MOB which depends on ASAP being totally calculated, also do depth and height
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000493 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
494 (I->second).MOB = std::max(0,(I->second).ALAP - (I->second).ASAP);
495
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000496 DEBUG(std::cerr << "MOB: " << (I->second).MOB << " (" << *(I->first) << ")\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000497 calculateDepth(I->first, (MSchedGraphNode*) 0);
498 calculateHeight(I->first, (MSchedGraphNode*) 0);
499 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000500
501
502}
503
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000504/// ignoreEdge - Checks to see if this edge of a recurrence should be ignored or not
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000505bool ModuloSchedulingPass::ignoreEdge(MSchedGraphNode *srcNode, MSchedGraphNode *destNode) {
506 if(destNode == 0 || srcNode ==0)
507 return false;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000508
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000509 bool findEdge = edgesToIgnore.count(std::make_pair(srcNode, destNode->getInEdgeNum(srcNode)));
Tanya Lattner4cffb582004-05-26 06:27:18 +0000510
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000511 return findEdge;
512}
513
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000514
515/// calculateASAP - Calculates the
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000516int ModuloSchedulingPass::calculateASAP(MSchedGraphNode *node, int MII, MSchedGraphNode *destNode) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000517
518 DEBUG(std::cerr << "Calculating ASAP for " << *node << "\n");
519
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000520 //Get current node attributes
521 MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
522
523 if(attributes.ASAP != -1)
524 return attributes.ASAP;
525
526 int maxPredValue = 0;
527
528 //Iterate over all of the predecessors and find max
529 for(MSchedGraphNode::pred_iterator P = node->pred_begin(), E = node->pred_end(); P != E; ++P) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000530
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000531 //Only process if we are not ignoring the edge
532 if(!ignoreEdge(*P, node)) {
533 int predASAP = -1;
534 predASAP = calculateASAP(*P, MII, node);
535
536 assert(predASAP != -1 && "ASAP has not been calculated");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000537 int iteDiff = node->getInEdge(*P).getIteDiff();
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000538
539 int currentPredValue = predASAP + (*P)->getLatency() - (iteDiff * MII);
540 DEBUG(std::cerr << "pred ASAP: " << predASAP << ", iteDiff: " << iteDiff << ", PredLatency: " << (*P)->getLatency() << ", Current ASAP pred: " << currentPredValue << "\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000541 maxPredValue = std::max(maxPredValue, currentPredValue);
542 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000543 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000544
545 attributes.ASAP = maxPredValue;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000546
547 DEBUG(std::cerr << "ASAP: " << attributes.ASAP << " (" << *node << ")\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000548
549 return maxPredValue;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000550}
551
552
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000553int ModuloSchedulingPass::calculateALAP(MSchedGraphNode *node, int MII,
554 int maxASAP, MSchedGraphNode *srcNode) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000555
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000556 DEBUG(std::cerr << "Calculating ALAP for " << *node << "\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000557
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000558 MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
559
560 if(attributes.ALAP != -1)
561 return attributes.ALAP;
562
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000563 if(node->hasSuccessors()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000564
565 //Trying to deal with the issue where the node has successors, but
566 //we are ignoring all of the edges to them. So this is my hack for
567 //now.. there is probably a more elegant way of doing this (FIXME)
568 bool processedOneEdge = false;
569
570 //FIXME, set to something high to start
571 int minSuccValue = 9999999;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000572
573 //Iterate over all of the predecessors and fine max
574 for(MSchedGraphNode::succ_iterator P = node->succ_begin(),
575 E = node->succ_end(); P != E; ++P) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000576
577 //Only process if we are not ignoring the edge
578 if(!ignoreEdge(node, *P)) {
579 processedOneEdge = true;
580 int succALAP = -1;
581 succALAP = calculateALAP(*P, MII, maxASAP, node);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000582
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000583 assert(succALAP != -1 && "Successors ALAP should have been caclulated");
584
585 int iteDiff = P.getEdge().getIteDiff();
586
587 int currentSuccValue = succALAP - node->getLatency() + iteDiff * MII;
588
589 DEBUG(std::cerr << "succ ALAP: " << succALAP << ", iteDiff: " << iteDiff << ", SuccLatency: " << (*P)->getLatency() << ", Current ALAP succ: " << currentSuccValue << "\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000590
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000591 minSuccValue = std::min(minSuccValue, currentSuccValue);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000592 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000593 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000594
595 if(processedOneEdge)
596 attributes.ALAP = minSuccValue;
597
598 else
599 attributes.ALAP = maxASAP;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000600 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000601 else
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000602 attributes.ALAP = maxASAP;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000603
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000604 DEBUG(std::cerr << "ALAP: " << attributes.ALAP << " (" << *node << ")\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000605
606 if(attributes.ALAP < 0)
607 attributes.ALAP = 0;
608
609 return attributes.ALAP;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000610}
611
612int ModuloSchedulingPass::findMaxASAP() {
613 int maxASAP = 0;
614
615 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(),
616 E = nodeToAttributesMap.end(); I != E; ++I)
617 maxASAP = std::max(maxASAP, I->second.ASAP);
618 return maxASAP;
619}
620
621
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000622int ModuloSchedulingPass::calculateHeight(MSchedGraphNode *node,MSchedGraphNode *srcNode) {
623
624 MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000625
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000626 if(attributes.height != -1)
627 return attributes.height;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000628
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000629 int maxHeight = 0;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000630
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000631 //Iterate over all of the predecessors and find max
632 for(MSchedGraphNode::succ_iterator P = node->succ_begin(),
633 E = node->succ_end(); P != E; ++P) {
634
635
636 if(!ignoreEdge(node, *P)) {
637 int succHeight = calculateHeight(*P, node);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000638
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000639 assert(succHeight != -1 && "Successors Height should have been caclulated");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000640
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000641 int currentHeight = succHeight + node->getLatency();
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000642 maxHeight = std::max(maxHeight, currentHeight);
643 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000644 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000645 attributes.height = maxHeight;
646 DEBUG(std::cerr << "Height: " << attributes.height << " (" << *node << ")\n");
647 return maxHeight;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000648}
649
650
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000651int ModuloSchedulingPass::calculateDepth(MSchedGraphNode *node,
652 MSchedGraphNode *destNode) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000653
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000654 MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000655
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000656 if(attributes.depth != -1)
657 return attributes.depth;
658
659 int maxDepth = 0;
660
661 //Iterate over all of the predecessors and fine max
662 for(MSchedGraphNode::pred_iterator P = node->pred_begin(), E = node->pred_end(); P != E; ++P) {
663
664 if(!ignoreEdge(*P, node)) {
665 int predDepth = -1;
666 predDepth = calculateDepth(*P, node);
667
668 assert(predDepth != -1 && "Predecessors ASAP should have been caclulated");
669
670 int currentDepth = predDepth + (*P)->getLatency();
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000671 maxDepth = std::max(maxDepth, currentDepth);
672 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000673 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000674 attributes.depth = maxDepth;
675
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000676 DEBUG(std::cerr << "Depth: " << attributes.depth << " (" << *node << "*)\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000677 return maxDepth;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000678}
679
680
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000681
682void ModuloSchedulingPass::addReccurrence(std::vector<MSchedGraphNode*> &recurrence, int II, MSchedGraphNode *srcBENode, MSchedGraphNode *destBENode) {
683 //Check to make sure that this recurrence is unique
684 bool same = false;
685
686
687 //Loop over all recurrences already in our list
688 for(std::set<std::pair<int, std::vector<MSchedGraphNode*> > >::iterator R = recurrenceList.begin(), RE = recurrenceList.end(); R != RE; ++R) {
689
690 bool all_same = true;
691 //First compare size
692 if(R->second.size() == recurrence.size()) {
693
694 for(std::vector<MSchedGraphNode*>::const_iterator node = R->second.begin(), end = R->second.end(); node != end; ++node) {
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000695 if(std::find(recurrence.begin(), recurrence.end(), *node) == recurrence.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000696 all_same = all_same && false;
697 break;
698 }
699 else
700 all_same = all_same && true;
701 }
702 if(all_same) {
703 same = true;
704 break;
705 }
706 }
707 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000708
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000709 if(!same) {
Tanya Lattner4cffb582004-05-26 06:27:18 +0000710 srcBENode = recurrence.back();
711 destBENode = recurrence.front();
712
713 //FIXME
714 if(destBENode->getInEdge(srcBENode).getIteDiff() == 0) {
715 //DEBUG(std::cerr << "NOT A BACKEDGE\n");
716 //find actual backedge HACK HACK
717 for(unsigned i=0; i< recurrence.size()-1; ++i) {
718 if(recurrence[i+1]->getInEdge(recurrence[i]).getIteDiff() == 1) {
719 srcBENode = recurrence[i];
720 destBENode = recurrence[i+1];
721 break;
722 }
723
724 }
725
726 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000727 DEBUG(std::cerr << "Back Edge to Remove: " << *srcBENode << " to " << *destBENode << "\n");
728 edgesToIgnore.insert(std::make_pair(srcBENode, destBENode->getInEdgeNum(srcBENode)));
729 recurrenceList.insert(std::make_pair(II, recurrence));
730 }
731
732}
733
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000734int CircCount;
735
736void ModuloSchedulingPass::unblock(MSchedGraphNode *u, std::set<MSchedGraphNode*> &blocked,
737 std::map<MSchedGraphNode*, std::set<MSchedGraphNode*> > &B) {
738
739 //Unblock u
740 DEBUG(std::cerr << "Unblocking: " << *u << "\n");
741 blocked.erase(u);
742
743 //std::set<MSchedGraphNode*> toErase;
744 while (!B[u].empty()) {
745 MSchedGraphNode *W = *B[u].begin();
746 B[u].erase(W);
747 //toErase.insert(*W);
748 DEBUG(std::cerr << "Removed: " << *W << "from B-List\n");
749 if(blocked.count(W))
750 unblock(W, blocked, B);
751 }
752
753}
754
755bool ModuloSchedulingPass::circuit(MSchedGraphNode *v, std::vector<MSchedGraphNode*> &stack,
756 std::set<MSchedGraphNode*> &blocked, std::vector<MSchedGraphNode*> &SCC,
757 MSchedGraphNode *s, std::map<MSchedGraphNode*, std::set<MSchedGraphNode*> > &B,
758 int II, std::map<MSchedGraphNode*, MSchedGraphNode*> &newNodes) {
759 bool f = false;
760
761 DEBUG(std::cerr << "Finding Circuits Starting with: ( " << v << ")"<< *v << "\n");
762
763 //Push node onto the stack
764 stack.push_back(v);
765
766 //block this node
767 blocked.insert(v);
768
769 //Loop over all successors of node v that are in the scc, create Adjaceny list
770 std::set<MSchedGraphNode*> AkV;
771 for(MSchedGraphNode::succ_iterator I = v->succ_begin(), E = v->succ_end(); I != E; ++I) {
772 if((std::find(SCC.begin(), SCC.end(), *I) != SCC.end())) {
773 AkV.insert(*I);
774 }
775 }
776
777 for(std::set<MSchedGraphNode*>::iterator I = AkV.begin(), E = AkV.end(); I != E; ++I) {
778 if(*I == s) {
779 //We have a circuit, so add it to our list
780
781 std::vector<MSchedGraphNode*> recc;
782 //Dump recurrence for now
783 DEBUG(std::cerr << "Starting Recc\n");
784
785 int totalDelay = 0;
786 int totalDistance = 0;
787 MSchedGraphNode *lastN = 0;
788
789 //Loop over recurrence, get delay and distance
790 for(std::vector<MSchedGraphNode*>::iterator N = stack.begin(), NE = stack.end(); N != NE; ++N) {
791 totalDelay += (*N)->getLatency();
792 if(lastN) {
793 totalDistance += (*N)->getInEdge(lastN).getIteDiff();
794 }
795
796 //Get the original node
797 lastN = *N;
798 recc.push_back(newNodes[*N]);
799
800 DEBUG(std::cerr << *lastN << "\n");
801 }
802
803 //Get the loop edge
804 totalDistance += lastN->getIteDiff(*stack.begin());
805
806 DEBUG(std::cerr << "End Recc\n");
807 f = true;
808 CircCount++;
809
810 //Insert reccurrence into the list
811 DEBUG(std::cerr << "Ignore Edge from: " << *lastN << " to " << **stack.begin() << "\n");
812 edgesToIgnore.insert(std::make_pair(newNodes[lastN], newNodes[(*stack.begin())]->getInEdgeNum(newNodes[lastN])));
813
814 //Adjust II until we get close to the inequality delay - II*distance <= 0
815 int RecMII = II; //Starting value
816 int value = totalDelay-(RecMII * totalDistance);
817 int lastII = II;
818 while(value <= 0) {
819
820 lastII = RecMII;
821 RecMII--;
822 value = totalDelay-(RecMII * totalDistance);
823 }
824
825 recurrenceList.insert(std::make_pair(lastII, recc));
826
827 }
828 else if(!blocked.count(*I)) {
829 if(circuit(*I, stack, blocked, SCC, s, B, II, newNodes))
830 f = true;
831 }
832 else
833 DEBUG(std::cerr << "Blocked: " << **I << "\n");
834 }
835
836
837 if(f) {
838 unblock(v, blocked, B);
839 }
840 else {
841 for(std::set<MSchedGraphNode*>::iterator I = AkV.begin(), E = AkV.end(); I != E; ++I)
842 B[*I].insert(v);
843
844 }
845
846 //Pop v
847 stack.pop_back();
848
849 return f;
850
851}
852
853void ModuloSchedulingPass::findAllCircuits(MSchedGraph *g, int II) {
854
855 CircCount = 0;
856
857 //Keep old to new node mapping information
858 std::map<MSchedGraphNode*, MSchedGraphNode*> newNodes;
859
860 //copy the graph
861 MSchedGraph *MSG = new MSchedGraph(*g, newNodes);
862
863 DEBUG(std::cerr << "Finding All Circuits\n");
864
865 //Set of blocked nodes
866 std::set<MSchedGraphNode*> blocked;
867
868 //Stack holding current circuit
869 std::vector<MSchedGraphNode*> stack;
870
871 //Map for B Lists
872 std::map<MSchedGraphNode*, std::set<MSchedGraphNode*> > B;
873
874 //current node
875 MSchedGraphNode *s;
876
877
878 //Iterate over the graph until its down to one node or empty
879 while(MSG->size() > 1) {
880
881 //Write Graph out to file
882 //WriteGraphToFile(std::cerr, "Graph" + utostr(MSG->size()), MSG);
883
884 DEBUG(std::cerr << "Graph Size: " << MSG->size() << "\n");
885 DEBUG(std::cerr << "Finding strong component Vk with least vertex\n");
886
887 //Iterate over all the SCCs in the graph
888 std::set<MSchedGraphNode*> Visited;
889 std::vector<MSchedGraphNode*> Vk;
890 MSchedGraphNode* s = 0;
891
892 //Find scc with the least vertex
893 for (MSchedGraph::iterator GI = MSG->begin(), E = MSG->end(); GI != E; ++GI)
894 if (Visited.insert(GI->second).second) {
895 for (scc_iterator<MSchedGraphNode*> SCCI = scc_begin(GI->second),
896 E = scc_end(GI->second); SCCI != E; ++SCCI) {
897 std::vector<MSchedGraphNode*> &nextSCC = *SCCI;
898
899 if (Visited.insert(nextSCC[0]).second) {
900 Visited.insert(nextSCC.begin()+1, nextSCC.end());
901
902 DEBUG(std::cerr << "SCC size: " << nextSCC.size() << "\n");
903
904 //Ignore self loops
905 if(nextSCC.size() > 1) {
906
907 //Get least vertex in Vk
908 if(!s) {
909 s = nextSCC[0];
910 Vk = nextSCC;
911 }
912
913 for(unsigned i = 0; i < nextSCC.size(); ++i) {
914 if(nextSCC[i] < s) {
915 s = nextSCC[i];
916 Vk = nextSCC;
917 }
918 }
919 }
920 }
921 }
922 }
923
924
925
926 //Process SCC
927 DEBUG(for(std::vector<MSchedGraphNode*>::iterator N = Vk.begin(), NE = Vk.end();
928 N != NE; ++N) { std::cerr << *((*N)->getInst()); });
929
930 //Iterate over all nodes in this scc
931 for(std::vector<MSchedGraphNode*>::iterator N = Vk.begin(), NE = Vk.end();
932 N != NE; ++N) {
933 blocked.erase(*N);
934 B[*N].clear();
935 }
936 if(Vk.size() > 1) {
937 circuit(s, stack, blocked, Vk, s, B, II, newNodes);
938
939 //Find all nodes up to s and delete them
940 std::vector<MSchedGraphNode*> nodesToRemove;
941 nodesToRemove.push_back(s);
942 for(MSchedGraph::iterator N = MSG->begin(), NE = MSG->end(); N != NE; ++N) {
943 if(N->second < s )
944 nodesToRemove.push_back(N->second);
945 }
946 for(std::vector<MSchedGraphNode*>::iterator N = nodesToRemove.begin(), NE = nodesToRemove.end(); N != NE; ++N) {
947 DEBUG(std::cerr << "Deleting Node: " << **N << "\n");
948 MSG->deleteNode(*N);
949 }
950 }
951 else
952 break;
953 }
954 DEBUG(std::cerr << "Num Circuits found: " << CircCount << "\n");
955}
956
957
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000958void ModuloSchedulingPass::findAllReccurrences(MSchedGraphNode *node,
959 std::vector<MSchedGraphNode*> &visitedNodes,
960 int II) {
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000961
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000962
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000963 if(std::find(visitedNodes.begin(), visitedNodes.end(), node) != visitedNodes.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000964 std::vector<MSchedGraphNode*> recurrence;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000965 bool first = true;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000966 int delay = 0;
967 int distance = 0;
968 int RecMII = II; //Starting value
969 MSchedGraphNode *last = node;
Chris Lattner46c2b3a2004-08-04 03:51:55 +0000970 MSchedGraphNode *srcBackEdge = 0;
971 MSchedGraphNode *destBackEdge = 0;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000972
973
974
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000975 for(std::vector<MSchedGraphNode*>::iterator I = visitedNodes.begin(), E = visitedNodes.end();
976 I !=E; ++I) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000977
978 if(*I == node)
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000979 first = false;
980 if(first)
981 continue;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000982
983 delay = delay + (*I)->getLatency();
984
985 if(*I != node) {
986 int diff = (*I)->getInEdge(last).getIteDiff();
987 distance += diff;
988 if(diff > 0) {
989 srcBackEdge = last;
990 destBackEdge = *I;
991 }
992 }
993
994 recurrence.push_back(*I);
995 last = *I;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000996 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000997
998
999
1000 //Get final distance calc
1001 distance += node->getInEdge(last).getIteDiff();
Tanya Lattnere1df2122004-11-22 20:41:24 +00001002 DEBUG(std::cerr << "Reccurrence Distance: " << distance << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001003
1004 //Adjust II until we get close to the inequality delay - II*distance <= 0
1005
1006 int value = delay-(RecMII * distance);
1007 int lastII = II;
1008 while(value <= 0) {
1009
1010 lastII = RecMII;
1011 RecMII--;
1012 value = delay-(RecMII * distance);
1013 }
1014
1015
1016 DEBUG(std::cerr << "Final II for this recurrence: " << lastII << "\n");
1017 addReccurrence(recurrence, lastII, srcBackEdge, destBackEdge);
1018 assert(distance != 0 && "Recurrence distance should not be zero");
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001019 return;
1020 }
1021
Tanya Lattner01114742005-01-18 04:15:41 +00001022 unsigned count = 0;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001023 for(MSchedGraphNode::succ_iterator I = node->succ_begin(), E = node->succ_end(); I != E; ++I) {
1024 visitedNodes.push_back(node);
Tanya Lattner01114742005-01-18 04:15:41 +00001025 //if(!edgesToIgnore.count(std::make_pair(node, count)))
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001026 findAllReccurrences(*I, visitedNodes, II);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001027 visitedNodes.pop_back();
Tanya Lattner01114742005-01-18 04:15:41 +00001028 count++;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001029 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001030}
1031
1032
1033
1034
1035
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001036void ModuloSchedulingPass::computePartialOrder() {
Tanya Lattnera6ec8f52004-11-24 01:49:10 +00001037
Tanya Lattnerdb40cf12005-02-10 17:02:58 +00001038 TIME_REGION(X, "calculatePartialOrder");
1039
Tanya Lattnera6ec8f52004-11-24 01:49:10 +00001040 //Only push BA branches onto the final node order, we put other branches after it
1041 //FIXME: Should we really be pushing branches on it a specific order instead of relying
1042 //on BA being there?
Tanya Lattner58fe2f02004-11-29 04:39:47 +00001043 std::vector<MSchedGraphNode*> branches;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001044
1045 //Loop over all recurrences and add to our partial order
1046 //be sure to remove nodes that are already in the partial order in
1047 //a different recurrence and don't add empty recurrences.
1048 for(std::set<std::pair<int, std::vector<MSchedGraphNode*> > >::reverse_iterator I = recurrenceList.rbegin(), E=recurrenceList.rend(); I !=E; ++I) {
1049
1050 //Add nodes that connect this recurrence to the previous recurrence
1051
1052 //If this is the first recurrence in the partial order, add all predecessors
1053 for(std::vector<MSchedGraphNode*>::const_iterator N = I->second.begin(), NE = I->second.end(); N != NE; ++N) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001054
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001055 }
1056
1057
Tanya Lattner260652a2004-10-30 00:39:07 +00001058 std::set<MSchedGraphNode*> new_recurrence;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001059 //Loop through recurrence and remove any nodes already in the partial order
1060 for(std::vector<MSchedGraphNode*>::const_iterator N = I->second.begin(), NE = I->second.end(); N != NE; ++N) {
1061 bool found = false;
Tanya Lattner260652a2004-10-30 00:39:07 +00001062 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(), PE = partialOrder.end(); PO != PE; ++PO) {
1063 if(PO->count(*N))
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001064 found = true;
1065 }
1066 if(!found) {
Tanya Lattnera6ec8f52004-11-24 01:49:10 +00001067 if((*N)->isBranch()) {
Tanya Lattner58fe2f02004-11-29 04:39:47 +00001068 branches.push_back(*N);
Tanya Lattnera6ec8f52004-11-24 01:49:10 +00001069 }
1070 else
1071 new_recurrence.insert(*N);
1072 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001073 if(partialOrder.size() == 0)
1074 //For each predecessors, add it to this recurrence ONLY if it is not already in it
1075 for(MSchedGraphNode::pred_iterator P = (*N)->pred_begin(),
1076 PE = (*N)->pred_end(); P != PE; ++P) {
1077
1078 //Check if we are supposed to ignore this edge or not
1079 if(!ignoreEdge(*P, *N))
1080 //Check if already in this recurrence
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001081 if(std::find(I->second.begin(), I->second.end(), *P) == I->second.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001082 //Also need to check if in partial order
1083 bool predFound = false;
Tanya Lattner260652a2004-10-30 00:39:07 +00001084 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(), PEND = partialOrder.end(); PO != PEND; ++PO) {
1085 if(PO->count(*P))
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001086 predFound = true;
1087 }
1088
1089 if(!predFound)
Tanya Lattnera6ec8f52004-11-24 01:49:10 +00001090 if(!new_recurrence.count(*P)) {
1091 if((*P)->isBranch()) {
Tanya Lattner58fe2f02004-11-29 04:39:47 +00001092 branches.push_back(*P);
Tanya Lattnera6ec8f52004-11-24 01:49:10 +00001093 }
1094 else
1095 new_recurrence.insert(*P);
1096
1097 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001098 }
1099 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001100 }
Tanya Lattnera6ec8f52004-11-24 01:49:10 +00001101
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001102 if(new_recurrence.size() > 0)
1103 partialOrder.push_back(new_recurrence);
1104 }
1105
1106 //Add any nodes that are not already in the partial order
Tanya Lattner260652a2004-10-30 00:39:07 +00001107 //Add them in a set, one set per connected component
1108 std::set<MSchedGraphNode*> lastNodes;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001109 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
1110 bool found = false;
1111 //Check if its already in our partial order, if not add it to the final vector
Tanya Lattner260652a2004-10-30 00:39:07 +00001112 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(), PE = partialOrder.end(); PO != PE; ++PO) {
1113 if(PO->count(I->first))
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001114 found = true;
1115 }
Tanya Lattnera6ec8f52004-11-24 01:49:10 +00001116 if(!found) {
1117 if(I->first->isBranch()) {
Tanya Lattner58fe2f02004-11-29 04:39:47 +00001118 if(std::find(branches.begin(), branches.end(), I->first) == branches.end())
1119 branches.push_back(I->first);
1120 }
Tanya Lattnera6ec8f52004-11-24 01:49:10 +00001121 else
1122 lastNodes.insert(I->first);
1123 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001124 }
1125
Tanya Lattner260652a2004-10-30 00:39:07 +00001126 //Break up remaining nodes that are not in the partial order
1127 //into their connected compoenents
1128 while(lastNodes.size() > 0) {
1129 std::set<MSchedGraphNode*> ccSet;
1130 connectedComponentSet(*(lastNodes.begin()),ccSet, lastNodes);
1131 if(ccSet.size() > 0)
1132 partialOrder.push_back(ccSet);
1133 }
1134 //if(lastNodes.size() > 0)
1135 //partialOrder.push_back(lastNodes);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001136
Tanya Lattnera6ec8f52004-11-24 01:49:10 +00001137 //Clean up branches by putting them in final order
Tanya Lattner58fe2f02004-11-29 04:39:47 +00001138 std::map<unsigned, MSchedGraphNode*> branchOrder;
1139 for(std::vector<MSchedGraphNode*>::iterator I = branches.begin(), E = branches.end(); I != E; ++I)
1140 branchOrder[(*I)->getIndex()] = *I;
1141
1142 for(std::map<unsigned, MSchedGraphNode*>::reverse_iterator I = branchOrder.rbegin(), E = branchOrder.rend(); I != E; ++I)
1143 FinalNodeOrder.push_back(I->second);
1144
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001145}
1146
1147
Tanya Lattner260652a2004-10-30 00:39:07 +00001148void ModuloSchedulingPass::connectedComponentSet(MSchedGraphNode *node, std::set<MSchedGraphNode*> &ccSet, std::set<MSchedGraphNode*> &lastNodes) {
1149
Tanya Lattnera6ec8f52004-11-24 01:49:10 +00001150//Add to final set
1151if( !ccSet.count(node) && lastNodes.count(node)) {
Tanya Lattner260652a2004-10-30 00:39:07 +00001152 lastNodes.erase(node);
Tanya Lattnera6ec8f52004-11-24 01:49:10 +00001153if(node->isBranch())
1154 FinalNodeOrder.push_back(node);
1155 else
1156 ccSet.insert(node);
Tanya Lattner260652a2004-10-30 00:39:07 +00001157 }
1158 else
1159 return;
1160
1161 //Loop over successors and recurse if we have not seen this node before
1162 for(MSchedGraphNode::succ_iterator node_succ = node->succ_begin(), end=node->succ_end(); node_succ != end; ++node_succ) {
1163 connectedComponentSet(*node_succ, ccSet, lastNodes);
1164 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001165
Tanya Lattner260652a2004-10-30 00:39:07 +00001166}
1167
1168void ModuloSchedulingPass::predIntersect(std::set<MSchedGraphNode*> &CurrentSet, std::set<MSchedGraphNode*> &IntersectResult) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001169
1170 for(unsigned j=0; j < FinalNodeOrder.size(); ++j) {
1171 for(MSchedGraphNode::pred_iterator P = FinalNodeOrder[j]->pred_begin(),
1172 E = FinalNodeOrder[j]->pred_end(); P != E; ++P) {
1173
1174 //Check if we are supposed to ignore this edge or not
1175 if(ignoreEdge(*P,FinalNodeOrder[j]))
1176 continue;
1177
Tanya Lattner260652a2004-10-30 00:39:07 +00001178 if(CurrentSet.count(*P))
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001179 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), *P) == FinalNodeOrder.end())
Tanya Lattner260652a2004-10-30 00:39:07 +00001180 IntersectResult.insert(*P);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001181 }
1182 }
1183}
1184
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001185
Tanya Lattner260652a2004-10-30 00:39:07 +00001186
1187
1188
1189void ModuloSchedulingPass::succIntersect(std::set<MSchedGraphNode*> &CurrentSet, std::set<MSchedGraphNode*> &IntersectResult) {
1190
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001191 for(unsigned j=0; j < FinalNodeOrder.size(); ++j) {
1192 for(MSchedGraphNode::succ_iterator P = FinalNodeOrder[j]->succ_begin(),
1193 E = FinalNodeOrder[j]->succ_end(); P != E; ++P) {
1194
1195 //Check if we are supposed to ignore this edge or not
1196 if(ignoreEdge(FinalNodeOrder[j],*P))
1197 continue;
1198
Tanya Lattner260652a2004-10-30 00:39:07 +00001199 if(CurrentSet.count(*P))
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001200 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), *P) == FinalNodeOrder.end())
Tanya Lattner260652a2004-10-30 00:39:07 +00001201 IntersectResult.insert(*P);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001202 }
1203 }
1204}
1205
Tanya Lattner260652a2004-10-30 00:39:07 +00001206void dumpIntersection(std::set<MSchedGraphNode*> &IntersectCurrent) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001207 std::cerr << "Intersection (";
Tanya Lattner260652a2004-10-30 00:39:07 +00001208 for(std::set<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(), E = IntersectCurrent.end(); I != E; ++I)
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001209 std::cerr << **I << ", ";
1210 std::cerr << ")\n";
1211}
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001212
1213
1214
1215void ModuloSchedulingPass::orderNodes() {
1216
Tanya Lattnerdb40cf12005-02-10 17:02:58 +00001217 TIME_REGION(X, "orderNodes");
1218
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001219 int BOTTOM_UP = 0;
1220 int TOP_DOWN = 1;
1221
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001222 //Set default order
1223 int order = BOTTOM_UP;
1224
Tanya Lattnera6ec8f52004-11-24 01:49:10 +00001225
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001226 //Loop over all the sets and place them in the final node order
Tanya Lattner260652a2004-10-30 00:39:07 +00001227 for(std::vector<std::set<MSchedGraphNode*> >::iterator CurrentSet = partialOrder.begin(), E= partialOrder.end(); CurrentSet != E; ++CurrentSet) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001228
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001229 DEBUG(std::cerr << "Processing set in S\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001230 DEBUG(dumpIntersection(*CurrentSet));
1231
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001232 //Result of intersection
Tanya Lattner260652a2004-10-30 00:39:07 +00001233 std::set<MSchedGraphNode*> IntersectCurrent;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001234
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001235 predIntersect(*CurrentSet, IntersectCurrent);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001236
1237 //If the intersection of predecessor and current set is not empty
1238 //sort nodes bottom up
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001239 if(IntersectCurrent.size() != 0) {
1240 DEBUG(std::cerr << "Final Node Order Predecessors and Current Set interesection is NOT empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001241 order = BOTTOM_UP;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001242 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001243 //If empty, use successors
1244 else {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001245 DEBUG(std::cerr << "Final Node Order Predecessors and Current Set interesection is empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001246
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001247 succIntersect(*CurrentSet, IntersectCurrent);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001248
1249 //sort top-down
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001250 if(IntersectCurrent.size() != 0) {
1251 DEBUG(std::cerr << "Final Node Order Successors and Current Set interesection is NOT empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001252 order = TOP_DOWN;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001253 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001254 else {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001255 DEBUG(std::cerr << "Final Node Order Successors and Current Set interesection is empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001256 //Find node with max ASAP in current Set
1257 MSchedGraphNode *node;
1258 int maxASAP = 0;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001259 DEBUG(std::cerr << "Using current set of size " << CurrentSet->size() << "to find max ASAP\n");
Tanya Lattner260652a2004-10-30 00:39:07 +00001260 for(std::set<MSchedGraphNode*>::iterator J = CurrentSet->begin(), JE = CurrentSet->end(); J != JE; ++J) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001261 //Get node attributes
Tanya Lattner260652a2004-10-30 00:39:07 +00001262 MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*J)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001263 //assert(nodeAttr != nodeToAttributesMap.end() && "Node not in attributes map!");
Tanya Lattner260652a2004-10-30 00:39:07 +00001264
1265 if(maxASAP <= nodeAttr.ASAP) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001266 maxASAP = nodeAttr.ASAP;
Tanya Lattner260652a2004-10-30 00:39:07 +00001267 node = *J;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001268 }
1269 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001270 assert(node != 0 && "In node ordering node should not be null");
Tanya Lattner260652a2004-10-30 00:39:07 +00001271 IntersectCurrent.insert(node);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001272 order = BOTTOM_UP;
1273 }
1274 }
1275
1276 //Repeat until all nodes are put into the final order from current set
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001277 while(IntersectCurrent.size() > 0) {
1278
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001279 if(order == TOP_DOWN) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001280 DEBUG(std::cerr << "Order is TOP DOWN\n");
1281
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001282 while(IntersectCurrent.size() > 0) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001283 DEBUG(std::cerr << "Intersection is not empty, so find heighest height\n");
1284
1285 int MOB = 0;
1286 int height = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +00001287 MSchedGraphNode *highestHeightNode = *(IntersectCurrent.begin());
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001288
1289 //Find node in intersection with highest heigh and lowest MOB
Tanya Lattner260652a2004-10-30 00:39:07 +00001290 for(std::set<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(),
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001291 E = IntersectCurrent.end(); I != E; ++I) {
1292
1293 //Get current nodes properties
1294 MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*I)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001295
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001296 if(height < nodeAttr.height) {
1297 highestHeightNode = *I;
1298 height = nodeAttr.height;
1299 MOB = nodeAttr.MOB;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001300 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001301 else if(height == nodeAttr.height) {
1302 if(MOB > nodeAttr.height) {
1303 highestHeightNode = *I;
1304 height = nodeAttr.height;
1305 MOB = nodeAttr.MOB;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001306 }
1307 }
1308 }
1309
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001310 //Append our node with greatest height to the NodeOrder
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001311 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), highestHeightNode) == FinalNodeOrder.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001312 DEBUG(std::cerr << "Adding node to Final Order: " << *highestHeightNode << "\n");
1313 FinalNodeOrder.push_back(highestHeightNode);
1314 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001315
1316 //Remove V from IntersectOrder
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001317 IntersectCurrent.erase(std::find(IntersectCurrent.begin(),
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001318 IntersectCurrent.end(), highestHeightNode));
1319
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001320
1321 //Intersect V's successors with CurrentSet
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001322 for(MSchedGraphNode::succ_iterator P = highestHeightNode->succ_begin(),
1323 E = highestHeightNode->succ_end(); P != E; ++P) {
1324 //if(lower_bound(CurrentSet->begin(),
1325 // CurrentSet->end(), *P) != CurrentSet->end()) {
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001326 if(std::find(CurrentSet->begin(), CurrentSet->end(), *P) != CurrentSet->end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001327 if(ignoreEdge(highestHeightNode, *P))
1328 continue;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001329 //If not already in Intersect, add
Tanya Lattner260652a2004-10-30 00:39:07 +00001330 if(!IntersectCurrent.count(*P))
1331 IntersectCurrent.insert(*P);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001332 }
1333 }
1334 } //End while loop over Intersect Size
1335
1336 //Change direction
1337 order = BOTTOM_UP;
1338
1339 //Reset Intersect to reflect changes in OrderNodes
1340 IntersectCurrent.clear();
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001341 predIntersect(*CurrentSet, IntersectCurrent);
1342
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001343 } //End If TOP_DOWN
1344
1345 //Begin if BOTTOM_UP
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001346 else {
1347 DEBUG(std::cerr << "Order is BOTTOM UP\n");
1348 while(IntersectCurrent.size() > 0) {
1349 DEBUG(std::cerr << "Intersection of size " << IntersectCurrent.size() << ", finding highest depth\n");
1350
1351 //dump intersection
1352 DEBUG(dumpIntersection(IntersectCurrent));
1353 //Get node with highest depth, if a tie, use one with lowest
1354 //MOB
1355 int MOB = 0;
1356 int depth = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +00001357 MSchedGraphNode *highestDepthNode = *(IntersectCurrent.begin());
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001358
Tanya Lattner260652a2004-10-30 00:39:07 +00001359 for(std::set<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(),
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001360 E = IntersectCurrent.end(); I != E; ++I) {
1361 //Find node attribute in graph
1362 MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*I)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001363
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001364 if(depth < nodeAttr.depth) {
1365 highestDepthNode = *I;
1366 depth = nodeAttr.depth;
1367 MOB = nodeAttr.MOB;
1368 }
1369 else if(depth == nodeAttr.depth) {
1370 if(MOB > nodeAttr.MOB) {
1371 highestDepthNode = *I;
1372 depth = nodeAttr.depth;
1373 MOB = nodeAttr.MOB;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001374 }
1375 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001376 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001377
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001378
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001379
1380 //Append highest depth node to the NodeOrder
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001381 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), highestDepthNode) == FinalNodeOrder.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001382 DEBUG(std::cerr << "Adding node to Final Order: " << *highestDepthNode << "\n");
1383 FinalNodeOrder.push_back(highestDepthNode);
1384 }
1385 //Remove heightestDepthNode from IntersectOrder
Tanya Lattner260652a2004-10-30 00:39:07 +00001386 IntersectCurrent.erase(highestDepthNode);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001387
1388
1389 //Intersect heightDepthNode's pred with CurrentSet
1390 for(MSchedGraphNode::pred_iterator P = highestDepthNode->pred_begin(),
1391 E = highestDepthNode->pred_end(); P != E; ++P) {
Tanya Lattner260652a2004-10-30 00:39:07 +00001392 if(CurrentSet->count(*P)) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001393 if(ignoreEdge(*P, highestDepthNode))
1394 continue;
1395
1396 //If not already in Intersect, add
Tanya Lattner260652a2004-10-30 00:39:07 +00001397 if(!IntersectCurrent.count(*P))
1398 IntersectCurrent.insert(*P);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001399 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001400 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001401
1402 } //End while loop over Intersect Size
1403
1404 //Change order
1405 order = TOP_DOWN;
1406
1407 //Reset IntersectCurrent to reflect changes in OrderNodes
1408 IntersectCurrent.clear();
1409 succIntersect(*CurrentSet, IntersectCurrent);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001410 } //End if BOTTOM_DOWN
1411
Tanya Lattner420025b2004-10-10 22:44:35 +00001412 DEBUG(std::cerr << "Current Intersection Size: " << IntersectCurrent.size() << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001413 }
1414 //End Wrapping while loop
Tanya Lattner420025b2004-10-10 22:44:35 +00001415 DEBUG(std::cerr << "Ending Size of Current Set: " << CurrentSet->size() << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001416 }//End for over all sets of nodes
Tanya Lattner420025b2004-10-10 22:44:35 +00001417
1418 //FIXME: As the algorithm stands it will NEVER add an instruction such as ba (with no
1419 //data dependencies) to the final order. We add this manually. It will always be
1420 //in the last set of S since its not part of a recurrence
1421 //Loop over all the sets and place them in the final node order
Tanya Lattner260652a2004-10-30 00:39:07 +00001422 std::vector<std::set<MSchedGraphNode*> > ::reverse_iterator LastSet = partialOrder.rbegin();
1423 for(std::set<MSchedGraphNode*>::iterator CurrentNode = LastSet->begin(), LastNode = LastSet->end();
Tanya Lattner420025b2004-10-10 22:44:35 +00001424 CurrentNode != LastNode; ++CurrentNode) {
1425 if((*CurrentNode)->getInst()->getOpcode() == V9::BA)
1426 FinalNodeOrder.push_back(*CurrentNode);
1427 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001428 //Return final Order
1429 //return FinalNodeOrder;
1430}
1431
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001432bool ModuloSchedulingPass::computeSchedule() {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001433
Tanya Lattnerdb40cf12005-02-10 17:02:58 +00001434 TIME_REGION(X, "computeSchedule");
1435
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001436 bool success = false;
1437
Tanya Lattner260652a2004-10-30 00:39:07 +00001438 //FIXME: Should be set to max II of the original loop
1439 //Cap II in order to prevent infinite loop
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001440 int capII = 100;
Tanya Lattner260652a2004-10-30 00:39:07 +00001441
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001442 while(!success) {
Tanya Lattner58fe2f02004-11-29 04:39:47 +00001443
1444 int branchES = II - 1;
1445 int branchLS = II - 1;
1446 bool lastBranch = true;
1447
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001448 //Loop over the final node order and process each node
1449 for(std::vector<MSchedGraphNode*>::iterator I = FinalNodeOrder.begin(),
1450 E = FinalNodeOrder.end(); I != E; ++I) {
1451
1452 //CalculateEarly and Late start
1453 int EarlyStart = -1;
1454 int LateStart = 99999; //Set to something higher then we would ever expect (FIXME)
1455 bool hasSucc = false;
1456 bool hasPred = false;
Tanya Lattner4cffb582004-05-26 06:27:18 +00001457
1458 if(!(*I)->isBranch()) {
1459 //Loop over nodes in the schedule and determine if they are predecessors
1460 //or successors of the node we are trying to schedule
1461 for(MSSchedule::schedule_iterator nodesByCycle = schedule.begin(), nodesByCycleEnd = schedule.end();
1462 nodesByCycle != nodesByCycleEnd; ++nodesByCycle) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001463
Tanya Lattner4cffb582004-05-26 06:27:18 +00001464 //For this cycle, get the vector of nodes schedule and loop over it
1465 for(std::vector<MSchedGraphNode*>::iterator schedNode = nodesByCycle->second.begin(), SNE = nodesByCycle->second.end(); schedNode != SNE; ++schedNode) {
1466
1467 if((*I)->isPredecessor(*schedNode)) {
Tanya Lattner01114742005-01-18 04:15:41 +00001468 //if(!ignoreEdge(*schedNode, *I)) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001469 int diff = (*I)->getInEdge(*schedNode).getIteDiff();
Tanya Lattner4cffb582004-05-26 06:27:18 +00001470 int ES_Temp = nodesByCycle->first + (*schedNode)->getLatency() - diff * II;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001471 DEBUG(std::cerr << "Diff: " << diff << " Cycle: " << nodesByCycle->first << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001472 DEBUG(std::cerr << "Temp EarlyStart: " << ES_Temp << " Prev EarlyStart: " << EarlyStart << "\n");
1473 EarlyStart = std::max(EarlyStart, ES_Temp);
1474 hasPred = true;
Tanya Lattner01114742005-01-18 04:15:41 +00001475 //}
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001476 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001477 if((*I)->isSuccessor(*schedNode)) {
Tanya Lattner01114742005-01-18 04:15:41 +00001478 //if(!ignoreEdge(*I,*schedNode)) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001479 int diff = (*schedNode)->getInEdge(*I).getIteDiff();
Tanya Lattner4cffb582004-05-26 06:27:18 +00001480 int LS_Temp = nodesByCycle->first - (*I)->getLatency() + diff * II;
1481 DEBUG(std::cerr << "Diff: " << diff << " Cycle: " << nodesByCycle->first << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001482 DEBUG(std::cerr << "Temp LateStart: " << LS_Temp << " Prev LateStart: " << LateStart << "\n");
1483 LateStart = std::min(LateStart, LS_Temp);
1484 hasSucc = true;
Tanya Lattner01114742005-01-18 04:15:41 +00001485 //}
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001486 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001487 }
1488 }
1489 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001490 else {
Tanya Lattner58fe2f02004-11-29 04:39:47 +00001491 if(lastBranch) {
1492 EarlyStart = branchES;
1493 LateStart = branchLS;
1494 lastBranch = false;
1495 --branchES;
1496 branchLS = 0;
Tanya Lattner420025b2004-10-10 22:44:35 +00001497 }
1498 else {
Tanya Lattner01114742005-01-18 04:15:41 +00001499 EarlyStart = branchLS;
1500 LateStart = branchES;
Tanya Lattner420025b2004-10-10 22:44:35 +00001501 assert( (EarlyStart >= 0) && (LateStart >=0) && "EarlyStart and LateStart must be greater then 0");
Tanya Lattner58fe2f02004-11-29 04:39:47 +00001502 --branchES;
Tanya Lattner420025b2004-10-10 22:44:35 +00001503 }
Tanya Lattner01114742005-01-18 04:15:41 +00001504 hasPred = 0;
Tanya Lattner4cffb582004-05-26 06:27:18 +00001505 hasSucc = 1;
1506 }
1507
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001508 DEBUG(std::cerr << "Has Successors: " << hasSucc << ", Has Pred: " << hasPred << "\n");
1509 DEBUG(std::cerr << "EarlyStart: " << EarlyStart << ", LateStart: " << LateStart << "\n");
1510
Tanya Lattner01114742005-01-18 04:15:41 +00001511
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001512 //Check if the node has no pred or successors and set Early Start to its ASAP
1513 if(!hasSucc && !hasPred)
1514 EarlyStart = nodeToAttributesMap.find(*I)->second.ASAP;
1515
1516 //Now, try to schedule this node depending upon its pred and successor in the schedule
1517 //already
1518 if(!hasSucc && hasPred)
1519 success = scheduleNode(*I, EarlyStart, (EarlyStart + II -1));
1520 else if(!hasPred && hasSucc)
1521 success = scheduleNode(*I, LateStart, (LateStart - II +1));
Tanya Lattner01114742005-01-18 04:15:41 +00001522 else if(hasPred && hasSucc) {
1523 if(EarlyStart > LateStart)
1524 success = false;
1525 else
1526 success = scheduleNode(*I, EarlyStart, std::min(LateStart, (EarlyStart + II -1)));
1527 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001528 else
1529 success = scheduleNode(*I, EarlyStart, EarlyStart + II - 1);
1530
1531 if(!success) {
Tanya Lattnere1df2122004-11-22 20:41:24 +00001532 ++IncreasedII;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001533 ++II;
1534 schedule.clear();
1535 break;
1536 }
1537
1538 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001539
Tanya Lattner260652a2004-10-30 00:39:07 +00001540 if(success) {
1541 DEBUG(std::cerr << "Constructing Schedule Kernel\n");
1542 success = schedule.constructKernel(II);
1543 DEBUG(std::cerr << "Done Constructing Schedule Kernel\n");
1544 if(!success) {
Tanya Lattnere1df2122004-11-22 20:41:24 +00001545 ++IncreasedII;
Tanya Lattner260652a2004-10-30 00:39:07 +00001546 ++II;
1547 schedule.clear();
1548 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001549 }
Tanya Lattner260652a2004-10-30 00:39:07 +00001550
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001551 if(II >= capII)
1552 return false;
1553
Tanya Lattner260652a2004-10-30 00:39:07 +00001554 assert(II < capII && "The II should not exceed the original loop number of cycles");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001555 }
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001556 return true;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001557}
1558
1559
1560bool ModuloSchedulingPass::scheduleNode(MSchedGraphNode *node,
1561 int start, int end) {
1562 bool success = false;
1563
1564 DEBUG(std::cerr << *node << " (Start Cycle: " << start << ", End Cycle: " << end << ")\n");
1565
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001566 //Make sure start and end are not negative
Tanya Lattner260652a2004-10-30 00:39:07 +00001567 if(start < 0) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001568 start = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +00001569
1570 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001571 if(end < 0)
1572 end = 0;
1573
1574 bool forward = true;
1575 if(start > end)
1576 forward = false;
1577
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001578 bool increaseSC = true;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001579 int cycle = start ;
1580
1581
1582 while(increaseSC) {
1583
1584 increaseSC = false;
1585
Tanya Lattner4cffb582004-05-26 06:27:18 +00001586 increaseSC = schedule.insert(node, cycle);
1587
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001588 if(!increaseSC)
1589 return true;
1590
1591 //Increment cycle to try again
1592 if(forward) {
1593 ++cycle;
1594 DEBUG(std::cerr << "Increase cycle: " << cycle << "\n");
1595 if(cycle > end)
1596 return false;
1597 }
1598 else {
1599 --cycle;
1600 DEBUG(std::cerr << "Decrease cycle: " << cycle << "\n");
1601 if(cycle < end)
1602 return false;
1603 }
1604 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001605
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001606 return success;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001607}
Tanya Lattner4cffb582004-05-26 06:27:18 +00001608
Tanya Lattner420025b2004-10-10 22:44:35 +00001609void 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 +00001610
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001611 //Keep a map to easily know whats in the kernel
Tanya Lattner4cffb582004-05-26 06:27:18 +00001612 std::map<int, std::set<const MachineInstr*> > inKernel;
1613 int maxStageCount = 0;
1614
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001615 //Keep a map of new values we consumed in case they need to be added back
1616 std::map<Value*, std::map<int, Value*> > consumedValues;
1617
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001618 MSchedGraphNode *branch = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +00001619 MSchedGraphNode *BAbranch = 0;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001620
Tanya Lattnere1df2122004-11-22 20:41:24 +00001621 schedule.print(std::cerr);
1622
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001623 std::vector<MSchedGraphNode*> branches;
1624
Tanya Lattner4cffb582004-05-26 06:27:18 +00001625 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
1626 maxStageCount = std::max(maxStageCount, I->second);
1627
1628 //Ignore the branch, we will handle this separately
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001629 if(I->first->isBranch()) {
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001630 branches.push_back(I->first);
Tanya Lattner4cffb582004-05-26 06:27:18 +00001631 continue;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001632 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001633
1634 //Put int the map so we know what instructions in each stage are in the kernel
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001635 DEBUG(std::cerr << "Inserting instruction " << *(I->first->getInst()) << " into map at stage " << I->second << "\n");
1636 inKernel[I->second].insert(I->first->getInst());
Tanya Lattner4cffb582004-05-26 06:27:18 +00001637 }
1638
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001639 //Get target information to look at machine operands
1640 const TargetInstrInfo *mii = target.getInstrInfo();
1641
1642 //Now write the prologues
1643 for(int i = 0; i < maxStageCount; ++i) {
1644 BasicBlock *llvmBB = new BasicBlock("PROLOGUE", (Function*) (origBB->getBasicBlock()->getParent()));
Tanya Lattner4cffb582004-05-26 06:27:18 +00001645 MachineBasicBlock *machineBB = new MachineBasicBlock(llvmBB);
1646
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001647 DEBUG(std::cerr << "i=" << i << "\n");
1648 for(int j = 0; j <= i; ++j) {
1649 for(MachineBasicBlock::const_iterator MI = origBB->begin(), ME = origBB->end(); ME != MI; ++MI) {
1650 if(inKernel[j].count(&*MI)) {
Tanya Lattner420025b2004-10-10 22:44:35 +00001651 MachineInstr *instClone = MI->clone();
1652 machineBB->push_back(instClone);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001653
Tanya Lattner420025b2004-10-10 22:44:35 +00001654 DEBUG(std::cerr << "Cloning: " << *MI << "\n");
1655
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001656 Instruction *tmp;
1657
1658 //After cloning, we may need to save the value that this instruction defines
1659 for(unsigned opNum=0; opNum < MI->getNumOperands(); ++opNum) {
1660 //get machine operand
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001661 MachineOperand &mOp = instClone->getOperand(opNum);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001662 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef()) {
1663
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001664 //Check if this is a value we should save
1665 if(valuesToSave.count(mOp.getVRegValue())) {
1666 //Save copy in tmpInstruction
1667 tmp = new TmpInstruction(mOp.getVRegValue());
1668
Tanya Lattner80f08552004-11-02 21:04:56 +00001669 //Add TmpInstruction to safe LLVM Instruction MCFI
1670 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001671 tempMvec.addTemp((Value*) tmp);
1672
Tanya Lattner420025b2004-10-10 22:44:35 +00001673 DEBUG(std::cerr << "Value: " << *(mOp.getVRegValue()) << " New Value: " << *tmp << " Stage: " << i << "\n");
1674
1675 newValues[mOp.getVRegValue()][i]= tmp;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001676 newValLocation[tmp] = machineBB;
1677
Tanya Lattner420025b2004-10-10 22:44:35 +00001678 DEBUG(std::cerr << "Machine Instr Operands: " << *(mOp.getVRegValue()) << ", 0, " << *tmp << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001679
1680 //Create machine instruction and put int machineBB
1681 MachineInstr *saveValue = BuildMI(machineBB, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
1682
1683 DEBUG(std::cerr << "Created new machine instr: " << *saveValue << "\n");
1684 }
1685 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001686
1687 //We may also need to update the value that we use if its from an earlier prologue
1688 if(j != 0) {
1689 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse()) {
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001690 if(newValues.count(mOp.getVRegValue())) {
1691 if(newValues[mOp.getVRegValue()].count(i-1)) {
1692 Value *oldV = mOp.getVRegValue();
Tanya Lattner420025b2004-10-10 22:44:35 +00001693 DEBUG(std::cerr << "Replaced this value: " << mOp.getVRegValue() << " With:" << (newValues[mOp.getVRegValue()][i-1]) << "\n");
1694 //Update the operand with the right value
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001695 mOp.setValueReg(newValues[mOp.getVRegValue()][i-1]);
1696
1697 //Remove this value since we have consumed it
1698 //NOTE: Should this only be done if j != maxStage?
1699 consumedValues[oldV][i-1] = (newValues[oldV][i-1]);
1700 DEBUG(std::cerr << "Deleted value: " << consumedValues[oldV][i-1] << "\n");
1701 newValues[oldV].erase(i-1);
Tanya Lattner420025b2004-10-10 22:44:35 +00001702 }
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001703 }
1704 else
1705 if(consumedValues.count(mOp.getVRegValue()))
1706 assert(!consumedValues[mOp.getVRegValue()].count(i-1) && "Found a case where we need the value");
Tanya Lattner420025b2004-10-10 22:44:35 +00001707 }
1708 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001709 }
1710 }
Tanya Lattner20890832004-05-28 20:14:12 +00001711 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001712 }
1713
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001714
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001715 for(std::vector<MSchedGraphNode*>::iterator BR = branches.begin(), BE = branches.end(); BR != BE; ++BR) {
1716
1717 //Stick in branch at the end
1718 machineBB->push_back((*BR)->getInst()->clone());
Tanya Lattner260652a2004-10-30 00:39:07 +00001719
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001720 //Add nop
1721 BuildMI(machineBB, V9::NOP, 0);
1722 }
Tanya Lattner260652a2004-10-30 00:39:07 +00001723
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001724
1725 (((MachineBasicBlock*)origBB)->getParent())->getBasicBlockList().push_back(machineBB);
Tanya Lattner4cffb582004-05-26 06:27:18 +00001726 prologues.push_back(machineBB);
1727 llvm_prologues.push_back(llvmBB);
1728 }
1729}
1730
Tanya Lattner420025b2004-10-10 22:44:35 +00001731void 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 +00001732
Tanya Lattner20890832004-05-28 20:14:12 +00001733 std::map<int, std::set<const MachineInstr*> > inKernel;
Tanya Lattner420025b2004-10-10 22:44:35 +00001734
Tanya Lattner20890832004-05-28 20:14:12 +00001735 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
Tanya Lattner20890832004-05-28 20:14:12 +00001736
1737 //Ignore the branch, we will handle this separately
1738 if(I->first->isBranch())
1739 continue;
1740
1741 //Put int the map so we know what instructions in each stage are in the kernel
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001742 inKernel[I->second].insert(I->first->getInst());
Tanya Lattner20890832004-05-28 20:14:12 +00001743 }
1744
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001745 std::map<Value*, Value*> valPHIs;
1746
Tanya Lattner420025b2004-10-10 22:44:35 +00001747 //some debug stuff, will remove later
1748 DEBUG(for(std::map<Value*, std::map<int, Value*> >::iterator V = newValues.begin(), E = newValues.end(); V !=E; ++V) {
1749 std::cerr << "Old Value: " << *(V->first) << "\n";
1750 for(std::map<int, Value*>::iterator I = V->second.begin(), IE = V->second.end(); I != IE; ++I)
1751 std::cerr << "Stage: " << I->first << " Value: " << *(I->second) << "\n";
1752 });
1753
1754 //some debug stuff, will remove later
1755 DEBUG(for(std::map<Value*, std::map<int, Value*> >::iterator V = kernelPHIs.begin(), E = kernelPHIs.end(); V !=E; ++V) {
1756 std::cerr << "Old Value: " << *(V->first) << "\n";
1757 for(std::map<int, Value*>::iterator I = V->second.begin(), IE = V->second.end(); I != IE; ++I)
1758 std::cerr << "Stage: " << I->first << " Value: " << *(I->second) << "\n";
1759 });
1760
Tanya Lattner20890832004-05-28 20:14:12 +00001761 //Now write the epilogues
Tanya Lattner420025b2004-10-10 22:44:35 +00001762 for(int i = schedule.getMaxStage()-1; i >= 0; --i) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001763 BasicBlock *llvmBB = new BasicBlock("EPILOGUE", (Function*) (origBB->getBasicBlock()->getParent()));
Tanya Lattner20890832004-05-28 20:14:12 +00001764 MachineBasicBlock *machineBB = new MachineBasicBlock(llvmBB);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001765
Tanya Lattner420025b2004-10-10 22:44:35 +00001766 DEBUG(std::cerr << " Epilogue #: " << i << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001767
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001768
Tanya Lattnera6457502004-10-14 06:04:28 +00001769 std::map<Value*, int> inEpilogue;
Tanya Lattner420025b2004-10-10 22:44:35 +00001770
1771 for(MachineBasicBlock::const_iterator MI = origBB->begin(), ME = origBB->end(); ME != MI; ++MI) {
1772 for(int j=schedule.getMaxStage(); j > i; --j) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001773 if(inKernel[j].count(&*MI)) {
1774 DEBUG(std::cerr << "Cloning instruction " << *MI << "\n");
1775 MachineInstr *clone = MI->clone();
1776
1777 //Update operands that need to use the result from the phi
Tanya Lattner420025b2004-10-10 22:44:35 +00001778 for(unsigned opNum=0; opNum < clone->getNumOperands(); ++opNum) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001779 //get machine operand
Tanya Lattner420025b2004-10-10 22:44:35 +00001780 const MachineOperand &mOp = clone->getOperand(opNum);
Tanya Lattner420025b2004-10-10 22:44:35 +00001781
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001782 if((mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse())) {
Tanya Lattner420025b2004-10-10 22:44:35 +00001783
1784 DEBUG(std::cerr << "Writing PHI for " << *(mOp.getVRegValue()) << "\n");
Tanya Lattnera6457502004-10-14 06:04:28 +00001785
1786 //If this is the last instructions for the max iterations ago, don't update operands
1787 if(inEpilogue.count(mOp.getVRegValue()))
1788 if(inEpilogue[mOp.getVRegValue()] == i)
1789 continue;
Tanya Lattner420025b2004-10-10 22:44:35 +00001790
1791 //Quickly write appropriate phis for this operand
1792 if(newValues.count(mOp.getVRegValue())) {
1793 if(newValues[mOp.getVRegValue()].count(i)) {
1794 Instruction *tmp = new TmpInstruction(newValues[mOp.getVRegValue()][i]);
Tanya Lattnera6457502004-10-14 06:04:28 +00001795
1796 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00001797 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001798 tempMvec.addTemp((Value*) tmp);
1799
Tanya Lattner420025b2004-10-10 22:44:35 +00001800 MachineInstr *saveValue = BuildMI(machineBB, V9::PHI, 3).addReg(newValues[mOp.getVRegValue()][i]).addReg(kernelPHIs[mOp.getVRegValue()][i]).addRegDef(tmp);
1801 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
1802 valPHIs[mOp.getVRegValue()] = tmp;
1803 }
1804 }
1805
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001806 if(valPHIs.count(mOp.getVRegValue())) {
1807 //Update the operand in the cloned instruction
Tanya Lattner420025b2004-10-10 22:44:35 +00001808 clone->getOperand(opNum).setValueReg(valPHIs[mOp.getVRegValue()]);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001809 }
1810 }
Tanya Lattnera6457502004-10-14 06:04:28 +00001811 else if((mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef())) {
1812 inEpilogue[mOp.getVRegValue()] = i;
1813 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001814 }
1815 machineBB->push_back(clone);
1816 }
1817 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001818 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001819
Tanya Lattner20890832004-05-28 20:14:12 +00001820 (((MachineBasicBlock*)origBB)->getParent())->getBasicBlockList().push_back(machineBB);
1821 epilogues.push_back(machineBB);
1822 llvm_epilogues.push_back(llvmBB);
Tanya Lattner420025b2004-10-10 22:44:35 +00001823
1824 DEBUG(std::cerr << "EPILOGUE #" << i << "\n");
1825 DEBUG(machineBB->print(std::cerr));
Tanya Lattner20890832004-05-28 20:14:12 +00001826 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001827}
1828
Tanya Lattner420025b2004-10-10 22:44:35 +00001829void 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 +00001830
1831 //Keep track of operands that are read and saved from a previous iteration. The new clone
1832 //instruction will use the result of the phi instead.
1833 std::map<Value*, Value*> finalPHIValue;
1834 std::map<Value*, Value*> kernelValue;
1835
Tanya Lattnerf3fa55f2004-12-03 05:25:22 +00001836 //Branches are a special case
1837 std::vector<MachineInstr*> branches;
1838
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001839 //Create TmpInstructions for the final phis
1840 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
1841
Tanya Lattner420025b2004-10-10 22:44:35 +00001842 DEBUG(std::cerr << "Stage: " << I->second << " Inst: " << *(I->first->getInst()) << "\n";);
1843
Tanya Lattnerf3fa55f2004-12-03 05:25:22 +00001844 if(I->first->isBranch()) {
1845 //Clone instruction
1846 const MachineInstr *inst = I->first->getInst();
1847 MachineInstr *instClone = inst->clone();
1848 branches.push_back(instClone);
Tanya Lattner01114742005-01-18 04:15:41 +00001849 continue;
Tanya Lattnerf3fa55f2004-12-03 05:25:22 +00001850 }
1851
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001852 //Clone instruction
1853 const MachineInstr *inst = I->first->getInst();
1854 MachineInstr *instClone = inst->clone();
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001855
Tanya Lattner420025b2004-10-10 22:44:35 +00001856 //Insert into machine basic block
1857 machineBB->push_back(instClone);
1858
Tanya Lattnerced82222004-11-16 21:31:37 +00001859 DEBUG(std::cerr << "Cloned Inst: " << *instClone << "\n");
1860
Tanya Lattner420025b2004-10-10 22:44:35 +00001861 //Loop over Machine Operands
1862 for(unsigned i=0; i < inst->getNumOperands(); ++i) {
1863 //get machine operand
1864 const MachineOperand &mOp = inst->getOperand(i);
1865
1866 if(I->second != 0) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001867 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse()) {
Tanya Lattner420025b2004-10-10 22:44:35 +00001868
1869 //Check to see where this operand is defined if this instruction is from max stage
1870 if(I->second == schedule.getMaxStage()) {
1871 DEBUG(std::cerr << "VREG: " << *(mOp.getVRegValue()) << "\n");
1872 }
1873
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001874 //If its in the value saved, we need to create a temp instruction and use that instead
1875 if(valuesToSave.count(mOp.getVRegValue())) {
Tanya Lattnerced82222004-11-16 21:31:37 +00001876
1877 //Check if we already have a final PHI value for this
1878 if(!finalPHIValue.count(mOp.getVRegValue())) {
1879 TmpInstruction *tmp = new TmpInstruction(mOp.getVRegValue());
1880
1881 //Get machine code for this instruction
1882 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
1883 tempMvec.addTemp((Value*) tmp);
1884
1885 //Update the operand in the cloned instruction
1886 instClone->getOperand(i).setValueReg(tmp);
1887
1888 //save this as our final phi
1889 finalPHIValue[mOp.getVRegValue()] = tmp;
1890 newValLocation[tmp] = machineBB;
1891 }
1892 else {
1893 //Use the previous final phi value
1894 instClone->getOperand(i).setValueReg(finalPHIValue[mOp.getVRegValue()]);
1895 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001896 }
1897 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001898 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001899 if(I->second != schedule.getMaxStage()) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001900 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef()) {
1901 if(valuesToSave.count(mOp.getVRegValue())) {
1902
1903 TmpInstruction *tmp = new TmpInstruction(mOp.getVRegValue());
1904
Tanya Lattnera6457502004-10-14 06:04:28 +00001905 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00001906 MachineCodeForInstruction & tempVec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001907 tempVec.addTemp((Value*) tmp);
1908
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001909 //Create new machine instr and put in MBB
1910 MachineInstr *saveValue = BuildMI(machineBB, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
1911
1912 //Save for future cleanup
1913 kernelValue[mOp.getVRegValue()] = tmp;
1914 newValLocation[tmp] = machineBB;
Tanya Lattner420025b2004-10-10 22:44:35 +00001915 kernelPHIs[mOp.getVRegValue()][schedule.getMaxStage()-1] = tmp;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001916 }
1917 }
1918 }
1919 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001920
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001921 }
1922
Tanya Lattnerf3fa55f2004-12-03 05:25:22 +00001923 //Add branches
1924 for(std::vector<MachineInstr*>::iterator I = branches.begin(), E = branches.end(); I != E; ++I) {
1925 machineBB->push_back(*I);
1926 BuildMI(machineBB, V9::NOP, 0);
1927 }
1928
1929
Tanya Lattner420025b2004-10-10 22:44:35 +00001930 DEBUG(std::cerr << "KERNEL before PHIs\n");
1931 DEBUG(machineBB->print(std::cerr));
1932
1933
1934 //Loop over each value we need to generate phis for
1935 for(std::map<Value*, std::map<int, Value*> >::iterator V = newValues.begin(),
1936 E = newValues.end(); V != E; ++V) {
1937
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001938
1939 DEBUG(std::cerr << "Writing phi for" << *(V->first));
Tanya Lattner420025b2004-10-10 22:44:35 +00001940 DEBUG(std::cerr << "\nMap of Value* for this phi\n");
1941 DEBUG(for(std::map<int, Value*>::iterator I = V->second.begin(),
1942 IE = V->second.end(); I != IE; ++I) {
1943 std::cerr << "Stage: " << I->first;
1944 std::cerr << " Value: " << *(I->second) << "\n";
1945 });
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001946
Tanya Lattner420025b2004-10-10 22:44:35 +00001947 //If we only have one current iteration live, its safe to set lastPhi = to kernel value
1948 if(V->second.size() == 1) {
1949 assert(kernelValue[V->first] != 0 && "Kernel value* must exist to create phi");
1950 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(),V9::PHI, 3).addReg(V->second.begin()->second).addReg(kernelValue[V->first]).addRegDef(finalPHIValue[V->first]);
1951 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
1952 kernelPHIs[V->first][schedule.getMaxStage()-1] = kernelValue[V->first];
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001953 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001954 else {
1955
1956 //Keep track of last phi created.
1957 Instruction *lastPhi = 0;
1958
1959 unsigned count = 1;
1960 //Loop over the the map backwards to generate phis
1961 for(std::map<int, Value*>::reverse_iterator I = V->second.rbegin(), IE = V->second.rend();
1962 I != IE; ++I) {
1963
1964 if(count < (V->second).size()) {
1965 if(lastPhi == 0) {
1966 lastPhi = new TmpInstruction(I->second);
Tanya Lattnera6457502004-10-14 06:04:28 +00001967
1968 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00001969 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001970 tempMvec.addTemp((Value*) lastPhi);
1971
Tanya Lattner420025b2004-10-10 22:44:35 +00001972 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(), V9::PHI, 3).addReg(kernelValue[V->first]).addReg(I->second).addRegDef(lastPhi);
1973 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
1974 newValLocation[lastPhi] = machineBB;
1975 }
1976 else {
1977 Instruction *tmp = new TmpInstruction(I->second);
Tanya Lattnera6457502004-10-14 06:04:28 +00001978
1979 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00001980 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001981 tempMvec.addTemp((Value*) tmp);
1982
1983
Tanya Lattner420025b2004-10-10 22:44:35 +00001984 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(), V9::PHI, 3).addReg(lastPhi).addReg(I->second).addRegDef(tmp);
1985 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
1986 lastPhi = tmp;
1987 kernelPHIs[V->first][I->first] = lastPhi;
1988 newValLocation[lastPhi] = machineBB;
1989 }
1990 }
1991 //Final phi value
1992 else {
1993 //The resulting value must be the Value* we created earlier
1994 assert(lastPhi != 0 && "Last phi is NULL!\n");
1995 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(), V9::PHI, 3).addReg(lastPhi).addReg(I->second).addRegDef(finalPHIValue[V->first]);
1996 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
1997 kernelPHIs[V->first][I->first] = finalPHIValue[V->first];
1998 }
1999
2000 ++count;
2001 }
2002
2003 }
2004 }
2005
2006 DEBUG(std::cerr << "KERNEL after PHIs\n");
2007 DEBUG(machineBB->print(std::cerr));
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002008}
2009
Tanya Lattner420025b2004-10-10 22:44:35 +00002010
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002011void ModuloSchedulingPass::removePHIs(const MachineBasicBlock *origBB, std::vector<MachineBasicBlock *> &prologues, std::vector<MachineBasicBlock *> &epilogues, MachineBasicBlock *kernelBB, std::map<Value*, MachineBasicBlock*> &newValLocation) {
2012
2013 //Worklist to delete things
2014 std::vector<std::pair<MachineBasicBlock*, MachineBasicBlock::iterator> > worklist;
Tanya Lattnera6457502004-10-14 06:04:28 +00002015
2016 //Worklist of TmpInstructions that need to be added to a MCFI
2017 std::vector<Instruction*> addToMCFI;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002018
Tanya Lattnera6457502004-10-14 06:04:28 +00002019 //Worklist to add OR instructions to end of kernel so not to invalidate the iterator
2020 //std::vector<std::pair<Instruction*, Value*> > newORs;
2021
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002022 const TargetInstrInfo *TMI = target.getInstrInfo();
2023
2024 //Start with the kernel and for each phi insert a copy for the phi def and for each arg
2025 for(MachineBasicBlock::iterator I = kernelBB->begin(), E = kernelBB->end(); I != E; ++I) {
Tanya Lattnera6457502004-10-14 06:04:28 +00002026
Tanya Lattner80f08552004-11-02 21:04:56 +00002027 DEBUG(std::cerr << "Looking at Instr: " << *I << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002028 //Get op code and check if its a phi
Tanya Lattnera6457502004-10-14 06:04:28 +00002029 if(I->getOpcode() == V9::PHI) {
2030
2031 DEBUG(std::cerr << "Replacing PHI: " << *I << "\n");
2032 Instruction *tmp = 0;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002033
Tanya Lattnera6457502004-10-14 06:04:28 +00002034 for(unsigned i = 0; i < I->getNumOperands(); ++i) {
2035 //Get Operand
2036 const MachineOperand &mOp = I->getOperand(i);
2037 assert(mOp.getType() == MachineOperand::MO_VirtualRegister && "Should be a Value*\n");
2038
2039 if(!tmp) {
2040 tmp = new TmpInstruction(mOp.getVRegValue());
2041 addToMCFI.push_back(tmp);
2042 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002043
Tanya Lattnera6457502004-10-14 06:04:28 +00002044 //Now for all our arguments we read, OR to the new TmpInstruction that we created
2045 if(mOp.isUse()) {
2046 DEBUG(std::cerr << "Use: " << mOp << "\n");
2047 //Place a copy at the end of its BB but before the branches
2048 assert(newValLocation.count(mOp.getVRegValue()) && "We must know where this value is located\n");
2049 //Reverse iterate to find the branches, we can safely assume no instructions have been
2050 //put in the nop positions
2051 for(MachineBasicBlock::iterator inst = --(newValLocation[mOp.getVRegValue()])->end(), endBB = (newValLocation[mOp.getVRegValue()])->begin(); inst != endBB; --inst) {
2052 MachineOpCode opc = inst->getOpcode();
2053 if(TMI->isBranch(opc) || TMI->isNop(opc))
2054 continue;
2055 else {
2056 BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
2057 break;
2058 }
2059
2060 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002061
Tanya Lattnera6457502004-10-14 06:04:28 +00002062 }
2063 else {
2064 //Remove the phi and replace it with an OR
2065 DEBUG(std::cerr << "Def: " << mOp << "\n");
2066 //newORs.push_back(std::make_pair(tmp, mOp.getVRegValue()));
2067 BuildMI(*kernelBB, I, V9::ORr, 3).addReg(tmp).addImm(0).addRegDef(mOp.getVRegValue());
2068 worklist.push_back(std::make_pair(kernelBB, I));
2069 }
2070
2071 }
2072
2073 }
2074
Tanya Lattnera6457502004-10-14 06:04:28 +00002075
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002076 }
2077
Tanya Lattner80f08552004-11-02 21:04:56 +00002078 //Add TmpInstructions to some MCFI
2079 if(addToMCFI.size() > 0) {
2080 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
2081 for(unsigned x = 0; x < addToMCFI.size(); ++x) {
2082 tempMvec.addTemp(addToMCFI[x]);
2083 }
2084 addToMCFI.clear();
2085 }
2086
Tanya Lattnera6457502004-10-14 06:04:28 +00002087
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002088 //Remove phis from epilogue
2089 for(std::vector<MachineBasicBlock*>::iterator MB = epilogues.begin(), ME = epilogues.end(); MB != ME; ++MB) {
2090 for(MachineBasicBlock::iterator I = (*MB)->begin(), E = (*MB)->end(); I != E; ++I) {
Tanya Lattner80f08552004-11-02 21:04:56 +00002091
2092 DEBUG(std::cerr << "Looking at Instr: " << *I << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002093 //Get op code and check if its a phi
Brian Gaeke418379e2004-08-18 20:04:24 +00002094 if(I->getOpcode() == V9::PHI) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002095 Instruction *tmp = 0;
Tanya Lattnera6457502004-10-14 06:04:28 +00002096
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002097 for(unsigned i = 0; i < I->getNumOperands(); ++i) {
2098 //Get Operand
2099 const MachineOperand &mOp = I->getOperand(i);
2100 assert(mOp.getType() == MachineOperand::MO_VirtualRegister && "Should be a Value*\n");
2101
2102 if(!tmp) {
2103 tmp = new TmpInstruction(mOp.getVRegValue());
Tanya Lattnera6457502004-10-14 06:04:28 +00002104 addToMCFI.push_back(tmp);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002105 }
2106
2107 //Now for all our arguments we read, OR to the new TmpInstruction that we created
2108 if(mOp.isUse()) {
2109 DEBUG(std::cerr << "Use: " << mOp << "\n");
2110 //Place a copy at the end of its BB but before the branches
2111 assert(newValLocation.count(mOp.getVRegValue()) && "We must know where this value is located\n");
2112 //Reverse iterate to find the branches, we can safely assume no instructions have been
2113 //put in the nop positions
2114 for(MachineBasicBlock::iterator inst = --(newValLocation[mOp.getVRegValue()])->end(), endBB = (newValLocation[mOp.getVRegValue()])->begin(); inst != endBB; --inst) {
2115 MachineOpCode opc = inst->getOpcode();
2116 if(TMI->isBranch(opc) || TMI->isNop(opc))
2117 continue;
2118 else {
2119 BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
2120 break;
2121 }
2122
2123 }
Tanya Lattnera6457502004-10-14 06:04:28 +00002124
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002125 }
2126 else {
2127 //Remove the phi and replace it with an OR
2128 DEBUG(std::cerr << "Def: " << mOp << "\n");
2129 BuildMI(**MB, I, V9::ORr, 3).addReg(tmp).addImm(0).addRegDef(mOp.getVRegValue());
2130 worklist.push_back(std::make_pair(*MB,I));
2131 }
2132
2133 }
2134 }
Tanya Lattnera6457502004-10-14 06:04:28 +00002135
Tanya Lattner80f08552004-11-02 21:04:56 +00002136
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002137 }
2138 }
2139
Tanya Lattner80f08552004-11-02 21:04:56 +00002140
2141 if(addToMCFI.size() > 0) {
2142 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
2143 for(unsigned x = 0; x < addToMCFI.size(); ++x) {
2144 tempMvec.addTemp(addToMCFI[x]);
2145 }
2146 addToMCFI.clear();
2147 }
2148
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002149 //Delete the phis
2150 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 +00002151
2152 DEBUG(std::cerr << "Deleting PHI " << *I->second << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002153 I->first->erase(I->second);
2154
2155 }
2156
Tanya Lattnera6457502004-10-14 06:04:28 +00002157
2158 assert((addToMCFI.size() == 0) && "We should have added all TmpInstructions to some MachineCodeForInstruction");
Tanya Lattner20890832004-05-28 20:14:12 +00002159}
2160
2161
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002162void ModuloSchedulingPass::reconstructLoop(MachineBasicBlock *BB) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00002163
Tanya Lattnerdb40cf12005-02-10 17:02:58 +00002164 TIME_REGION(X, "reconstructLoop");
2165
2166
Tanya Lattner420025b2004-10-10 22:44:35 +00002167 DEBUG(std::cerr << "Reconstructing Loop\n");
2168
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002169 //First find the value *'s that we need to "save"
2170 std::map<const Value*, std::pair<const MSchedGraphNode*, int> > valuesToSave;
Tanya Lattner4cffb582004-05-26 06:27:18 +00002171
Tanya Lattner420025b2004-10-10 22:44:35 +00002172 //Keep track of instructions we have already seen and their stage because
2173 //we don't want to "save" values if they are used in the kernel immediately
2174 std::map<const MachineInstr*, int> lastInstrs;
2175
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002176 //Loop over kernel and only look at instructions from a stage > 0
2177 //Look at its operands and save values *'s that are read
Tanya Lattner4cffb582004-05-26 06:27:18 +00002178 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00002179
Tanya Lattner420025b2004-10-10 22:44:35 +00002180 if(I->second !=0) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00002181 //For this instruction, get the Value*'s that it reads and put them into the set.
2182 //Assert if there is an operand of another type that we need to save
2183 const MachineInstr *inst = I->first->getInst();
Tanya Lattner420025b2004-10-10 22:44:35 +00002184 lastInstrs[inst] = I->second;
2185
Tanya Lattner4cffb582004-05-26 06:27:18 +00002186 for(unsigned i=0; i < inst->getNumOperands(); ++i) {
2187 //get machine operand
2188 const MachineOperand &mOp = inst->getOperand(i);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002189
Tanya Lattner4cffb582004-05-26 06:27:18 +00002190 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse()) {
2191 //find the value in the map
Tanya Lattner420025b2004-10-10 22:44:35 +00002192 if (const Value* srcI = mOp.getVRegValue()) {
2193
Tanya Lattnerced82222004-11-16 21:31:37 +00002194 if(isa<Constant>(srcI) || isa<Argument>(srcI) || isa<PHINode>(srcI))
Tanya Lattner80f08552004-11-02 21:04:56 +00002195 continue;
2196
Tanya Lattner420025b2004-10-10 22:44:35 +00002197 //Before we declare this Value* one that we should save
2198 //make sure its def is not of the same stage as this instruction
2199 //because it will be consumed before its used
2200 Instruction *defInst = (Instruction*) srcI;
2201
2202 //Should we save this value?
2203 bool save = true;
2204
Tanya Lattnerced82222004-11-16 21:31:37 +00002205 //Continue if not in the def map, loop invariant code does not need to be saved
2206 if(!defMap.count(srcI))
2207 continue;
2208
Tanya Lattner80f08552004-11-02 21:04:56 +00002209 MachineInstr *defInstr = defMap[srcI];
2210
Tanya Lattnerced82222004-11-16 21:31:37 +00002211
Tanya Lattner80f08552004-11-02 21:04:56 +00002212 if(lastInstrs.count(defInstr)) {
Tanya Lattnerced82222004-11-16 21:31:37 +00002213 if(lastInstrs[defInstr] == I->second) {
Tanya Lattner80f08552004-11-02 21:04:56 +00002214 save = false;
Tanya Lattnerced82222004-11-16 21:31:37 +00002215
2216 }
Tanya Lattner420025b2004-10-10 22:44:35 +00002217 }
Tanya Lattner80f08552004-11-02 21:04:56 +00002218
Tanya Lattner420025b2004-10-10 22:44:35 +00002219 if(save)
2220 valuesToSave[srcI] = std::make_pair(I->first, i);
2221 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00002222 }
2223
2224 if(mOp.getType() != MachineOperand::MO_VirtualRegister && mOp.isUse()) {
2225 assert("Our assumption is wrong. We have another type of register that needs to be saved\n");
2226 }
2227 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00002228 }
2229 }
2230
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002231 //The new loop will consist of one or more prologues, the kernel, and one or more epilogues.
2232
2233 //Map to keep track of old to new values
Tanya Lattner420025b2004-10-10 22:44:35 +00002234 std::map<Value*, std::map<int, Value*> > newValues;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002235
Tanya Lattner420025b2004-10-10 22:44:35 +00002236 //Map to keep track of old to new values in kernel
2237 std::map<Value*, std::map<int, Value*> > kernelPHIs;
2238
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002239 //Another map to keep track of what machine basic blocks these new value*s are in since
2240 //they have no llvm instruction equivalent
2241 std::map<Value*, MachineBasicBlock*> newValLocation;
2242
2243 std::vector<MachineBasicBlock*> prologues;
2244 std::vector<BasicBlock*> llvm_prologues;
2245
2246
2247 //Write prologue
2248 writePrologues(prologues, BB, llvm_prologues, valuesToSave, newValues, newValLocation);
Tanya Lattner420025b2004-10-10 22:44:35 +00002249
2250 //Print out epilogues and prologue
2251 DEBUG(for(std::vector<MachineBasicBlock*>::iterator I = prologues.begin(), E = prologues.end();
2252 I != E; ++I) {
2253 std::cerr << "PROLOGUE\n";
2254 (*I)->print(std::cerr);
2255 });
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002256
2257 BasicBlock *llvmKernelBB = new BasicBlock("Kernel", (Function*) (BB->getBasicBlock()->getParent()));
2258 MachineBasicBlock *machineKernelBB = new MachineBasicBlock(llvmKernelBB);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002259 (((MachineBasicBlock*)BB)->getParent())->getBasicBlockList().push_back(machineKernelBB);
Tanya Lattner420025b2004-10-10 22:44:35 +00002260 writeKernel(llvmKernelBB, machineKernelBB, valuesToSave, newValues, newValLocation, kernelPHIs);
2261
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002262
2263 std::vector<MachineBasicBlock*> epilogues;
2264 std::vector<BasicBlock*> llvm_epilogues;
2265
2266 //Write epilogues
Tanya Lattner420025b2004-10-10 22:44:35 +00002267 writeEpilogues(epilogues, BB, llvm_epilogues, valuesToSave, newValues, newValLocation, kernelPHIs);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002268
2269
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002270 //Fix our branches
2271 fixBranches(prologues, llvm_prologues, machineKernelBB, llvmKernelBB, epilogues, llvm_epilogues, BB);
2272
2273 //Remove phis
2274 removePHIs(BB, prologues, epilogues, machineKernelBB, newValLocation);
2275
2276 //Print out epilogues and prologue
2277 DEBUG(for(std::vector<MachineBasicBlock*>::iterator I = prologues.begin(), E = prologues.end();
2278 I != E; ++I) {
2279 std::cerr << "PROLOGUE\n";
2280 (*I)->print(std::cerr);
2281 });
2282
2283 DEBUG(std::cerr << "KERNEL\n");
2284 DEBUG(machineKernelBB->print(std::cerr));
2285
2286 DEBUG(for(std::vector<MachineBasicBlock*>::iterator I = epilogues.begin(), E = epilogues.end();
2287 I != E; ++I) {
2288 std::cerr << "EPILOGUE\n";
2289 (*I)->print(std::cerr);
2290 });
2291
2292
2293 DEBUG(std::cerr << "New Machine Function" << "\n");
2294 DEBUG(std::cerr << BB->getParent() << "\n");
2295
2296
2297}
2298
2299void ModuloSchedulingPass::fixBranches(std::vector<MachineBasicBlock *> &prologues, std::vector<BasicBlock*> &llvm_prologues, MachineBasicBlock *machineKernelBB, BasicBlock *llvmKernelBB, std::vector<MachineBasicBlock *> &epilogues, std::vector<BasicBlock*> &llvm_epilogues, MachineBasicBlock *BB) {
2300
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002301 const TargetInstrInfo *TMI = target.getInstrInfo();
2302
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002303 //Fix prologue branches
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002304 for(unsigned I = 0; I < prologues.size(); ++I) {
2305
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002306 //Find terminator since getFirstTerminator does not work!
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002307 for(MachineBasicBlock::reverse_iterator mInst = prologues[I]->rbegin(), mInstEnd = prologues[I]->rend(); mInst != mInstEnd; ++mInst) {
2308 MachineOpCode OC = mInst->getOpcode();
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002309 //If its a branch update its branchto
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002310 if(TMI->isBranch(OC)) {
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002311 for(unsigned opNum = 0; opNum < mInst->getNumOperands(); ++opNum) {
2312 MachineOperand &mOp = mInst->getOperand(opNum);
2313 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2314 //Check if we are branching to the kernel, if not branch to epilogue
2315 if(mOp.getVRegValue() == BB->getBasicBlock()) {
2316 if(I == prologues.size()-1)
2317 mOp.setValueReg(llvmKernelBB);
2318 else
2319 mOp.setValueReg(llvm_prologues[I+1]);
2320 }
2321 else {
2322 mOp.setValueReg(llvm_epilogues[(llvm_epilogues.size()-1-I)]);
2323 }
2324 }
2325 }
2326
2327 DEBUG(std::cerr << "New Prologue Branch: " << *mInst << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002328 }
2329 }
2330
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002331
2332 //Update llvm basic block with our new branch instr
2333 DEBUG(std::cerr << BB->getBasicBlock()->getTerminator() << "\n");
2334 const BranchInst *branchVal = dyn_cast<BranchInst>(BB->getBasicBlock()->getTerminator());
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002335
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002336 if(I == prologues.size()-1) {
2337 TerminatorInst *newBranch = new BranchInst(llvmKernelBB,
2338 llvm_epilogues[(llvm_epilogues.size()-1-I)],
Tanya Lattnera6457502004-10-14 06:04:28 +00002339 branchVal->getCondition(),
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002340 llvm_prologues[I]);
2341 }
2342 else
2343 TerminatorInst *newBranch = new BranchInst(llvm_prologues[I+1],
2344 llvm_epilogues[(llvm_epilogues.size()-1-I)],
Tanya Lattnera6457502004-10-14 06:04:28 +00002345 branchVal->getCondition(),
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002346 llvm_prologues[I]);
2347
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002348 }
2349
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002350 Value *origBranchExit = 0;
Tanya Lattnera6457502004-10-14 06:04:28 +00002351
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002352 //Fix up kernel machine branches
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002353 for(MachineBasicBlock::reverse_iterator mInst = machineKernelBB->rbegin(), mInstEnd = machineKernelBB->rend(); mInst != mInstEnd; ++mInst) {
2354 MachineOpCode OC = mInst->getOpcode();
2355 if(TMI->isBranch(OC)) {
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002356 for(unsigned opNum = 0; opNum < mInst->getNumOperands(); ++opNum) {
2357 MachineOperand &mOp = mInst->getOperand(opNum);
2358
2359 if(mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2360 if(mOp.getVRegValue() == BB->getBasicBlock())
2361 mOp.setValueReg(llvmKernelBB);
2362 else
2363 if(llvm_epilogues.size() > 0) {
2364 assert(origBranchExit == 0 && "There should only be one branch out of the loop");
2365
2366 origBranchExit = mOp.getVRegValue();
2367 mOp.setValueReg(llvm_epilogues[0]);
2368 }
2369 }
Tanya Lattnera6457502004-10-14 06:04:28 +00002370 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002371 }
2372 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002373
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002374 //Update kernelLLVM branches
2375 const BranchInst *branchVal = dyn_cast<BranchInst>(BB->getBasicBlock()->getTerminator());
Tanya Lattnera6457502004-10-14 06:04:28 +00002376
Tanya Lattner260652a2004-10-30 00:39:07 +00002377 assert(llvm_epilogues.size() != 0 && "We must have epilogues!");
2378
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002379 TerminatorInst *newBranch = new BranchInst(llvmKernelBB,
2380 llvm_epilogues[0],
Tanya Lattnera6457502004-10-14 06:04:28 +00002381 branchVal->getCondition(),
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002382 llvmKernelBB);
2383
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002384
2385 //Lastly add unconditional branches for the epilogues
2386 for(unsigned I = 0; I < epilogues.size(); ++I) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00002387
Tanya Lattnera6457502004-10-14 06:04:28 +00002388 //Now since we don't have fall throughs, add a unconditional branch to the next prologue
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002389 if(I != epilogues.size()-1) {
Tanya Lattner420025b2004-10-10 22:44:35 +00002390 BuildMI(epilogues[I], V9::BA, 1).addPCDisp(llvm_epilogues[I+1]);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002391 //Add unconditional branch to end of epilogue
2392 TerminatorInst *newBranch = new BranchInst(llvm_epilogues[I+1],
2393 llvm_epilogues[I]);
2394
Tanya Lattner4cffb582004-05-26 06:27:18 +00002395 }
Tanya Lattnera6457502004-10-14 06:04:28 +00002396 else {
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002397 BuildMI(epilogues[I], V9::BA, 1).addPCDisp(origBranchExit);
Tanya Lattnera6457502004-10-14 06:04:28 +00002398
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002399
Tanya Lattnera6457502004-10-14 06:04:28 +00002400 //Update last epilogue exit branch
2401 BranchInst *branchVal = (BranchInst*) dyn_cast<BranchInst>(BB->getBasicBlock()->getTerminator());
2402 //Find where we are supposed to branch to
2403 BasicBlock *nextBlock = 0;
2404 for(unsigned j=0; j <branchVal->getNumSuccessors(); ++j) {
2405 if(branchVal->getSuccessor(j) != BB->getBasicBlock())
2406 nextBlock = branchVal->getSuccessor(j);
2407 }
2408
2409 assert((nextBlock != 0) && "Next block should not be null!");
2410 TerminatorInst *newBranch = new BranchInst(nextBlock, llvm_epilogues[I]);
2411 }
2412 //Add one more nop!
2413 BuildMI(epilogues[I], V9::NOP, 0);
2414
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002415 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00002416
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002417 //FIX UP Machine BB entry!!
2418 //We are looking at the predecesor of our loop basic block and we want to change its ba instruction
2419
Tanya Lattner4cffb582004-05-26 06:27:18 +00002420
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002421 //Find all llvm basic blocks that branch to the loop entry and change to our first prologue.
2422 const BasicBlock *llvmBB = BB->getBasicBlock();
2423
Tanya Lattner260652a2004-10-30 00:39:07 +00002424 std::vector<const BasicBlock*>Preds (pred_begin(llvmBB), pred_end(llvmBB));
2425
2426 //for(pred_const_iterator P = pred_begin(llvmBB), PE = pred_end(llvmBB); P != PE; ++PE) {
2427 for(std::vector<const BasicBlock*>::iterator P = Preds.begin(), PE = Preds.end(); P != PE; ++P) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002428 if(*P == llvmBB)
2429 continue;
2430 else {
2431 DEBUG(std::cerr << "Found our entry BB\n");
2432 //Get the Terminator instruction for this basic block and print it out
2433 DEBUG(std::cerr << *((*P)->getTerminator()) << "\n");
2434 //Update the terminator
2435 TerminatorInst *term = ((BasicBlock*)*P)->getTerminator();
2436 for(unsigned i=0; i < term->getNumSuccessors(); ++i) {
2437 if(term->getSuccessor(i) == llvmBB) {
2438 DEBUG(std::cerr << "Replacing successor bb\n");
2439 if(llvm_prologues.size() > 0) {
2440 term->setSuccessor(i, llvm_prologues[0]);
2441 //Also update its corresponding machine instruction
2442 MachineCodeForInstruction & tempMvec =
2443 MachineCodeForInstruction::get(term);
2444 for (unsigned j = 0; j < tempMvec.size(); j++) {
2445 MachineInstr *temp = tempMvec[j];
2446 MachineOpCode opc = temp->getOpcode();
2447 if(TMI->isBranch(opc)) {
2448 DEBUG(std::cerr << *temp << "\n");
2449 //Update branch
2450 for(unsigned opNum = 0; opNum < temp->getNumOperands(); ++opNum) {
2451 MachineOperand &mOp = temp->getOperand(opNum);
2452 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2453 mOp.setValueReg(llvm_prologues[0]);
2454 }
2455 }
2456 }
2457 }
2458 }
2459 else {
2460 term->setSuccessor(i, llvmKernelBB);
2461 //Also update its corresponding machine instruction
2462 MachineCodeForInstruction & tempMvec =
2463 MachineCodeForInstruction::get(term);
2464 for (unsigned j = 0; j < tempMvec.size(); j++) {
2465 MachineInstr *temp = tempMvec[j];
2466 MachineOpCode opc = temp->getOpcode();
2467 if(TMI->isBranch(opc)) {
2468 DEBUG(std::cerr << *temp << "\n");
2469 //Update branch
2470 for(unsigned opNum = 0; opNum < temp->getNumOperands(); ++opNum) {
2471 MachineOperand &mOp = temp->getOperand(opNum);
2472 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2473 mOp.setValueReg(llvmKernelBB);
2474 }
2475 }
2476 }
2477 }
2478 }
2479 }
2480 }
2481 break;
2482 }
2483 }
2484
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002485
Tanya Lattner420025b2004-10-10 22:44:35 +00002486 //BB->getParent()->getBasicBlockList().erase(BB);
Tanya Lattner4cffb582004-05-26 06:27:18 +00002487
2488}
2489