blob: f2e442e4866358a42fe87937bc0d6ed16c4dcf3f [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
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001032void ModuloSchedulingPass::searchPath(MSchedGraphNode *node,
1033 std::vector<MSchedGraphNode*> &path,
1034 std::set<MSchedGraphNode*> &nodesToAdd) {
1035 //Push node onto the path
1036 path.push_back(node);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001037
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001038 //Loop over all successors and see if there is a path from this node to
1039 //a recurrence in the partial order, if so.. add all nodes to be added to recc
1040 for(MSchedGraphNode::succ_iterator S = node->succ_begin(), SE = node->succ_end(); S != SE;
1041 ++S) {
1042
1043 //If this node exists in a recurrence already in the partial order, then add all
1044 //nodes in the path to the set of nodes to add
1045 //Check if its already in our partial order, if not add it to the final vector
1046 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(),
1047 PE = partialOrder.end(); PO != PE; ++PO) {
1048
1049 //Check if we should ignore this edge first
1050 if(ignoreEdge(node,*S))
1051 continue;
1052
1053 if(PO->count(*S)) {
1054 nodesToAdd.insert(*S);
1055 }
1056 searchPath(*S, path, nodesToAdd);
1057 }
1058
1059 }
1060
1061 //Pop Node off the path
1062 path.pop_back();
1063}
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001064
1065
1066
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001067void ModuloSchedulingPass::computePartialOrder() {
Tanya Lattnera6ec8f52004-11-24 01:49:10 +00001068
Tanya Lattnerdb40cf12005-02-10 17:02:58 +00001069 TIME_REGION(X, "calculatePartialOrder");
1070
Tanya Lattnera6ec8f52004-11-24 01:49:10 +00001071 //Only push BA branches onto the final node order, we put other branches after it
1072 //FIXME: Should we really be pushing branches on it a specific order instead of relying
1073 //on BA being there?
Tanya Lattner58fe2f02004-11-29 04:39:47 +00001074 std::vector<MSchedGraphNode*> branches;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001075
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001076 //Steps to add a recurrence to the partial order
1077 // 1) Find reccurrence with the highest RecMII. Add it to the partial order.
1078 // 2) For each recurrence with decreasing RecMII, add it to the partial order along with
1079 // any nodes that connect this recurrence to recurrences already in the partial order
1080 for(std::set<std::pair<int, std::vector<MSchedGraphNode*> > >::reverse_iterator
1081 I = recurrenceList.rbegin(), E=recurrenceList.rend(); I !=E; ++I) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001082
Tanya Lattner260652a2004-10-30 00:39:07 +00001083 std::set<MSchedGraphNode*> new_recurrence;
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001084
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001085 //Loop through recurrence and remove any nodes already in the partial order
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001086 for(std::vector<MSchedGraphNode*>::const_iterator N = I->second.begin(),
1087 NE = I->second.end(); N != NE; ++N) {
1088
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001089 bool found = false;
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001090 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(),
1091 PE = partialOrder.end(); PO != PE; ++PO) {
Tanya Lattner260652a2004-10-30 00:39:07 +00001092 if(PO->count(*N))
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001093 found = true;
1094 }
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001095
1096 //Check if its a branch, and remove to handle special
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001097 if(!found) {
Tanya Lattnera6ec8f52004-11-24 01:49:10 +00001098 if((*N)->isBranch()) {
Tanya Lattner58fe2f02004-11-29 04:39:47 +00001099 branches.push_back(*N);
Tanya Lattnera6ec8f52004-11-24 01:49:10 +00001100 }
1101 else
1102 new_recurrence.insert(*N);
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001103 }
1104
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001105 }
Tanya Lattnera6ec8f52004-11-24 01:49:10 +00001106
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001107
1108 if(new_recurrence.size() > 0) {
1109
1110 std::vector<MSchedGraphNode*> path;
1111 std::set<MSchedGraphNode*> nodesToAdd;
1112
1113 //Add nodes that connect this recurrence to recurrences in the partial path
1114 for(std::set<MSchedGraphNode*>::iterator N = new_recurrence.begin(),
1115 NE = new_recurrence.end(); N != NE; ++N)
1116 searchPath(*N, path, nodesToAdd);
1117
1118 //Add nodes to this recurrence if they are not already in the partial order
1119 for(std::set<MSchedGraphNode*>::iterator N = nodesToAdd.begin(), NE = nodesToAdd.end();
1120 N != NE; ++N) {
1121 bool found = false;
1122 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(),
1123 PE = partialOrder.end(); PO != PE; ++PO) {
1124 if(PO->count(*N))
1125 found = true;
1126 }
1127 if(!found) {
1128 assert("FOUND CONNECTOR");
1129 new_recurrence.insert(*N);
1130 }
1131 }
1132
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001133 partialOrder.push_back(new_recurrence);
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001134
1135 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001136 }
1137
1138 //Add any nodes that are not already in the partial order
Tanya Lattner260652a2004-10-30 00:39:07 +00001139 //Add them in a set, one set per connected component
1140 std::set<MSchedGraphNode*> lastNodes;
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001141 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(),
1142 E = nodeToAttributesMap.end(); I != E; ++I) {
1143
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001144 bool found = false;
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001145
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001146 //Check if its already in our partial order, if not add it to the final vector
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001147 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(),
1148 PE = partialOrder.end(); PO != PE; ++PO) {
Tanya Lattner260652a2004-10-30 00:39:07 +00001149 if(PO->count(I->first))
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001150 found = true;
1151 }
Tanya Lattnera6ec8f52004-11-24 01:49:10 +00001152 if(!found) {
1153 if(I->first->isBranch()) {
Tanya Lattner58fe2f02004-11-29 04:39:47 +00001154 if(std::find(branches.begin(), branches.end(), I->first) == branches.end())
1155 branches.push_back(I->first);
1156 }
Tanya Lattnera6ec8f52004-11-24 01:49:10 +00001157 else
1158 lastNodes.insert(I->first);
1159 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001160 }
1161
Tanya Lattner260652a2004-10-30 00:39:07 +00001162 //Break up remaining nodes that are not in the partial order
1163 //into their connected compoenents
1164 while(lastNodes.size() > 0) {
1165 std::set<MSchedGraphNode*> ccSet;
1166 connectedComponentSet(*(lastNodes.begin()),ccSet, lastNodes);
1167 if(ccSet.size() > 0)
1168 partialOrder.push_back(ccSet);
1169 }
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001170
Tanya Lattnera6ec8f52004-11-24 01:49:10 +00001171 //Clean up branches by putting them in final order
Tanya Lattner58fe2f02004-11-29 04:39:47 +00001172 std::map<unsigned, MSchedGraphNode*> branchOrder;
1173 for(std::vector<MSchedGraphNode*>::iterator I = branches.begin(), E = branches.end(); I != E; ++I)
1174 branchOrder[(*I)->getIndex()] = *I;
1175
1176 for(std::map<unsigned, MSchedGraphNode*>::reverse_iterator I = branchOrder.rbegin(), E = branchOrder.rend(); I != E; ++I)
1177 FinalNodeOrder.push_back(I->second);
1178
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001179}
1180
1181
Tanya Lattner260652a2004-10-30 00:39:07 +00001182void ModuloSchedulingPass::connectedComponentSet(MSchedGraphNode *node, std::set<MSchedGraphNode*> &ccSet, std::set<MSchedGraphNode*> &lastNodes) {
1183
Tanya Lattnera6ec8f52004-11-24 01:49:10 +00001184//Add to final set
1185if( !ccSet.count(node) && lastNodes.count(node)) {
Tanya Lattner260652a2004-10-30 00:39:07 +00001186 lastNodes.erase(node);
Tanya Lattnera6ec8f52004-11-24 01:49:10 +00001187if(node->isBranch())
1188 FinalNodeOrder.push_back(node);
1189 else
1190 ccSet.insert(node);
Tanya Lattner260652a2004-10-30 00:39:07 +00001191 }
1192 else
1193 return;
1194
1195 //Loop over successors and recurse if we have not seen this node before
1196 for(MSchedGraphNode::succ_iterator node_succ = node->succ_begin(), end=node->succ_end(); node_succ != end; ++node_succ) {
1197 connectedComponentSet(*node_succ, ccSet, lastNodes);
1198 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001199
Tanya Lattner260652a2004-10-30 00:39:07 +00001200}
1201
1202void ModuloSchedulingPass::predIntersect(std::set<MSchedGraphNode*> &CurrentSet, std::set<MSchedGraphNode*> &IntersectResult) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001203
1204 for(unsigned j=0; j < FinalNodeOrder.size(); ++j) {
1205 for(MSchedGraphNode::pred_iterator P = FinalNodeOrder[j]->pred_begin(),
1206 E = FinalNodeOrder[j]->pred_end(); P != E; ++P) {
1207
1208 //Check if we are supposed to ignore this edge or not
1209 if(ignoreEdge(*P,FinalNodeOrder[j]))
1210 continue;
1211
Tanya Lattner260652a2004-10-30 00:39:07 +00001212 if(CurrentSet.count(*P))
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001213 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), *P) == FinalNodeOrder.end())
Tanya Lattner260652a2004-10-30 00:39:07 +00001214 IntersectResult.insert(*P);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001215 }
1216 }
1217}
1218
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001219
Tanya Lattner260652a2004-10-30 00:39:07 +00001220
1221
1222
1223void ModuloSchedulingPass::succIntersect(std::set<MSchedGraphNode*> &CurrentSet, std::set<MSchedGraphNode*> &IntersectResult) {
1224
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001225 for(unsigned j=0; j < FinalNodeOrder.size(); ++j) {
1226 for(MSchedGraphNode::succ_iterator P = FinalNodeOrder[j]->succ_begin(),
1227 E = FinalNodeOrder[j]->succ_end(); P != E; ++P) {
1228
1229 //Check if we are supposed to ignore this edge or not
1230 if(ignoreEdge(FinalNodeOrder[j],*P))
1231 continue;
1232
Tanya Lattner260652a2004-10-30 00:39:07 +00001233 if(CurrentSet.count(*P))
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001234 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), *P) == FinalNodeOrder.end())
Tanya Lattner260652a2004-10-30 00:39:07 +00001235 IntersectResult.insert(*P);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001236 }
1237 }
1238}
1239
Tanya Lattner260652a2004-10-30 00:39:07 +00001240void dumpIntersection(std::set<MSchedGraphNode*> &IntersectCurrent) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001241 std::cerr << "Intersection (";
Tanya Lattner260652a2004-10-30 00:39:07 +00001242 for(std::set<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(), E = IntersectCurrent.end(); I != E; ++I)
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001243 std::cerr << **I << ", ";
1244 std::cerr << ")\n";
1245}
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001246
1247
1248
1249void ModuloSchedulingPass::orderNodes() {
1250
Tanya Lattnerdb40cf12005-02-10 17:02:58 +00001251 TIME_REGION(X, "orderNodes");
1252
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001253 int BOTTOM_UP = 0;
1254 int TOP_DOWN = 1;
1255
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001256 //Set default order
1257 int order = BOTTOM_UP;
1258
Tanya Lattnera6ec8f52004-11-24 01:49:10 +00001259
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001260 //Loop over all the sets and place them in the final node order
Tanya Lattner260652a2004-10-30 00:39:07 +00001261 for(std::vector<std::set<MSchedGraphNode*> >::iterator CurrentSet = partialOrder.begin(), E= partialOrder.end(); CurrentSet != E; ++CurrentSet) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001262
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001263 DEBUG(std::cerr << "Processing set in S\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001264 DEBUG(dumpIntersection(*CurrentSet));
1265
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001266 //Result of intersection
Tanya Lattner260652a2004-10-30 00:39:07 +00001267 std::set<MSchedGraphNode*> IntersectCurrent;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001268
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001269 predIntersect(*CurrentSet, IntersectCurrent);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001270
1271 //If the intersection of predecessor and current set is not empty
1272 //sort nodes bottom up
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001273 if(IntersectCurrent.size() != 0) {
1274 DEBUG(std::cerr << "Final Node Order Predecessors and Current Set interesection is NOT empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001275 order = BOTTOM_UP;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001276 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001277 //If empty, use successors
1278 else {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001279 DEBUG(std::cerr << "Final Node Order Predecessors and Current Set interesection is empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001280
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001281 succIntersect(*CurrentSet, IntersectCurrent);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001282
1283 //sort top-down
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001284 if(IntersectCurrent.size() != 0) {
1285 DEBUG(std::cerr << "Final Node Order Successors and Current Set interesection is NOT empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001286 order = TOP_DOWN;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001287 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001288 else {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001289 DEBUG(std::cerr << "Final Node Order Successors and Current Set interesection is empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001290 //Find node with max ASAP in current Set
1291 MSchedGraphNode *node;
1292 int maxASAP = 0;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001293 DEBUG(std::cerr << "Using current set of size " << CurrentSet->size() << "to find max ASAP\n");
Tanya Lattner260652a2004-10-30 00:39:07 +00001294 for(std::set<MSchedGraphNode*>::iterator J = CurrentSet->begin(), JE = CurrentSet->end(); J != JE; ++J) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001295 //Get node attributes
Tanya Lattner260652a2004-10-30 00:39:07 +00001296 MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*J)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001297 //assert(nodeAttr != nodeToAttributesMap.end() && "Node not in attributes map!");
Tanya Lattner260652a2004-10-30 00:39:07 +00001298
1299 if(maxASAP <= nodeAttr.ASAP) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001300 maxASAP = nodeAttr.ASAP;
Tanya Lattner260652a2004-10-30 00:39:07 +00001301 node = *J;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001302 }
1303 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001304 assert(node != 0 && "In node ordering node should not be null");
Tanya Lattner260652a2004-10-30 00:39:07 +00001305 IntersectCurrent.insert(node);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001306 order = BOTTOM_UP;
1307 }
1308 }
1309
1310 //Repeat until all nodes are put into the final order from current set
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001311 while(IntersectCurrent.size() > 0) {
1312
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001313 if(order == TOP_DOWN) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001314 DEBUG(std::cerr << "Order is TOP DOWN\n");
1315
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001316 while(IntersectCurrent.size() > 0) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001317 DEBUG(std::cerr << "Intersection is not empty, so find heighest height\n");
1318
1319 int MOB = 0;
1320 int height = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +00001321 MSchedGraphNode *highestHeightNode = *(IntersectCurrent.begin());
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001322
1323 //Find node in intersection with highest heigh and lowest MOB
Tanya Lattner260652a2004-10-30 00:39:07 +00001324 for(std::set<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(),
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001325 E = IntersectCurrent.end(); I != E; ++I) {
1326
1327 //Get current nodes properties
1328 MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*I)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001329
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001330 if(height < nodeAttr.height) {
1331 highestHeightNode = *I;
1332 height = nodeAttr.height;
1333 MOB = nodeAttr.MOB;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001334 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001335 else if(height == nodeAttr.height) {
1336 if(MOB > nodeAttr.height) {
1337 highestHeightNode = *I;
1338 height = nodeAttr.height;
1339 MOB = nodeAttr.MOB;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001340 }
1341 }
1342 }
1343
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001344 //Append our node with greatest height to the NodeOrder
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001345 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), highestHeightNode) == FinalNodeOrder.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001346 DEBUG(std::cerr << "Adding node to Final Order: " << *highestHeightNode << "\n");
1347 FinalNodeOrder.push_back(highestHeightNode);
1348 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001349
1350 //Remove V from IntersectOrder
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001351 IntersectCurrent.erase(std::find(IntersectCurrent.begin(),
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001352 IntersectCurrent.end(), highestHeightNode));
1353
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001354
1355 //Intersect V's successors with CurrentSet
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001356 for(MSchedGraphNode::succ_iterator P = highestHeightNode->succ_begin(),
1357 E = highestHeightNode->succ_end(); P != E; ++P) {
1358 //if(lower_bound(CurrentSet->begin(),
1359 // CurrentSet->end(), *P) != CurrentSet->end()) {
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001360 if(std::find(CurrentSet->begin(), CurrentSet->end(), *P) != CurrentSet->end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001361 if(ignoreEdge(highestHeightNode, *P))
1362 continue;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001363 //If not already in Intersect, add
Tanya Lattner260652a2004-10-30 00:39:07 +00001364 if(!IntersectCurrent.count(*P))
1365 IntersectCurrent.insert(*P);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001366 }
1367 }
1368 } //End while loop over Intersect Size
1369
1370 //Change direction
1371 order = BOTTOM_UP;
1372
1373 //Reset Intersect to reflect changes in OrderNodes
1374 IntersectCurrent.clear();
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001375 predIntersect(*CurrentSet, IntersectCurrent);
1376
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001377 } //End If TOP_DOWN
1378
1379 //Begin if BOTTOM_UP
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001380 else {
1381 DEBUG(std::cerr << "Order is BOTTOM UP\n");
1382 while(IntersectCurrent.size() > 0) {
1383 DEBUG(std::cerr << "Intersection of size " << IntersectCurrent.size() << ", finding highest depth\n");
1384
1385 //dump intersection
1386 DEBUG(dumpIntersection(IntersectCurrent));
1387 //Get node with highest depth, if a tie, use one with lowest
1388 //MOB
1389 int MOB = 0;
1390 int depth = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +00001391 MSchedGraphNode *highestDepthNode = *(IntersectCurrent.begin());
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001392
Tanya Lattner260652a2004-10-30 00:39:07 +00001393 for(std::set<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(),
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001394 E = IntersectCurrent.end(); I != E; ++I) {
1395 //Find node attribute in graph
1396 MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*I)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001397
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001398 if(depth < nodeAttr.depth) {
1399 highestDepthNode = *I;
1400 depth = nodeAttr.depth;
1401 MOB = nodeAttr.MOB;
1402 }
1403 else if(depth == nodeAttr.depth) {
1404 if(MOB > nodeAttr.MOB) {
1405 highestDepthNode = *I;
1406 depth = nodeAttr.depth;
1407 MOB = nodeAttr.MOB;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001408 }
1409 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001410 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001411
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001412
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001413
1414 //Append highest depth node to the NodeOrder
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001415 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), highestDepthNode) == FinalNodeOrder.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001416 DEBUG(std::cerr << "Adding node to Final Order: " << *highestDepthNode << "\n");
1417 FinalNodeOrder.push_back(highestDepthNode);
1418 }
1419 //Remove heightestDepthNode from IntersectOrder
Tanya Lattner260652a2004-10-30 00:39:07 +00001420 IntersectCurrent.erase(highestDepthNode);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001421
1422
1423 //Intersect heightDepthNode's pred with CurrentSet
1424 for(MSchedGraphNode::pred_iterator P = highestDepthNode->pred_begin(),
1425 E = highestDepthNode->pred_end(); P != E; ++P) {
Tanya Lattner260652a2004-10-30 00:39:07 +00001426 if(CurrentSet->count(*P)) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001427 if(ignoreEdge(*P, highestDepthNode))
1428 continue;
1429
1430 //If not already in Intersect, add
Tanya Lattner260652a2004-10-30 00:39:07 +00001431 if(!IntersectCurrent.count(*P))
1432 IntersectCurrent.insert(*P);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001433 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001434 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001435
1436 } //End while loop over Intersect Size
1437
1438 //Change order
1439 order = TOP_DOWN;
1440
1441 //Reset IntersectCurrent to reflect changes in OrderNodes
1442 IntersectCurrent.clear();
1443 succIntersect(*CurrentSet, IntersectCurrent);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001444 } //End if BOTTOM_DOWN
1445
Tanya Lattner420025b2004-10-10 22:44:35 +00001446 DEBUG(std::cerr << "Current Intersection Size: " << IntersectCurrent.size() << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001447 }
1448 //End Wrapping while loop
Tanya Lattner420025b2004-10-10 22:44:35 +00001449 DEBUG(std::cerr << "Ending Size of Current Set: " << CurrentSet->size() << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001450 }//End for over all sets of nodes
Tanya Lattner420025b2004-10-10 22:44:35 +00001451
1452 //FIXME: As the algorithm stands it will NEVER add an instruction such as ba (with no
1453 //data dependencies) to the final order. We add this manually. It will always be
1454 //in the last set of S since its not part of a recurrence
1455 //Loop over all the sets and place them in the final node order
Tanya Lattner260652a2004-10-30 00:39:07 +00001456 std::vector<std::set<MSchedGraphNode*> > ::reverse_iterator LastSet = partialOrder.rbegin();
1457 for(std::set<MSchedGraphNode*>::iterator CurrentNode = LastSet->begin(), LastNode = LastSet->end();
Tanya Lattner420025b2004-10-10 22:44:35 +00001458 CurrentNode != LastNode; ++CurrentNode) {
1459 if((*CurrentNode)->getInst()->getOpcode() == V9::BA)
1460 FinalNodeOrder.push_back(*CurrentNode);
1461 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001462 //Return final Order
1463 //return FinalNodeOrder;
1464}
1465
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001466bool ModuloSchedulingPass::computeSchedule() {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001467
Tanya Lattnerdb40cf12005-02-10 17:02:58 +00001468 TIME_REGION(X, "computeSchedule");
1469
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001470 bool success = false;
1471
Tanya Lattner260652a2004-10-30 00:39:07 +00001472 //FIXME: Should be set to max II of the original loop
1473 //Cap II in order to prevent infinite loop
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001474 int capII = 100;
Tanya Lattner260652a2004-10-30 00:39:07 +00001475
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001476 while(!success) {
Tanya Lattner58fe2f02004-11-29 04:39:47 +00001477
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001478 //Keep track of branches, but do not insert into the schedule
1479 std::vector<MSchedGraphNode*> branches;
Tanya Lattner58fe2f02004-11-29 04:39:47 +00001480
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001481 //Loop over the final node order and process each node
1482 for(std::vector<MSchedGraphNode*>::iterator I = FinalNodeOrder.begin(),
1483 E = FinalNodeOrder.end(); I != E; ++I) {
1484
1485 //CalculateEarly and Late start
1486 int EarlyStart = -1;
1487 int LateStart = 99999; //Set to something higher then we would ever expect (FIXME)
1488 bool hasSucc = false;
1489 bool hasPred = false;
Tanya Lattner4cffb582004-05-26 06:27:18 +00001490
1491 if(!(*I)->isBranch()) {
1492 //Loop over nodes in the schedule and determine if they are predecessors
1493 //or successors of the node we are trying to schedule
1494 for(MSSchedule::schedule_iterator nodesByCycle = schedule.begin(), nodesByCycleEnd = schedule.end();
1495 nodesByCycle != nodesByCycleEnd; ++nodesByCycle) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001496
Tanya Lattner4cffb582004-05-26 06:27:18 +00001497 //For this cycle, get the vector of nodes schedule and loop over it
1498 for(std::vector<MSchedGraphNode*>::iterator schedNode = nodesByCycle->second.begin(), SNE = nodesByCycle->second.end(); schedNode != SNE; ++schedNode) {
1499
1500 if((*I)->isPredecessor(*schedNode)) {
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001501 int diff = (*I)->getInEdge(*schedNode).getIteDiff();
1502 int ES_Temp = nodesByCycle->first + (*schedNode)->getLatency() - diff * II;
1503 DEBUG(std::cerr << "Diff: " << diff << " Cycle: " << nodesByCycle->first << "\n");
1504 DEBUG(std::cerr << "Temp EarlyStart: " << ES_Temp << " Prev EarlyStart: " << EarlyStart << "\n");
1505 EarlyStart = std::max(EarlyStart, ES_Temp);
1506 hasPred = true;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001507 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001508 if((*I)->isSuccessor(*schedNode)) {
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001509 int diff = (*schedNode)->getInEdge(*I).getIteDiff();
1510 int LS_Temp = nodesByCycle->first - (*I)->getLatency() + diff * II;
1511 DEBUG(std::cerr << "Diff: " << diff << " Cycle: " << nodesByCycle->first << "\n");
1512 DEBUG(std::cerr << "Temp LateStart: " << LS_Temp << " Prev LateStart: " << LateStart << "\n");
1513 LateStart = std::min(LateStart, LS_Temp);
1514 hasSucc = true;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001515 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001516 }
1517 }
1518 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001519 else {
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001520 branches.push_back(*I);
1521 continue;
1522 }
1523
1524 //Check if this node is a pred or succ to a branch, and restrict its placement
1525 //even though the branch is not in the schedule
1526 int count = branches.size();
1527 for(std::vector<MSchedGraphNode*>::iterator B = branches.begin(), BE = branches.end();
1528 B != BE; ++B) {
1529 if((*I)->isPredecessor(*B)) {
1530 int diff = (*I)->getInEdge(*B).getIteDiff();
1531 int ES_Temp = (II+count) + (*B)->getLatency() - diff * II;
1532 DEBUG(std::cerr << "Diff: " << diff << " Cycle: " << (II+count) << "\n");
1533 DEBUG(std::cerr << "Temp EarlyStart: " << ES_Temp << " Prev EarlyStart: " << EarlyStart << "\n");
1534 EarlyStart = std::max(EarlyStart, ES_Temp);
1535 hasPred = true;
Tanya Lattner420025b2004-10-10 22:44:35 +00001536 }
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001537
1538 if((*I)->isSuccessor(*B)) {
1539 int diff = (*B)->getInEdge(*I).getIteDiff();
1540 int LS_Temp = (II+count) - (*I)->getLatency() + diff * II;
1541 DEBUG(std::cerr << "Diff: " << diff << " Cycle: " << (II+count) << "\n");
1542 DEBUG(std::cerr << "Temp LateStart: " << LS_Temp << " Prev LateStart: " << LateStart << "\n");
1543 LateStart = std::min(LateStart, LS_Temp);
1544 hasSucc = true;
Tanya Lattner420025b2004-10-10 22:44:35 +00001545 }
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001546
1547 count--;
Tanya Lattner4cffb582004-05-26 06:27:18 +00001548 }
1549
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001550 //Check if the node has no pred or successors and set Early Start to its ASAP
1551 if(!hasSucc && !hasPred)
1552 EarlyStart = nodeToAttributesMap.find(*I)->second.ASAP;
1553
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001554 DEBUG(std::cerr << "Has Successors: " << hasSucc << ", Has Pred: " << hasPred << "\n");
1555 DEBUG(std::cerr << "EarlyStart: " << EarlyStart << ", LateStart: " << LateStart << "\n");
1556
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001557 //Now, try to schedule this node depending upon its pred and successor in the schedule
1558 //already
1559 if(!hasSucc && hasPred)
1560 success = scheduleNode(*I, EarlyStart, (EarlyStart + II -1));
1561 else if(!hasPred && hasSucc)
1562 success = scheduleNode(*I, LateStart, (LateStart - II +1));
Tanya Lattner01114742005-01-18 04:15:41 +00001563 else if(hasPred && hasSucc) {
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001564 if(EarlyStart > LateStart) {
1565 //success = false;
1566 LateStart = EarlyStart;
1567 DEBUG(std::cerr << "Early Start can not be later then the late start cycle, schedule fails\n");
1568 }
1569 //else
1570 success = scheduleNode(*I, EarlyStart, std::min(LateStart, (EarlyStart + II -1)));
Tanya Lattner01114742005-01-18 04:15:41 +00001571 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001572 else
1573 success = scheduleNode(*I, EarlyStart, EarlyStart + II - 1);
1574
1575 if(!success) {
Tanya Lattnere1df2122004-11-22 20:41:24 +00001576 ++IncreasedII;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001577 ++II;
1578 schedule.clear();
1579 break;
1580 }
1581
1582 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001583
Tanya Lattner260652a2004-10-30 00:39:07 +00001584 if(success) {
1585 DEBUG(std::cerr << "Constructing Schedule Kernel\n");
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001586 success = schedule.constructKernel(II, branches);
Tanya Lattner260652a2004-10-30 00:39:07 +00001587 DEBUG(std::cerr << "Done Constructing Schedule Kernel\n");
1588 if(!success) {
Tanya Lattnere1df2122004-11-22 20:41:24 +00001589 ++IncreasedII;
Tanya Lattner260652a2004-10-30 00:39:07 +00001590 ++II;
1591 schedule.clear();
1592 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001593 }
Tanya Lattner260652a2004-10-30 00:39:07 +00001594
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001595 if(II >= capII) {
1596 DEBUG(std::cerr << "Maximum II reached, giving up\n");
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001597 return false;
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001598 }
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001599
Tanya Lattner260652a2004-10-30 00:39:07 +00001600 assert(II < capII && "The II should not exceed the original loop number of cycles");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001601 }
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001602 return true;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001603}
1604
1605
1606bool ModuloSchedulingPass::scheduleNode(MSchedGraphNode *node,
1607 int start, int end) {
1608 bool success = false;
1609
1610 DEBUG(std::cerr << *node << " (Start Cycle: " << start << ", End Cycle: " << end << ")\n");
1611
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001612 //Make sure start and end are not negative
Tanya Lattner260652a2004-10-30 00:39:07 +00001613 if(start < 0) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001614 start = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +00001615
1616 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001617 if(end < 0)
1618 end = 0;
1619
1620 bool forward = true;
1621 if(start > end)
1622 forward = false;
1623
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001624 bool increaseSC = true;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001625 int cycle = start ;
1626
1627
1628 while(increaseSC) {
1629
1630 increaseSC = false;
1631
Tanya Lattner4cffb582004-05-26 06:27:18 +00001632 increaseSC = schedule.insert(node, cycle);
1633
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001634 if(!increaseSC)
1635 return true;
1636
1637 //Increment cycle to try again
1638 if(forward) {
1639 ++cycle;
1640 DEBUG(std::cerr << "Increase cycle: " << cycle << "\n");
1641 if(cycle > end)
1642 return false;
1643 }
1644 else {
1645 --cycle;
1646 DEBUG(std::cerr << "Decrease cycle: " << cycle << "\n");
1647 if(cycle < end)
1648 return false;
1649 }
1650 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001651
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001652 return success;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001653}
Tanya Lattner4cffb582004-05-26 06:27:18 +00001654
Tanya Lattner420025b2004-10-10 22:44:35 +00001655void 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 +00001656
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001657 //Keep a map to easily know whats in the kernel
Tanya Lattner4cffb582004-05-26 06:27:18 +00001658 std::map<int, std::set<const MachineInstr*> > inKernel;
1659 int maxStageCount = 0;
1660
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001661 //Keep a map of new values we consumed in case they need to be added back
1662 std::map<Value*, std::map<int, Value*> > consumedValues;
1663
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001664 MSchedGraphNode *branch = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +00001665 MSchedGraphNode *BAbranch = 0;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001666
Tanya Lattnere1df2122004-11-22 20:41:24 +00001667 schedule.print(std::cerr);
1668
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001669 std::vector<MSchedGraphNode*> branches;
1670
Tanya Lattner4cffb582004-05-26 06:27:18 +00001671 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
1672 maxStageCount = std::max(maxStageCount, I->second);
1673
1674 //Ignore the branch, we will handle this separately
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001675 if(I->first->isBranch()) {
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001676 branches.push_back(I->first);
Tanya Lattner4cffb582004-05-26 06:27:18 +00001677 continue;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001678 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001679
1680 //Put int the map so we know what instructions in each stage are in the kernel
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001681 DEBUG(std::cerr << "Inserting instruction " << *(I->first->getInst()) << " into map at stage " << I->second << "\n");
1682 inKernel[I->second].insert(I->first->getInst());
Tanya Lattner4cffb582004-05-26 06:27:18 +00001683 }
1684
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001685 //Get target information to look at machine operands
1686 const TargetInstrInfo *mii = target.getInstrInfo();
1687
1688 //Now write the prologues
1689 for(int i = 0; i < maxStageCount; ++i) {
1690 BasicBlock *llvmBB = new BasicBlock("PROLOGUE", (Function*) (origBB->getBasicBlock()->getParent()));
Tanya Lattner4cffb582004-05-26 06:27:18 +00001691 MachineBasicBlock *machineBB = new MachineBasicBlock(llvmBB);
1692
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001693 DEBUG(std::cerr << "i=" << i << "\n");
1694 for(int j = 0; j <= i; ++j) {
1695 for(MachineBasicBlock::const_iterator MI = origBB->begin(), ME = origBB->end(); ME != MI; ++MI) {
1696 if(inKernel[j].count(&*MI)) {
Tanya Lattner420025b2004-10-10 22:44:35 +00001697 MachineInstr *instClone = MI->clone();
1698 machineBB->push_back(instClone);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001699
Tanya Lattner420025b2004-10-10 22:44:35 +00001700 DEBUG(std::cerr << "Cloning: " << *MI << "\n");
1701
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001702 Instruction *tmp;
1703
1704 //After cloning, we may need to save the value that this instruction defines
1705 for(unsigned opNum=0; opNum < MI->getNumOperands(); ++opNum) {
1706 //get machine operand
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001707 MachineOperand &mOp = instClone->getOperand(opNum);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001708 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef()) {
1709
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001710 //Check if this is a value we should save
1711 if(valuesToSave.count(mOp.getVRegValue())) {
1712 //Save copy in tmpInstruction
1713 tmp = new TmpInstruction(mOp.getVRegValue());
1714
Tanya Lattner80f08552004-11-02 21:04:56 +00001715 //Add TmpInstruction to safe LLVM Instruction MCFI
1716 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001717 tempMvec.addTemp((Value*) tmp);
1718
Tanya Lattner420025b2004-10-10 22:44:35 +00001719 DEBUG(std::cerr << "Value: " << *(mOp.getVRegValue()) << " New Value: " << *tmp << " Stage: " << i << "\n");
1720
1721 newValues[mOp.getVRegValue()][i]= tmp;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001722 newValLocation[tmp] = machineBB;
1723
Tanya Lattner420025b2004-10-10 22:44:35 +00001724 DEBUG(std::cerr << "Machine Instr Operands: " << *(mOp.getVRegValue()) << ", 0, " << *tmp << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001725
1726 //Create machine instruction and put int machineBB
1727 MachineInstr *saveValue = BuildMI(machineBB, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
1728
1729 DEBUG(std::cerr << "Created new machine instr: " << *saveValue << "\n");
1730 }
1731 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001732
1733 //We may also need to update the value that we use if its from an earlier prologue
1734 if(j != 0) {
1735 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse()) {
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001736 if(newValues.count(mOp.getVRegValue())) {
1737 if(newValues[mOp.getVRegValue()].count(i-1)) {
1738 Value *oldV = mOp.getVRegValue();
Tanya Lattner420025b2004-10-10 22:44:35 +00001739 DEBUG(std::cerr << "Replaced this value: " << mOp.getVRegValue() << " With:" << (newValues[mOp.getVRegValue()][i-1]) << "\n");
1740 //Update the operand with the right value
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001741 mOp.setValueReg(newValues[mOp.getVRegValue()][i-1]);
1742
1743 //Remove this value since we have consumed it
1744 //NOTE: Should this only be done if j != maxStage?
1745 consumedValues[oldV][i-1] = (newValues[oldV][i-1]);
1746 DEBUG(std::cerr << "Deleted value: " << consumedValues[oldV][i-1] << "\n");
1747 newValues[oldV].erase(i-1);
Tanya Lattner420025b2004-10-10 22:44:35 +00001748 }
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001749 }
1750 else
1751 if(consumedValues.count(mOp.getVRegValue()))
1752 assert(!consumedValues[mOp.getVRegValue()].count(i-1) && "Found a case where we need the value");
Tanya Lattner420025b2004-10-10 22:44:35 +00001753 }
1754 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001755 }
1756 }
Tanya Lattner20890832004-05-28 20:14:12 +00001757 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001758 }
1759
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001760
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001761 for(std::vector<MSchedGraphNode*>::iterator BR = branches.begin(), BE = branches.end(); BR != BE; ++BR) {
1762
1763 //Stick in branch at the end
1764 machineBB->push_back((*BR)->getInst()->clone());
Tanya Lattner260652a2004-10-30 00:39:07 +00001765
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001766 //Add nop
1767 BuildMI(machineBB, V9::NOP, 0);
1768 }
Tanya Lattner260652a2004-10-30 00:39:07 +00001769
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001770
1771 (((MachineBasicBlock*)origBB)->getParent())->getBasicBlockList().push_back(machineBB);
Tanya Lattner4cffb582004-05-26 06:27:18 +00001772 prologues.push_back(machineBB);
1773 llvm_prologues.push_back(llvmBB);
1774 }
1775}
1776
Tanya Lattner420025b2004-10-10 22:44:35 +00001777void 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 +00001778
Tanya Lattner20890832004-05-28 20:14:12 +00001779 std::map<int, std::set<const MachineInstr*> > inKernel;
Tanya Lattner420025b2004-10-10 22:44:35 +00001780
Tanya Lattner20890832004-05-28 20:14:12 +00001781 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
Tanya Lattner20890832004-05-28 20:14:12 +00001782
1783 //Ignore the branch, we will handle this separately
1784 if(I->first->isBranch())
1785 continue;
1786
1787 //Put int the map so we know what instructions in each stage are in the kernel
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001788 inKernel[I->second].insert(I->first->getInst());
Tanya Lattner20890832004-05-28 20:14:12 +00001789 }
1790
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001791 std::map<Value*, Value*> valPHIs;
1792
Tanya Lattner420025b2004-10-10 22:44:35 +00001793 //some debug stuff, will remove later
1794 DEBUG(for(std::map<Value*, std::map<int, Value*> >::iterator V = newValues.begin(), E = newValues.end(); V !=E; ++V) {
1795 std::cerr << "Old Value: " << *(V->first) << "\n";
1796 for(std::map<int, Value*>::iterator I = V->second.begin(), IE = V->second.end(); I != IE; ++I)
1797 std::cerr << "Stage: " << I->first << " Value: " << *(I->second) << "\n";
1798 });
1799
1800 //some debug stuff, will remove later
1801 DEBUG(for(std::map<Value*, std::map<int, Value*> >::iterator V = kernelPHIs.begin(), E = kernelPHIs.end(); V !=E; ++V) {
1802 std::cerr << "Old Value: " << *(V->first) << "\n";
1803 for(std::map<int, Value*>::iterator I = V->second.begin(), IE = V->second.end(); I != IE; ++I)
1804 std::cerr << "Stage: " << I->first << " Value: " << *(I->second) << "\n";
1805 });
1806
Tanya Lattner20890832004-05-28 20:14:12 +00001807 //Now write the epilogues
Tanya Lattner420025b2004-10-10 22:44:35 +00001808 for(int i = schedule.getMaxStage()-1; i >= 0; --i) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001809 BasicBlock *llvmBB = new BasicBlock("EPILOGUE", (Function*) (origBB->getBasicBlock()->getParent()));
Tanya Lattner20890832004-05-28 20:14:12 +00001810 MachineBasicBlock *machineBB = new MachineBasicBlock(llvmBB);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001811
Tanya Lattner420025b2004-10-10 22:44:35 +00001812 DEBUG(std::cerr << " Epilogue #: " << i << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001813
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001814
Tanya Lattnera6457502004-10-14 06:04:28 +00001815 std::map<Value*, int> inEpilogue;
Tanya Lattner420025b2004-10-10 22:44:35 +00001816
1817 for(MachineBasicBlock::const_iterator MI = origBB->begin(), ME = origBB->end(); ME != MI; ++MI) {
1818 for(int j=schedule.getMaxStage(); j > i; --j) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001819 if(inKernel[j].count(&*MI)) {
1820 DEBUG(std::cerr << "Cloning instruction " << *MI << "\n");
1821 MachineInstr *clone = MI->clone();
1822
1823 //Update operands that need to use the result from the phi
Tanya Lattner420025b2004-10-10 22:44:35 +00001824 for(unsigned opNum=0; opNum < clone->getNumOperands(); ++opNum) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001825 //get machine operand
Tanya Lattner420025b2004-10-10 22:44:35 +00001826 const MachineOperand &mOp = clone->getOperand(opNum);
Tanya Lattner420025b2004-10-10 22:44:35 +00001827
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001828 if((mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse())) {
Tanya Lattner420025b2004-10-10 22:44:35 +00001829
1830 DEBUG(std::cerr << "Writing PHI for " << *(mOp.getVRegValue()) << "\n");
Tanya Lattnera6457502004-10-14 06:04:28 +00001831
1832 //If this is the last instructions for the max iterations ago, don't update operands
1833 if(inEpilogue.count(mOp.getVRegValue()))
1834 if(inEpilogue[mOp.getVRegValue()] == i)
1835 continue;
Tanya Lattner420025b2004-10-10 22:44:35 +00001836
1837 //Quickly write appropriate phis for this operand
1838 if(newValues.count(mOp.getVRegValue())) {
1839 if(newValues[mOp.getVRegValue()].count(i)) {
1840 Instruction *tmp = new TmpInstruction(newValues[mOp.getVRegValue()][i]);
Tanya Lattnera6457502004-10-14 06:04:28 +00001841
1842 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00001843 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001844 tempMvec.addTemp((Value*) tmp);
1845
Tanya Lattner420025b2004-10-10 22:44:35 +00001846 MachineInstr *saveValue = BuildMI(machineBB, V9::PHI, 3).addReg(newValues[mOp.getVRegValue()][i]).addReg(kernelPHIs[mOp.getVRegValue()][i]).addRegDef(tmp);
1847 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
1848 valPHIs[mOp.getVRegValue()] = tmp;
1849 }
1850 }
1851
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001852 if(valPHIs.count(mOp.getVRegValue())) {
1853 //Update the operand in the cloned instruction
Tanya Lattner420025b2004-10-10 22:44:35 +00001854 clone->getOperand(opNum).setValueReg(valPHIs[mOp.getVRegValue()]);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001855 }
1856 }
Tanya Lattnera6457502004-10-14 06:04:28 +00001857 else if((mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef())) {
1858 inEpilogue[mOp.getVRegValue()] = i;
1859 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001860 }
1861 machineBB->push_back(clone);
1862 }
1863 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001864 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001865
Tanya Lattner20890832004-05-28 20:14:12 +00001866 (((MachineBasicBlock*)origBB)->getParent())->getBasicBlockList().push_back(machineBB);
1867 epilogues.push_back(machineBB);
1868 llvm_epilogues.push_back(llvmBB);
Tanya Lattner420025b2004-10-10 22:44:35 +00001869
1870 DEBUG(std::cerr << "EPILOGUE #" << i << "\n");
1871 DEBUG(machineBB->print(std::cerr));
Tanya Lattner20890832004-05-28 20:14:12 +00001872 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001873}
1874
Tanya Lattner420025b2004-10-10 22:44:35 +00001875void 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 +00001876
1877 //Keep track of operands that are read and saved from a previous iteration. The new clone
1878 //instruction will use the result of the phi instead.
1879 std::map<Value*, Value*> finalPHIValue;
1880 std::map<Value*, Value*> kernelValue;
1881
Tanya Lattnerf3fa55f2004-12-03 05:25:22 +00001882 //Branches are a special case
1883 std::vector<MachineInstr*> branches;
1884
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001885 //Create TmpInstructions for the final phis
1886 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
1887
Tanya Lattner420025b2004-10-10 22:44:35 +00001888 DEBUG(std::cerr << "Stage: " << I->second << " Inst: " << *(I->first->getInst()) << "\n";);
1889
Tanya Lattnerf3fa55f2004-12-03 05:25:22 +00001890 if(I->first->isBranch()) {
1891 //Clone instruction
1892 const MachineInstr *inst = I->first->getInst();
1893 MachineInstr *instClone = inst->clone();
1894 branches.push_back(instClone);
Tanya Lattner01114742005-01-18 04:15:41 +00001895 continue;
Tanya Lattnerf3fa55f2004-12-03 05:25:22 +00001896 }
1897
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001898 //Clone instruction
1899 const MachineInstr *inst = I->first->getInst();
1900 MachineInstr *instClone = inst->clone();
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001901
Tanya Lattner420025b2004-10-10 22:44:35 +00001902 //Insert into machine basic block
1903 machineBB->push_back(instClone);
1904
Tanya Lattnerced82222004-11-16 21:31:37 +00001905 DEBUG(std::cerr << "Cloned Inst: " << *instClone << "\n");
1906
Tanya Lattner420025b2004-10-10 22:44:35 +00001907 //Loop over Machine Operands
1908 for(unsigned i=0; i < inst->getNumOperands(); ++i) {
1909 //get machine operand
1910 const MachineOperand &mOp = inst->getOperand(i);
1911
1912 if(I->second != 0) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001913 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse()) {
Tanya Lattner420025b2004-10-10 22:44:35 +00001914
1915 //Check to see where this operand is defined if this instruction is from max stage
1916 if(I->second == schedule.getMaxStage()) {
1917 DEBUG(std::cerr << "VREG: " << *(mOp.getVRegValue()) << "\n");
1918 }
1919
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001920 //If its in the value saved, we need to create a temp instruction and use that instead
1921 if(valuesToSave.count(mOp.getVRegValue())) {
Tanya Lattnerced82222004-11-16 21:31:37 +00001922
1923 //Check if we already have a final PHI value for this
1924 if(!finalPHIValue.count(mOp.getVRegValue())) {
1925 TmpInstruction *tmp = new TmpInstruction(mOp.getVRegValue());
1926
1927 //Get machine code for this instruction
1928 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
1929 tempMvec.addTemp((Value*) tmp);
1930
1931 //Update the operand in the cloned instruction
1932 instClone->getOperand(i).setValueReg(tmp);
1933
1934 //save this as our final phi
1935 finalPHIValue[mOp.getVRegValue()] = tmp;
1936 newValLocation[tmp] = machineBB;
1937 }
1938 else {
1939 //Use the previous final phi value
1940 instClone->getOperand(i).setValueReg(finalPHIValue[mOp.getVRegValue()]);
1941 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001942 }
1943 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001944 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001945 if(I->second != schedule.getMaxStage()) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001946 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef()) {
1947 if(valuesToSave.count(mOp.getVRegValue())) {
1948
1949 TmpInstruction *tmp = new TmpInstruction(mOp.getVRegValue());
1950
Tanya Lattnera6457502004-10-14 06:04:28 +00001951 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00001952 MachineCodeForInstruction & tempVec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001953 tempVec.addTemp((Value*) tmp);
1954
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001955 //Create new machine instr and put in MBB
1956 MachineInstr *saveValue = BuildMI(machineBB, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
1957
1958 //Save for future cleanup
1959 kernelValue[mOp.getVRegValue()] = tmp;
1960 newValLocation[tmp] = machineBB;
Tanya Lattner420025b2004-10-10 22:44:35 +00001961 kernelPHIs[mOp.getVRegValue()][schedule.getMaxStage()-1] = tmp;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001962 }
1963 }
1964 }
1965 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001966
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001967 }
1968
Tanya Lattnerf3fa55f2004-12-03 05:25:22 +00001969 //Add branches
1970 for(std::vector<MachineInstr*>::iterator I = branches.begin(), E = branches.end(); I != E; ++I) {
1971 machineBB->push_back(*I);
1972 BuildMI(machineBB, V9::NOP, 0);
1973 }
1974
1975
Tanya Lattner420025b2004-10-10 22:44:35 +00001976 DEBUG(std::cerr << "KERNEL before PHIs\n");
1977 DEBUG(machineBB->print(std::cerr));
1978
1979
1980 //Loop over each value we need to generate phis for
1981 for(std::map<Value*, std::map<int, Value*> >::iterator V = newValues.begin(),
1982 E = newValues.end(); V != E; ++V) {
1983
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001984
1985 DEBUG(std::cerr << "Writing phi for" << *(V->first));
Tanya Lattner420025b2004-10-10 22:44:35 +00001986 DEBUG(std::cerr << "\nMap of Value* for this phi\n");
1987 DEBUG(for(std::map<int, Value*>::iterator I = V->second.begin(),
1988 IE = V->second.end(); I != IE; ++I) {
1989 std::cerr << "Stage: " << I->first;
1990 std::cerr << " Value: " << *(I->second) << "\n";
1991 });
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001992
Tanya Lattner420025b2004-10-10 22:44:35 +00001993 //If we only have one current iteration live, its safe to set lastPhi = to kernel value
1994 if(V->second.size() == 1) {
1995 assert(kernelValue[V->first] != 0 && "Kernel value* must exist to create phi");
1996 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(),V9::PHI, 3).addReg(V->second.begin()->second).addReg(kernelValue[V->first]).addRegDef(finalPHIValue[V->first]);
1997 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
1998 kernelPHIs[V->first][schedule.getMaxStage()-1] = kernelValue[V->first];
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001999 }
Tanya Lattner420025b2004-10-10 22:44:35 +00002000 else {
2001
2002 //Keep track of last phi created.
2003 Instruction *lastPhi = 0;
2004
2005 unsigned count = 1;
2006 //Loop over the the map backwards to generate phis
2007 for(std::map<int, Value*>::reverse_iterator I = V->second.rbegin(), IE = V->second.rend();
2008 I != IE; ++I) {
2009
2010 if(count < (V->second).size()) {
2011 if(lastPhi == 0) {
2012 lastPhi = new TmpInstruction(I->second);
Tanya Lattnera6457502004-10-14 06:04:28 +00002013
2014 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00002015 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00002016 tempMvec.addTemp((Value*) lastPhi);
2017
Tanya Lattner420025b2004-10-10 22:44:35 +00002018 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(), V9::PHI, 3).addReg(kernelValue[V->first]).addReg(I->second).addRegDef(lastPhi);
2019 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
2020 newValLocation[lastPhi] = machineBB;
2021 }
2022 else {
2023 Instruction *tmp = new TmpInstruction(I->second);
Tanya Lattnera6457502004-10-14 06:04:28 +00002024
2025 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00002026 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00002027 tempMvec.addTemp((Value*) tmp);
2028
2029
Tanya Lattner420025b2004-10-10 22:44:35 +00002030 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(), V9::PHI, 3).addReg(lastPhi).addReg(I->second).addRegDef(tmp);
2031 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
2032 lastPhi = tmp;
2033 kernelPHIs[V->first][I->first] = lastPhi;
2034 newValLocation[lastPhi] = machineBB;
2035 }
2036 }
2037 //Final phi value
2038 else {
2039 //The resulting value must be the Value* we created earlier
2040 assert(lastPhi != 0 && "Last phi is NULL!\n");
2041 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(), V9::PHI, 3).addReg(lastPhi).addReg(I->second).addRegDef(finalPHIValue[V->first]);
2042 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
2043 kernelPHIs[V->first][I->first] = finalPHIValue[V->first];
2044 }
2045
2046 ++count;
2047 }
2048
2049 }
2050 }
2051
2052 DEBUG(std::cerr << "KERNEL after PHIs\n");
2053 DEBUG(machineBB->print(std::cerr));
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002054}
2055
Tanya Lattner420025b2004-10-10 22:44:35 +00002056
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002057void ModuloSchedulingPass::removePHIs(const MachineBasicBlock *origBB, std::vector<MachineBasicBlock *> &prologues, std::vector<MachineBasicBlock *> &epilogues, MachineBasicBlock *kernelBB, std::map<Value*, MachineBasicBlock*> &newValLocation) {
2058
2059 //Worklist to delete things
2060 std::vector<std::pair<MachineBasicBlock*, MachineBasicBlock::iterator> > worklist;
Tanya Lattnera6457502004-10-14 06:04:28 +00002061
2062 //Worklist of TmpInstructions that need to be added to a MCFI
2063 std::vector<Instruction*> addToMCFI;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002064
Tanya Lattnera6457502004-10-14 06:04:28 +00002065 //Worklist to add OR instructions to end of kernel so not to invalidate the iterator
2066 //std::vector<std::pair<Instruction*, Value*> > newORs;
2067
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002068 const TargetInstrInfo *TMI = target.getInstrInfo();
2069
2070 //Start with the kernel and for each phi insert a copy for the phi def and for each arg
2071 for(MachineBasicBlock::iterator I = kernelBB->begin(), E = kernelBB->end(); I != E; ++I) {
Tanya Lattnera6457502004-10-14 06:04:28 +00002072
Tanya Lattner80f08552004-11-02 21:04:56 +00002073 DEBUG(std::cerr << "Looking at Instr: " << *I << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002074 //Get op code and check if its a phi
Tanya Lattnera6457502004-10-14 06:04:28 +00002075 if(I->getOpcode() == V9::PHI) {
2076
2077 DEBUG(std::cerr << "Replacing PHI: " << *I << "\n");
2078 Instruction *tmp = 0;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002079
Tanya Lattnera6457502004-10-14 06:04:28 +00002080 for(unsigned i = 0; i < I->getNumOperands(); ++i) {
2081 //Get Operand
2082 const MachineOperand &mOp = I->getOperand(i);
2083 assert(mOp.getType() == MachineOperand::MO_VirtualRegister && "Should be a Value*\n");
2084
2085 if(!tmp) {
2086 tmp = new TmpInstruction(mOp.getVRegValue());
2087 addToMCFI.push_back(tmp);
2088 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002089
Tanya Lattnera6457502004-10-14 06:04:28 +00002090 //Now for all our arguments we read, OR to the new TmpInstruction that we created
2091 if(mOp.isUse()) {
2092 DEBUG(std::cerr << "Use: " << mOp << "\n");
2093 //Place a copy at the end of its BB but before the branches
2094 assert(newValLocation.count(mOp.getVRegValue()) && "We must know where this value is located\n");
2095 //Reverse iterate to find the branches, we can safely assume no instructions have been
2096 //put in the nop positions
2097 for(MachineBasicBlock::iterator inst = --(newValLocation[mOp.getVRegValue()])->end(), endBB = (newValLocation[mOp.getVRegValue()])->begin(); inst != endBB; --inst) {
2098 MachineOpCode opc = inst->getOpcode();
2099 if(TMI->isBranch(opc) || TMI->isNop(opc))
2100 continue;
2101 else {
2102 BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
2103 break;
2104 }
2105
2106 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002107
Tanya Lattnera6457502004-10-14 06:04:28 +00002108 }
2109 else {
2110 //Remove the phi and replace it with an OR
2111 DEBUG(std::cerr << "Def: " << mOp << "\n");
2112 //newORs.push_back(std::make_pair(tmp, mOp.getVRegValue()));
2113 BuildMI(*kernelBB, I, V9::ORr, 3).addReg(tmp).addImm(0).addRegDef(mOp.getVRegValue());
2114 worklist.push_back(std::make_pair(kernelBB, I));
2115 }
2116
2117 }
2118
2119 }
2120
Tanya Lattnera6457502004-10-14 06:04:28 +00002121
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002122 }
2123
Tanya Lattner80f08552004-11-02 21:04:56 +00002124 //Add TmpInstructions to some MCFI
2125 if(addToMCFI.size() > 0) {
2126 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
2127 for(unsigned x = 0; x < addToMCFI.size(); ++x) {
2128 tempMvec.addTemp(addToMCFI[x]);
2129 }
2130 addToMCFI.clear();
2131 }
2132
Tanya Lattnera6457502004-10-14 06:04:28 +00002133
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002134 //Remove phis from epilogue
2135 for(std::vector<MachineBasicBlock*>::iterator MB = epilogues.begin(), ME = epilogues.end(); MB != ME; ++MB) {
2136 for(MachineBasicBlock::iterator I = (*MB)->begin(), E = (*MB)->end(); I != E; ++I) {
Tanya Lattner80f08552004-11-02 21:04:56 +00002137
2138 DEBUG(std::cerr << "Looking at Instr: " << *I << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002139 //Get op code and check if its a phi
Brian Gaeke418379e2004-08-18 20:04:24 +00002140 if(I->getOpcode() == V9::PHI) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002141 Instruction *tmp = 0;
Tanya Lattnera6457502004-10-14 06:04:28 +00002142
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002143 for(unsigned i = 0; i < I->getNumOperands(); ++i) {
2144 //Get Operand
2145 const MachineOperand &mOp = I->getOperand(i);
2146 assert(mOp.getType() == MachineOperand::MO_VirtualRegister && "Should be a Value*\n");
2147
2148 if(!tmp) {
2149 tmp = new TmpInstruction(mOp.getVRegValue());
Tanya Lattnera6457502004-10-14 06:04:28 +00002150 addToMCFI.push_back(tmp);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002151 }
2152
2153 //Now for all our arguments we read, OR to the new TmpInstruction that we created
2154 if(mOp.isUse()) {
2155 DEBUG(std::cerr << "Use: " << mOp << "\n");
2156 //Place a copy at the end of its BB but before the branches
2157 assert(newValLocation.count(mOp.getVRegValue()) && "We must know where this value is located\n");
2158 //Reverse iterate to find the branches, we can safely assume no instructions have been
2159 //put in the nop positions
2160 for(MachineBasicBlock::iterator inst = --(newValLocation[mOp.getVRegValue()])->end(), endBB = (newValLocation[mOp.getVRegValue()])->begin(); inst != endBB; --inst) {
2161 MachineOpCode opc = inst->getOpcode();
2162 if(TMI->isBranch(opc) || TMI->isNop(opc))
2163 continue;
2164 else {
2165 BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
2166 break;
2167 }
2168
2169 }
Tanya Lattnera6457502004-10-14 06:04:28 +00002170
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002171 }
2172 else {
2173 //Remove the phi and replace it with an OR
2174 DEBUG(std::cerr << "Def: " << mOp << "\n");
2175 BuildMI(**MB, I, V9::ORr, 3).addReg(tmp).addImm(0).addRegDef(mOp.getVRegValue());
2176 worklist.push_back(std::make_pair(*MB,I));
2177 }
2178
2179 }
2180 }
Tanya Lattnera6457502004-10-14 06:04:28 +00002181
Tanya Lattner80f08552004-11-02 21:04:56 +00002182
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002183 }
2184 }
2185
Tanya Lattner80f08552004-11-02 21:04:56 +00002186
2187 if(addToMCFI.size() > 0) {
2188 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
2189 for(unsigned x = 0; x < addToMCFI.size(); ++x) {
2190 tempMvec.addTemp(addToMCFI[x]);
2191 }
2192 addToMCFI.clear();
2193 }
2194
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002195 //Delete the phis
2196 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 +00002197
2198 DEBUG(std::cerr << "Deleting PHI " << *I->second << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002199 I->first->erase(I->second);
2200
2201 }
2202
Tanya Lattnera6457502004-10-14 06:04:28 +00002203
2204 assert((addToMCFI.size() == 0) && "We should have added all TmpInstructions to some MachineCodeForInstruction");
Tanya Lattner20890832004-05-28 20:14:12 +00002205}
2206
2207
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002208void ModuloSchedulingPass::reconstructLoop(MachineBasicBlock *BB) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00002209
Tanya Lattnerdb40cf12005-02-10 17:02:58 +00002210 TIME_REGION(X, "reconstructLoop");
2211
2212
Tanya Lattner420025b2004-10-10 22:44:35 +00002213 DEBUG(std::cerr << "Reconstructing Loop\n");
2214
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002215 //First find the value *'s that we need to "save"
2216 std::map<const Value*, std::pair<const MSchedGraphNode*, int> > valuesToSave;
Tanya Lattner4cffb582004-05-26 06:27:18 +00002217
Tanya Lattner420025b2004-10-10 22:44:35 +00002218 //Keep track of instructions we have already seen and their stage because
2219 //we don't want to "save" values if they are used in the kernel immediately
2220 std::map<const MachineInstr*, int> lastInstrs;
2221
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002222 //Loop over kernel and only look at instructions from a stage > 0
2223 //Look at its operands and save values *'s that are read
Tanya Lattner4cffb582004-05-26 06:27:18 +00002224 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00002225
Tanya Lattner420025b2004-10-10 22:44:35 +00002226 if(I->second !=0) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00002227 //For this instruction, get the Value*'s that it reads and put them into the set.
2228 //Assert if there is an operand of another type that we need to save
2229 const MachineInstr *inst = I->first->getInst();
Tanya Lattner420025b2004-10-10 22:44:35 +00002230 lastInstrs[inst] = I->second;
2231
Tanya Lattner4cffb582004-05-26 06:27:18 +00002232 for(unsigned i=0; i < inst->getNumOperands(); ++i) {
2233 //get machine operand
2234 const MachineOperand &mOp = inst->getOperand(i);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002235
Tanya Lattner4cffb582004-05-26 06:27:18 +00002236 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse()) {
2237 //find the value in the map
Tanya Lattner420025b2004-10-10 22:44:35 +00002238 if (const Value* srcI = mOp.getVRegValue()) {
2239
Tanya Lattnerced82222004-11-16 21:31:37 +00002240 if(isa<Constant>(srcI) || isa<Argument>(srcI) || isa<PHINode>(srcI))
Tanya Lattner80f08552004-11-02 21:04:56 +00002241 continue;
2242
Tanya Lattner420025b2004-10-10 22:44:35 +00002243 //Before we declare this Value* one that we should save
2244 //make sure its def is not of the same stage as this instruction
2245 //because it will be consumed before its used
2246 Instruction *defInst = (Instruction*) srcI;
2247
2248 //Should we save this value?
2249 bool save = true;
2250
Tanya Lattnerced82222004-11-16 21:31:37 +00002251 //Continue if not in the def map, loop invariant code does not need to be saved
2252 if(!defMap.count(srcI))
2253 continue;
2254
Tanya Lattner80f08552004-11-02 21:04:56 +00002255 MachineInstr *defInstr = defMap[srcI];
2256
Tanya Lattnerced82222004-11-16 21:31:37 +00002257
Tanya Lattner80f08552004-11-02 21:04:56 +00002258 if(lastInstrs.count(defInstr)) {
Tanya Lattnerced82222004-11-16 21:31:37 +00002259 if(lastInstrs[defInstr] == I->second) {
Tanya Lattner80f08552004-11-02 21:04:56 +00002260 save = false;
Tanya Lattnerced82222004-11-16 21:31:37 +00002261
2262 }
Tanya Lattner420025b2004-10-10 22:44:35 +00002263 }
Tanya Lattner80f08552004-11-02 21:04:56 +00002264
Tanya Lattner420025b2004-10-10 22:44:35 +00002265 if(save)
2266 valuesToSave[srcI] = std::make_pair(I->first, i);
2267 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00002268 }
2269
2270 if(mOp.getType() != MachineOperand::MO_VirtualRegister && mOp.isUse()) {
2271 assert("Our assumption is wrong. We have another type of register that needs to be saved\n");
2272 }
2273 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00002274 }
2275 }
2276
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002277 //The new loop will consist of one or more prologues, the kernel, and one or more epilogues.
2278
2279 //Map to keep track of old to new values
Tanya Lattner420025b2004-10-10 22:44:35 +00002280 std::map<Value*, std::map<int, Value*> > newValues;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002281
Tanya Lattner420025b2004-10-10 22:44:35 +00002282 //Map to keep track of old to new values in kernel
2283 std::map<Value*, std::map<int, Value*> > kernelPHIs;
2284
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002285 //Another map to keep track of what machine basic blocks these new value*s are in since
2286 //they have no llvm instruction equivalent
2287 std::map<Value*, MachineBasicBlock*> newValLocation;
2288
2289 std::vector<MachineBasicBlock*> prologues;
2290 std::vector<BasicBlock*> llvm_prologues;
2291
2292
2293 //Write prologue
2294 writePrologues(prologues, BB, llvm_prologues, valuesToSave, newValues, newValLocation);
Tanya Lattner420025b2004-10-10 22:44:35 +00002295
2296 //Print out epilogues and prologue
2297 DEBUG(for(std::vector<MachineBasicBlock*>::iterator I = prologues.begin(), E = prologues.end();
2298 I != E; ++I) {
2299 std::cerr << "PROLOGUE\n";
2300 (*I)->print(std::cerr);
2301 });
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002302
2303 BasicBlock *llvmKernelBB = new BasicBlock("Kernel", (Function*) (BB->getBasicBlock()->getParent()));
2304 MachineBasicBlock *machineKernelBB = new MachineBasicBlock(llvmKernelBB);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002305 (((MachineBasicBlock*)BB)->getParent())->getBasicBlockList().push_back(machineKernelBB);
Tanya Lattner420025b2004-10-10 22:44:35 +00002306 writeKernel(llvmKernelBB, machineKernelBB, valuesToSave, newValues, newValLocation, kernelPHIs);
2307
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002308
2309 std::vector<MachineBasicBlock*> epilogues;
2310 std::vector<BasicBlock*> llvm_epilogues;
2311
2312 //Write epilogues
Tanya Lattner420025b2004-10-10 22:44:35 +00002313 writeEpilogues(epilogues, BB, llvm_epilogues, valuesToSave, newValues, newValLocation, kernelPHIs);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002314
2315
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002316 //Fix our branches
2317 fixBranches(prologues, llvm_prologues, machineKernelBB, llvmKernelBB, epilogues, llvm_epilogues, BB);
2318
2319 //Remove phis
2320 removePHIs(BB, prologues, epilogues, machineKernelBB, newValLocation);
2321
2322 //Print out epilogues and prologue
2323 DEBUG(for(std::vector<MachineBasicBlock*>::iterator I = prologues.begin(), E = prologues.end();
2324 I != E; ++I) {
2325 std::cerr << "PROLOGUE\n";
2326 (*I)->print(std::cerr);
2327 });
2328
2329 DEBUG(std::cerr << "KERNEL\n");
2330 DEBUG(machineKernelBB->print(std::cerr));
2331
2332 DEBUG(for(std::vector<MachineBasicBlock*>::iterator I = epilogues.begin(), E = epilogues.end();
2333 I != E; ++I) {
2334 std::cerr << "EPILOGUE\n";
2335 (*I)->print(std::cerr);
2336 });
2337
2338
2339 DEBUG(std::cerr << "New Machine Function" << "\n");
2340 DEBUG(std::cerr << BB->getParent() << "\n");
2341
2342
2343}
2344
2345void 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) {
2346
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002347 const TargetInstrInfo *TMI = target.getInstrInfo();
2348
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002349 //Fix prologue branches
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002350 for(unsigned I = 0; I < prologues.size(); ++I) {
2351
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002352 //Find terminator since getFirstTerminator does not work!
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002353 for(MachineBasicBlock::reverse_iterator mInst = prologues[I]->rbegin(), mInstEnd = prologues[I]->rend(); mInst != mInstEnd; ++mInst) {
2354 MachineOpCode OC = mInst->getOpcode();
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002355 //If its a branch update its branchto
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002356 if(TMI->isBranch(OC)) {
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002357 for(unsigned opNum = 0; opNum < mInst->getNumOperands(); ++opNum) {
2358 MachineOperand &mOp = mInst->getOperand(opNum);
2359 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2360 //Check if we are branching to the kernel, if not branch to epilogue
2361 if(mOp.getVRegValue() == BB->getBasicBlock()) {
2362 if(I == prologues.size()-1)
2363 mOp.setValueReg(llvmKernelBB);
2364 else
2365 mOp.setValueReg(llvm_prologues[I+1]);
2366 }
2367 else {
2368 mOp.setValueReg(llvm_epilogues[(llvm_epilogues.size()-1-I)]);
2369 }
2370 }
2371 }
2372
2373 DEBUG(std::cerr << "New Prologue Branch: " << *mInst << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002374 }
2375 }
2376
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002377
2378 //Update llvm basic block with our new branch instr
2379 DEBUG(std::cerr << BB->getBasicBlock()->getTerminator() << "\n");
2380 const BranchInst *branchVal = dyn_cast<BranchInst>(BB->getBasicBlock()->getTerminator());
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002381
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002382 if(I == prologues.size()-1) {
2383 TerminatorInst *newBranch = new BranchInst(llvmKernelBB,
2384 llvm_epilogues[(llvm_epilogues.size()-1-I)],
Tanya Lattnera6457502004-10-14 06:04:28 +00002385 branchVal->getCondition(),
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002386 llvm_prologues[I]);
2387 }
2388 else
2389 TerminatorInst *newBranch = new BranchInst(llvm_prologues[I+1],
2390 llvm_epilogues[(llvm_epilogues.size()-1-I)],
Tanya Lattnera6457502004-10-14 06:04:28 +00002391 branchVal->getCondition(),
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002392 llvm_prologues[I]);
2393
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002394 }
2395
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002396 Value *origBranchExit = 0;
Tanya Lattnera6457502004-10-14 06:04:28 +00002397
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002398 //Fix up kernel machine branches
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002399 for(MachineBasicBlock::reverse_iterator mInst = machineKernelBB->rbegin(), mInstEnd = machineKernelBB->rend(); mInst != mInstEnd; ++mInst) {
2400 MachineOpCode OC = mInst->getOpcode();
2401 if(TMI->isBranch(OC)) {
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002402 for(unsigned opNum = 0; opNum < mInst->getNumOperands(); ++opNum) {
2403 MachineOperand &mOp = mInst->getOperand(opNum);
2404
2405 if(mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2406 if(mOp.getVRegValue() == BB->getBasicBlock())
2407 mOp.setValueReg(llvmKernelBB);
2408 else
2409 if(llvm_epilogues.size() > 0) {
2410 assert(origBranchExit == 0 && "There should only be one branch out of the loop");
2411
2412 origBranchExit = mOp.getVRegValue();
2413 mOp.setValueReg(llvm_epilogues[0]);
2414 }
2415 }
Tanya Lattnera6457502004-10-14 06:04:28 +00002416 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002417 }
2418 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002419
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002420 //Update kernelLLVM branches
2421 const BranchInst *branchVal = dyn_cast<BranchInst>(BB->getBasicBlock()->getTerminator());
Tanya Lattnera6457502004-10-14 06:04:28 +00002422
Tanya Lattner260652a2004-10-30 00:39:07 +00002423 assert(llvm_epilogues.size() != 0 && "We must have epilogues!");
2424
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002425 TerminatorInst *newBranch = new BranchInst(llvmKernelBB,
2426 llvm_epilogues[0],
Tanya Lattnera6457502004-10-14 06:04:28 +00002427 branchVal->getCondition(),
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002428 llvmKernelBB);
2429
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002430
2431 //Lastly add unconditional branches for the epilogues
2432 for(unsigned I = 0; I < epilogues.size(); ++I) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00002433
Tanya Lattnera6457502004-10-14 06:04:28 +00002434 //Now since we don't have fall throughs, add a unconditional branch to the next prologue
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002435 if(I != epilogues.size()-1) {
Tanya Lattner420025b2004-10-10 22:44:35 +00002436 BuildMI(epilogues[I], V9::BA, 1).addPCDisp(llvm_epilogues[I+1]);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002437 //Add unconditional branch to end of epilogue
2438 TerminatorInst *newBranch = new BranchInst(llvm_epilogues[I+1],
2439 llvm_epilogues[I]);
2440
Tanya Lattner4cffb582004-05-26 06:27:18 +00002441 }
Tanya Lattnera6457502004-10-14 06:04:28 +00002442 else {
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002443 BuildMI(epilogues[I], V9::BA, 1).addPCDisp(origBranchExit);
Tanya Lattnera6457502004-10-14 06:04:28 +00002444
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002445
Tanya Lattnera6457502004-10-14 06:04:28 +00002446 //Update last epilogue exit branch
2447 BranchInst *branchVal = (BranchInst*) dyn_cast<BranchInst>(BB->getBasicBlock()->getTerminator());
2448 //Find where we are supposed to branch to
2449 BasicBlock *nextBlock = 0;
2450 for(unsigned j=0; j <branchVal->getNumSuccessors(); ++j) {
2451 if(branchVal->getSuccessor(j) != BB->getBasicBlock())
2452 nextBlock = branchVal->getSuccessor(j);
2453 }
2454
2455 assert((nextBlock != 0) && "Next block should not be null!");
2456 TerminatorInst *newBranch = new BranchInst(nextBlock, llvm_epilogues[I]);
2457 }
2458 //Add one more nop!
2459 BuildMI(epilogues[I], V9::NOP, 0);
2460
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002461 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00002462
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002463 //FIX UP Machine BB entry!!
2464 //We are looking at the predecesor of our loop basic block and we want to change its ba instruction
2465
Tanya Lattner4cffb582004-05-26 06:27:18 +00002466
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002467 //Find all llvm basic blocks that branch to the loop entry and change to our first prologue.
2468 const BasicBlock *llvmBB = BB->getBasicBlock();
2469
Tanya Lattner260652a2004-10-30 00:39:07 +00002470 std::vector<const BasicBlock*>Preds (pred_begin(llvmBB), pred_end(llvmBB));
2471
2472 //for(pred_const_iterator P = pred_begin(llvmBB), PE = pred_end(llvmBB); P != PE; ++PE) {
2473 for(std::vector<const BasicBlock*>::iterator P = Preds.begin(), PE = Preds.end(); P != PE; ++P) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002474 if(*P == llvmBB)
2475 continue;
2476 else {
2477 DEBUG(std::cerr << "Found our entry BB\n");
2478 //Get the Terminator instruction for this basic block and print it out
2479 DEBUG(std::cerr << *((*P)->getTerminator()) << "\n");
2480 //Update the terminator
2481 TerminatorInst *term = ((BasicBlock*)*P)->getTerminator();
2482 for(unsigned i=0; i < term->getNumSuccessors(); ++i) {
2483 if(term->getSuccessor(i) == llvmBB) {
2484 DEBUG(std::cerr << "Replacing successor bb\n");
2485 if(llvm_prologues.size() > 0) {
2486 term->setSuccessor(i, llvm_prologues[0]);
2487 //Also update its corresponding machine instruction
2488 MachineCodeForInstruction & tempMvec =
2489 MachineCodeForInstruction::get(term);
2490 for (unsigned j = 0; j < tempMvec.size(); j++) {
2491 MachineInstr *temp = tempMvec[j];
2492 MachineOpCode opc = temp->getOpcode();
2493 if(TMI->isBranch(opc)) {
2494 DEBUG(std::cerr << *temp << "\n");
2495 //Update branch
2496 for(unsigned opNum = 0; opNum < temp->getNumOperands(); ++opNum) {
2497 MachineOperand &mOp = temp->getOperand(opNum);
2498 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2499 mOp.setValueReg(llvm_prologues[0]);
2500 }
2501 }
2502 }
2503 }
2504 }
2505 else {
2506 term->setSuccessor(i, llvmKernelBB);
2507 //Also update its corresponding machine instruction
2508 MachineCodeForInstruction & tempMvec =
2509 MachineCodeForInstruction::get(term);
2510 for (unsigned j = 0; j < tempMvec.size(); j++) {
2511 MachineInstr *temp = tempMvec[j];
2512 MachineOpCode opc = temp->getOpcode();
2513 if(TMI->isBranch(opc)) {
2514 DEBUG(std::cerr << *temp << "\n");
2515 //Update branch
2516 for(unsigned opNum = 0; opNum < temp->getNumOperands(); ++opNum) {
2517 MachineOperand &mOp = temp->getOperand(opNum);
2518 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2519 mOp.setValueReg(llvmKernelBB);
2520 }
2521 }
2522 }
2523 }
2524 }
2525 }
2526 }
2527 break;
2528 }
2529 }
2530
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002531
Tanya Lattner420025b2004-10-10 22:44:35 +00002532 //BB->getParent()->getBasicBlockList().erase(BB);
Tanya Lattner4cffb582004-05-26 06:27:18 +00002533
2534}
2535