blob: 6adb5f5225dc3c826480cca49400d14b142cf1c6 [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 Lattner9532ab92005-03-23 01:47:20 +000018#include "llvm/Constants.h"
Tanya Lattner0a88d2d2004-07-30 23:36:10 +000019#include "llvm/Instructions.h"
20#include "llvm/Function.h"
Tanya Lattnerd14b8372004-03-01 02:50:01 +000021#include "llvm/CodeGen/MachineFunction.h"
22#include "llvm/CodeGen/Passes.h"
23#include "llvm/Support/CFG.h"
24#include "llvm/Target/TargetSchedInfo.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000025#include "llvm/Support/Debug.h"
26#include "llvm/Support/GraphWriter.h"
Tanya Lattnerdb40cf12005-02-10 17:02:58 +000027#include "llvm/ADT/SCCIterator.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000028#include "llvm/ADT/StringExtras.h"
Tanya Lattnere1df2122004-11-22 20:41:24 +000029#include "llvm/ADT/Statistic.h"
Tanya Lattnerdb40cf12005-02-10 17:02:58 +000030#include "llvm/Support/Timer.h"
Misha Brukman82fd8d82004-08-02 13:59:10 +000031#include <cmath>
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +000032#include <algorithm>
Tanya Lattnerd14b8372004-03-01 02:50:01 +000033#include <fstream>
34#include <sstream>
Misha Brukman82fd8d82004-08-02 13:59:10 +000035#include <utility>
36#include <vector>
Misha Brukman7da1e6e2004-10-10 23:34:50 +000037#include "../MachineCodeForInstruction.h"
38#include "../SparcV9TmpInstr.h"
39#include "../SparcV9Internals.h"
40#include "../SparcV9RegisterInfo.h"
Tanya Lattnerd14b8372004-03-01 02:50:01 +000041using namespace llvm;
42
43/// Create ModuloSchedulingPass
44///
45FunctionPass *llvm::createModuloSchedulingPass(TargetMachine & targ) {
46 DEBUG(std::cerr << "Created ModuloSchedulingPass\n");
47 return new ModuloSchedulingPass(targ);
48}
49
Tanya Lattner0a88d2d2004-07-30 23:36:10 +000050
51//Graph Traits for printing out the dependence graph
Tanya Lattnerd14b8372004-03-01 02:50:01 +000052template<typename GraphType>
53static void WriteGraphToFile(std::ostream &O, const std::string &GraphName,
54 const GraphType &GT) {
55 std::string Filename = GraphName + ".dot";
56 O << "Writing '" << Filename << "'...";
57 std::ofstream F(Filename.c_str());
58
59 if (F.good())
60 WriteGraph(F, GT);
61 else
62 O << " error opening file for writing!";
63 O << "\n";
64};
Guochun Shif1c154f2003-03-27 17:57:44 +000065
Tanya Lattnerdb40cf12005-02-10 17:02:58 +000066
67#if 1
68#define TIME_REGION(VARNAME, DESC) \
69 NamedRegionTimer VARNAME(DESC)
70#else
71#define TIME_REGION(VARNAME, DESC)
72#endif
73
74
Tanya Lattner0a88d2d2004-07-30 23:36:10 +000075//Graph Traits for printing out the dependence graph
Brian Gaeked0fde302003-11-11 22:41:34 +000076namespace llvm {
Tanya Lattnere1df2122004-11-22 20:41:24 +000077 Statistic<> ValidLoops("modulosched-validLoops", "Number of candidate loops modulo-scheduled");
78 Statistic<> MSLoops("modulosched-schedLoops", "Number of loops successfully modulo-scheduled");
79 Statistic<> IncreasedII("modulosched-increasedII", "Number of times we had to increase II");
Tanya Lattnerdb40cf12005-02-10 17:02:58 +000080 Statistic<> SingleBBLoops("modulosched-singeBBLoops", "Number of single basic block loops");
Tanya Lattnerdb1680b2005-02-16 04:00:59 +000081 Statistic<> NoSched("modulosched-noSched", "No schedule");
82 Statistic<> SameStage("modulosched-sameStage", "Max stage is 0");
Brian Gaeked0fde302003-11-11 22:41:34 +000083
Tanya Lattnerd14b8372004-03-01 02:50:01 +000084 template<>
85 struct DOTGraphTraits<MSchedGraph*> : public DefaultDOTGraphTraits {
86 static std::string getGraphName(MSchedGraph *F) {
87 return "Dependence Graph";
88 }
Guochun Shi8f1d4ab2003-06-08 23:16:07 +000089
Tanya Lattnerd14b8372004-03-01 02:50:01 +000090 static std::string getNodeLabel(MSchedGraphNode *Node, MSchedGraph *Graph) {
91 if (Node->getInst()) {
92 std::stringstream ss;
93 ss << *(Node->getInst());
94 return ss.str(); //((MachineInstr*)Node->getInst());
95 }
96 else
97 return "No Inst";
98 }
99 static std::string getEdgeSourceLabel(MSchedGraphNode *Node,
100 MSchedGraphNode::succ_iterator I) {
101 //Label each edge with the type of dependence
102 std::string edgelabel = "";
103 switch (I.getEdge().getDepOrderType()) {
104
105 case MSchedGraphEdge::TrueDep:
106 edgelabel = "True";
107 break;
108
109 case MSchedGraphEdge::AntiDep:
110 edgelabel = "Anti";
111 break;
112
113 case MSchedGraphEdge::OutputDep:
114 edgelabel = "Output";
115 break;
116
117 default:
118 edgelabel = "Unknown";
119 break;
120 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000121
122 //FIXME
123 int iteDiff = I.getEdge().getIteDiff();
124 std::string intStr = "(IteDiff: ";
125 intStr += itostr(iteDiff);
126
127 intStr += ")";
128 edgelabel += intStr;
129
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000130 return edgelabel;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000131 }
Guochun Shif1c154f2003-03-27 17:57:44 +0000132 };
Guochun Shif1c154f2003-03-27 17:57:44 +0000133}
Tanya Lattner4f839cc2003-08-28 17:12:14 +0000134
Tanya Lattner9532ab92005-03-23 01:47:20 +0000135
136#include <unistd.h>
137
Misha Brukmanaa41c3c2003-10-10 17:41:32 +0000138/// ModuloScheduling::runOnFunction - main transformation entry point
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000139/// The Swing Modulo Schedule algorithm has three basic steps:
140/// 1) Computation and Analysis of the dependence graph
141/// 2) Ordering of the nodes
142/// 3) Scheduling
143///
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000144bool ModuloSchedulingPass::runOnFunction(Function &F) {
Tanya Lattner9532ab92005-03-23 01:47:20 +0000145 alarm(300);
146
Tanya Lattner4f839cc2003-08-28 17:12:14 +0000147 bool Changed = false;
Tanya Lattnerced82222004-11-16 21:31:37 +0000148 int numMS = 0;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000149
Tanya Lattner420025b2004-10-10 22:44:35 +0000150 DEBUG(std::cerr << "Creating ModuloSchedGraph for each valid BasicBlock in " + F.getName() + "\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000151
152 //Get MachineFunction
153 MachineFunction &MF = MachineFunction::get(&F);
Tanya Lattner260652a2004-10-30 00:39:07 +0000154
Tanya Lattner5e9f3522005-03-29 20:35:10 +0000155 DependenceAnalyzer &DA = getAnalysis<DependenceAnalyzer>();
Tanya Lattner9532ab92005-03-23 01:47:20 +0000156 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
157 TargetData &TD = getAnalysis<TargetData>();
158
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000159 //Worklist
160 std::vector<MachineBasicBlock*> Worklist;
161
162 //Iterate over BasicBlocks and put them into our worklist if they are valid
163 for (MachineFunction::iterator BI = MF.begin(); BI != MF.end(); ++BI)
Tanya Lattnere1df2122004-11-22 20:41:24 +0000164 if(MachineBBisValid(BI)) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000165 Worklist.push_back(&*BI);
Tanya Lattnere1df2122004-11-22 20:41:24 +0000166 ++ValidLoops;
167 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000168
Tanya Lattner80f08552004-11-02 21:04:56 +0000169 defaultInst = 0;
170
Tanya Lattner420025b2004-10-10 22:44:35 +0000171 DEBUG(if(Worklist.size() == 0) std::cerr << "No single basic block loops in function to ModuloSchedule\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000172
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000173 //Iterate over the worklist and perform scheduling
174 for(std::vector<MachineBasicBlock*>::iterator BI = Worklist.begin(),
175 BE = Worklist.end(); BI != BE; ++BI) {
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000176
177 //Print out BB for debugging
178 DEBUG(std::cerr << "ModuloScheduling BB: \n"; (*BI)->print(std::cerr));
179
Tanya Lattner9532ab92005-03-23 01:47:20 +0000180 //Print out LLVM BB
181 DEBUG(std::cerr << "ModuloScheduling LLVMBB: \n"; (*BI)->getBasicBlock()->print(std::cerr));
182
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000183 //Catch the odd case where we only have TmpInstructions and no real Value*s
184 if(!CreateDefMap(*BI)) {
185 //Clear out our maps for the next basic block that is processed
186 nodeToAttributesMap.clear();
187 partialOrder.clear();
188 recurrenceList.clear();
189 FinalNodeOrder.clear();
190 schedule.clear();
191 defMap.clear();
192 continue;
193 }
Tanya Lattnerced82222004-11-16 21:31:37 +0000194
Tanya Lattner5e9f3522005-03-29 20:35:10 +0000195 MSchedGraph *MSG = new MSchedGraph(*BI, target, AA, TD, indVarInstrs[*BI], DA, machineTollvm[*BI]);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000196
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000197 //Write Graph out to file
198 DEBUG(WriteGraphToFile(std::cerr, F.getName(), MSG));
199
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000200 //Calculate Resource II
201 int ResMII = calculateResMII(*BI);
202
203 //Calculate Recurrence II
204 int RecMII = calculateRecMII(MSG, ResMII);
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000205
206 DEBUG(std::cerr << "Number of reccurrences found: " << recurrenceList.size() << "\n");
207
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000208
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000209
210
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000211 //Our starting initiation interval is the maximum of RecMII and ResMII
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000212 II = std::max(RecMII, ResMII);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000213
214 //Print out II, RecMII, and ResMII
Tanya Lattner260652a2004-10-30 00:39:07 +0000215 DEBUG(std::cerr << "II starts out as " << II << " ( RecMII=" << RecMII << " and ResMII=" << ResMII << ")\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000216
Tanya Lattner260652a2004-10-30 00:39:07 +0000217 //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 Lattner260652a2004-10-30 00:39:07 +0000224
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000225 //Calculate Node Properties
226 calculateNodeAttributes(MSG, ResMII);
227
228 //Dump node properties if in debug mode
229 DEBUG(for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(),
230 E = nodeToAttributesMap.end(); I !=E; ++I) {
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000231 std::cerr << "Node: " << *(I->first) << " ASAP: " << I->second.ASAP << " ALAP: "
232 << I->second.ALAP << " MOB: " << I->second.MOB << " Depth: " << I->second.depth
233 << " Height: " << I->second.height << "\n";
234 });
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000235
236 //Put nodes in order to schedule them
237 computePartialOrder();
238
239 //Dump out partial order
Tanya Lattner260652a2004-10-30 00:39:07 +0000240 DEBUG(for(std::vector<std::set<MSchedGraphNode*> >::iterator I = partialOrder.begin(),
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000241 E = partialOrder.end(); I !=E; ++I) {
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000242 std::cerr << "Start set in PO\n";
243 for(std::set<MSchedGraphNode*>::iterator J = I->begin(), JE = I->end(); J != JE; ++J)
244 std::cerr << "PO:" << **J << "\n";
245 });
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000246
247 //Place nodes in final order
248 orderNodes();
249
250 //Dump out order of nodes
251 DEBUG(for(std::vector<MSchedGraphNode*>::iterator I = FinalNodeOrder.begin(), E = FinalNodeOrder.end(); I != E; ++I) {
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000252 std::cerr << "FO:" << **I << "\n";
253 });
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000254
255 //Finally schedule nodes
Tanya Lattner9532ab92005-03-23 01:47:20 +0000256 bool haveSched = computeSchedule(*BI);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000257
258 //Print out final schedule
259 DEBUG(schedule.print(std::cerr));
260
Tanya Lattner260652a2004-10-30 00:39:07 +0000261 //Final scheduling step is to reconstruct the loop only if we actual have
262 //stage > 0
Tanya Lattnerad7654f2004-12-02 07:22:15 +0000263 if(schedule.getMaxStage() != 0 && haveSched) {
Tanya Lattner260652a2004-10-30 00:39:07 +0000264 reconstructLoop(*BI);
Tanya Lattnere1df2122004-11-22 20:41:24 +0000265 ++MSLoops;
Tanya Lattnerced82222004-11-16 21:31:37 +0000266 Changed = true;
267 }
Tanya Lattnerdb1680b2005-02-16 04:00:59 +0000268 else {
269 if(!haveSched)
270 ++NoSched;
271 else
272 ++SameStage;
Tanya Lattnerad7654f2004-12-02 07:22:15 +0000273 DEBUG(std::cerr << "Max stage is 0, so no change in loop or reached cap\n");
Tanya Lattnerdb1680b2005-02-16 04:00:59 +0000274 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000275 //Clear out our maps for the next basic block that is processed
276 nodeToAttributesMap.clear();
277 partialOrder.clear();
278 recurrenceList.clear();
279 FinalNodeOrder.clear();
280 schedule.clear();
Tanya Lattnerced82222004-11-16 21:31:37 +0000281 defMap.clear();
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000282 //Clean up. Nuke old MachineBB and llvmBB
283 //BasicBlock *llvmBB = (BasicBlock*) (*BI)->getBasicBlock();
284 //Function *parent = (Function*) llvmBB->getParent();
285 //Should't std::find work??
286 //parent->getBasicBlockList().erase(std::find(parent->getBasicBlockList().begin(), parent->getBasicBlockList().end(), *llvmBB));
287 //parent->getBasicBlockList().erase(llvmBB);
288
289 //delete(llvmBB);
290 //delete(*BI);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000291 }
Tanya Lattner9532ab92005-03-23 01:47:20 +0000292
293 alarm(0);
Tanya Lattner4f839cc2003-08-28 17:12:14 +0000294 return Changed;
295}
Brian Gaeked0fde302003-11-11 22:41:34 +0000296
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000297bool ModuloSchedulingPass::CreateDefMap(MachineBasicBlock *BI) {
Tanya Lattnerced82222004-11-16 21:31:37 +0000298 defaultInst = 0;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000299
Tanya Lattnerced82222004-11-16 21:31:37 +0000300 for(MachineBasicBlock::iterator I = BI->begin(), E = BI->end(); I != E; ++I) {
301 for(unsigned opNum = 0; opNum < I->getNumOperands(); ++opNum) {
302 const MachineOperand &mOp = I->getOperand(opNum);
303 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef()) {
Tanya Lattnere1df2122004-11-22 20:41:24 +0000304 //assert if this is the second def we have seen
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000305 //DEBUG(std::cerr << "Putting " << *(mOp.getVRegValue()) << " into map\n");
Tanya Lattnere1df2122004-11-22 20:41:24 +0000306 assert(!defMap.count(mOp.getVRegValue()) && "Def already in the map");
307
Tanya Lattnerced82222004-11-16 21:31:37 +0000308 defMap[mOp.getVRegValue()] = &*I;
309 }
310
311 //See if we can use this Value* as our defaultInst
312 if(!defaultInst && mOp.getType() == MachineOperand::MO_VirtualRegister) {
313 Value *V = mOp.getVRegValue();
314 if(!isa<TmpInstruction>(V) && !isa<Argument>(V) && !isa<Constant>(V) && !isa<PHINode>(V))
315 defaultInst = (Instruction*) V;
316 }
317 }
318 }
Tanya Lattnere1df2122004-11-22 20:41:24 +0000319
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000320 if(!defaultInst)
321 return false;
322
323 return true;
Tanya Lattnerced82222004-11-16 21:31:37 +0000324
325}
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000326/// This function checks if a Machine Basic Block is valid for modulo
327/// scheduling. This means that it has no control flow (if/else or
328/// calls) in the block. Currently ModuloScheduling only works on
329/// single basic block loops.
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000330bool ModuloSchedulingPass::MachineBBisValid(const MachineBasicBlock *BI) {
331
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000332 bool isLoop = false;
333
334 //Check first if its a valid loop
335 for(succ_const_iterator I = succ_begin(BI->getBasicBlock()),
336 E = succ_end(BI->getBasicBlock()); I != E; ++I) {
337 if (*I == BI->getBasicBlock()) // has single block loop
338 isLoop = true;
339 }
340
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000341 if(!isLoop)
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000342 return false;
Tanya Lattnerad7654f2004-12-02 07:22:15 +0000343
344 //Check that we have a conditional branch (avoiding MS infinite loops)
345 if(BranchInst *b = dyn_cast<BranchInst>(((BasicBlock*) BI->getBasicBlock())->getTerminator()))
346 if(b->isUnconditional())
347 return false;
348
Tanya Lattnere1df2122004-11-22 20:41:24 +0000349 //Check size of our basic block.. make sure we have more then just the terminator in it
350 if(BI->getBasicBlock()->size() == 1)
351 return false;
352
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000353 //Increase number of single basic block loops for stats
354 ++SingleBBLoops;
355
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000356 //Get Target machine instruction info
357 const TargetInstrInfo *TMI = target.getInstrInfo();
358
Tanya Lattner9532ab92005-03-23 01:47:20 +0000359 //Check each instruction and look for calls, keep map to get index later
360 std::map<const MachineInstr*, unsigned> indexMap;
361
362 unsigned count = 0;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000363 for(MachineBasicBlock::const_iterator I = BI->begin(), E = BI->end(); I != E; ++I) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000364 //Get opcode to check instruction type
365 MachineOpCode OC = I->getOpcode();
Tanya Lattner5e9f3522005-03-29 20:35:10 +0000366
367 //Look for calls
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000368 if(TMI->isCall(OC))
369 return false;
Tanya Lattner5e9f3522005-03-29 20:35:10 +0000370
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000371 //Look for conditional move
372 if(OC == V9::MOVRZr || OC == V9::MOVRZi || OC == V9::MOVRLEZr || OC == V9::MOVRLEZi
373 || OC == V9::MOVRLZr || OC == V9::MOVRLZi || OC == V9::MOVRNZr || OC == V9::MOVRNZi
374 || OC == V9::MOVRGZr || OC == V9::MOVRGZi || OC == V9::MOVRGEZr
375 || OC == V9::MOVRGEZi || OC == V9::MOVLEr || OC == V9::MOVLEi || OC == V9::MOVLEUr
376 || OC == V9::MOVLEUi || OC == V9::MOVFLEr || OC == V9::MOVFLEi
377 || OC == V9::MOVNEr || OC == V9::MOVNEi || OC == V9::MOVNEGr || OC == V9::MOVNEGi
378 || OC == V9::MOVFNEr || OC == V9::MOVFNEi)
379 return false;
Tanya Lattner9532ab92005-03-23 01:47:20 +0000380
381 indexMap[I] = count;
382
383 if(TMI->isNop(OC))
384 continue;
385
386 ++count;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000387 }
Tanya Lattner9532ab92005-03-23 01:47:20 +0000388
389 //Apply a simple pattern match to make sure this loop can be modulo scheduled
390 //This means only loops with a branch associated to the iteration count
391
392 //Get the branch
393 BranchInst *b = dyn_cast<BranchInst>(((BasicBlock*) BI->getBasicBlock())->getTerminator());
394
395 //Get the condition for the branch (we already checked if it was conditional)
396 Value *cond = b->getCondition();
397
398 DEBUG(std::cerr << "Condition: " << *cond << "\n");
399
400 //List of instructions associated with induction variable
401 std::set<Instruction*> indVar;
402 std::vector<Instruction*> stack;
403
404 BasicBlock *BB = (BasicBlock*) BI->getBasicBlock();
405
406 //Add branch
407 indVar.insert(b);
408
409 if(Instruction *I = dyn_cast<Instruction>(cond))
410 if(I->getParent() == BB) {
411 if (!assocIndVar(I, indVar, stack, BB))
412 return false;
413 }
414 else
415 return false;
416 else
417 return false;
418
419 //The indVar set must be >= 3 instructions for this loop to match (FIX ME!)
420 if(indVar.size() < 3 )
421 return false;
422
423 //Dump out instructions associate with indvar for debug reasons
424 DEBUG(for(std::set<Instruction*>::iterator N = indVar.begin(), NE = indVar.end(); N != NE; ++N) {
425 std::cerr << **N << "\n";
426 });
427
Tanya Lattner5e9f3522005-03-29 20:35:10 +0000428 //Create map of machine instr to llvm instr
429 std::map<MachineInstr*, Instruction*> mllvm;
430 for(BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
431 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(I);
432 for (unsigned j = 0; j < tempMvec.size(); j++) {
433 mllvm[tempMvec[j]] = I;
434 }
435 }
436
Tanya Lattner9532ab92005-03-23 01:47:20 +0000437 //Convert list of LLVM Instructions to list of Machine instructions
438 std::map<const MachineInstr*, unsigned> mIndVar;
439 for(std::set<Instruction*>::iterator N = indVar.begin(), NE = indVar.end(); N != NE; ++N) {
440 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(*N);
441 for (unsigned j = 0; j < tempMvec.size(); j++) {
442 MachineOpCode OC = (tempMvec[j])->getOpcode();
443 if(TMI->isNop(OC))
444 continue;
445 if(!indexMap.count(tempMvec[j]))
446 continue;
447 mIndVar[(MachineInstr*) tempMvec[j]] = indexMap[(MachineInstr*) tempMvec[j]];
448 DEBUG(std::cerr << *(tempMvec[j]) << " at index " << indexMap[(MachineInstr*) tempMvec[j]] << "\n");
449 }
450 }
451
452 //Must have some guts to the loop body
453 if(mIndVar.size() >= (BI->size()-2))
454 return false;
455
456 //Put into a map for future access
457 indVarInstrs[BI] = mIndVar;
Tanya Lattner5e9f3522005-03-29 20:35:10 +0000458 machineTollvm[BI] = mllvm;
Tanya Lattner9532ab92005-03-23 01:47:20 +0000459 return true;
460}
461
462bool ModuloSchedulingPass::assocIndVar(Instruction *I, std::set<Instruction*> &indVar,
463 std::vector<Instruction*> &stack, BasicBlock *BB) {
464
465 stack.push_back(I);
466
467 //If this is a phi node, check if its the canonical indvar
468 if(PHINode *PN = dyn_cast<PHINode>(I)) {
469 if (Instruction *Inc =
470 dyn_cast<Instruction>(PN->getIncomingValueForBlock(BB)))
471 if (Inc->getOpcode() == Instruction::Add && Inc->getOperand(0) == PN)
472 if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
473 if (CI->equalsInt(1)) {
474 //We have found the indvar, so add the stack, and inc instruction to the set
475 indVar.insert(stack.begin(), stack.end());
476 indVar.insert(Inc);
477 stack.pop_back();
478 return true;
479 }
480 return false;
481 }
482 else {
483 //Loop over each of the instructions operands, check if they are an instruction and in this BB
484 for(unsigned i = 0; i < I->getNumOperands(); ++i) {
485 if(Instruction *N = dyn_cast<Instruction>(I->getOperand(i))) {
486 if(N->getParent() == BB)
487 if(!assocIndVar(N, indVar, stack, BB))
488 return false;
489 }
490 }
491 }
492
493 stack.pop_back();
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000494 return true;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000495}
496
497//ResMII is calculated by determining the usage count for each resource
498//and using the maximum.
499//FIXME: In future there should be a way to get alternative resources
500//for each instruction
501int ModuloSchedulingPass::calculateResMII(const MachineBasicBlock *BI) {
502
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000503 TIME_REGION(X, "calculateResMII");
504
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000505 const TargetInstrInfo *mii = target.getInstrInfo();
506 const TargetSchedInfo *msi = target.getSchedInfo();
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000507
508 int ResMII = 0;
509
510 //Map to keep track of usage count of each resource
511 std::map<unsigned, unsigned> resourceUsageCount;
512
513 for(MachineBasicBlock::const_iterator I = BI->begin(), E = BI->end(); I != E; ++I) {
514
515 //Get resource usage for this instruction
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000516 InstrRUsage rUsage = msi->getInstrRUsage(I->getOpcode());
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000517 std::vector<std::vector<resourceId_t> > resources = rUsage.resourcesByCycle;
518
519 //Loop over resources in each cycle and increments their usage count
520 for(unsigned i=0; i < resources.size(); ++i)
521 for(unsigned j=0; j < resources[i].size(); ++j) {
522 if( resourceUsageCount.find(resources[i][j]) == resourceUsageCount.end()) {
523 resourceUsageCount[resources[i][j]] = 1;
524 }
525 else {
526 resourceUsageCount[resources[i][j]] = resourceUsageCount[resources[i][j]] + 1;
527 }
528 }
529 }
530
531 //Find maximum usage count
532
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000533 //Get max number of instructions that can be issued at once. (FIXME)
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000534 int issueSlots = msi->maxNumIssueTotal;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000535
536 for(std::map<unsigned,unsigned>::iterator RB = resourceUsageCount.begin(), RE = resourceUsageCount.end(); RB != RE; ++RB) {
Tanya Lattner4cffb582004-05-26 06:27:18 +0000537
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000538 //Get the total number of the resources in our cpu
Tanya Lattner4cffb582004-05-26 06:27:18 +0000539 int resourceNum = CPUResource::getCPUResource(RB->first)->maxNumUsers;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000540
541 //Get total usage count for this resources
542 unsigned usageCount = RB->second;
543
544 //Divide the usage count by either the max number we can issue or the number of
545 //resources (whichever is its upper bound)
546 double finalUsageCount;
Tanya Lattner4cffb582004-05-26 06:27:18 +0000547 if( resourceNum <= issueSlots)
548 finalUsageCount = ceil(1.0 * usageCount / resourceNum);
549 else
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000550 finalUsageCount = ceil(1.0 * usageCount / issueSlots);
551
552
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000553 //Only keep track of the max
554 ResMII = std::max( (int) finalUsageCount, ResMII);
555
556 }
557
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000558 return ResMII;
559
560}
561
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000562/// calculateRecMII - Calculates the value of the highest recurrence
563/// By value we mean the total latency
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000564int ModuloSchedulingPass::calculateRecMII(MSchedGraph *graph, int MII) {
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000565 /*std::vector<MSchedGraphNode*> vNodes;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000566 //Loop over all nodes in the graph
567 for(MSchedGraph::iterator I = graph->begin(), E = graph->end(); I != E; ++I) {
568 findAllReccurrences(I->second, vNodes, MII);
569 vNodes.clear();
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000570 }*/
571
572 TIME_REGION(X, "calculateRecMII");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000573
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000574 findAllCircuits(graph, MII);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000575 int RecMII = 0;
576
Tanya Lattner9532ab92005-03-23 01:47:20 +0000577 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 +0000578 RecMII = std::max(RecMII, I->first);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000579 }
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000580
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000581 return MII;
582}
583
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000584/// calculateNodeAttributes - The following properties are calculated for
585/// each node in the dependence graph: ASAP, ALAP, Depth, Height, and
586/// MOB.
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000587void ModuloSchedulingPass::calculateNodeAttributes(MSchedGraph *graph, int MII) {
588
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000589 TIME_REGION(X, "calculateNodeAttributes");
590
Tanya Lattner260652a2004-10-30 00:39:07 +0000591 assert(nodeToAttributesMap.empty() && "Node attribute map was not cleared");
592
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000593 //Loop over the nodes and add them to the map
594 for(MSchedGraph::iterator I = graph->begin(), E = graph->end(); I != E; ++I) {
Tanya Lattner260652a2004-10-30 00:39:07 +0000595
596 DEBUG(std::cerr << "Inserting node into attribute map: " << *I->second << "\n");
597
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000598 //Assert if its already in the map
Tanya Lattner260652a2004-10-30 00:39:07 +0000599 assert(nodeToAttributesMap.count(I->second) == 0 &&
600 "Node attributes are already in the map");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000601
602 //Put into the map with default attribute values
603 nodeToAttributesMap[I->second] = MSNodeAttributes();
604 }
605
606 //Create set to deal with reccurrences
607 std::set<MSchedGraphNode*> visitedNodes;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000608
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000609 //Now Loop over map and calculate the node attributes
610 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000611 calculateASAP(I->first, MII, (MSchedGraphNode*) 0);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000612 visitedNodes.clear();
613 }
614
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000615 int maxASAP = findMaxASAP();
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000616 //Calculate ALAP which depends on ASAP being totally calculated
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000617 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
618 calculateALAP(I->first, MII, maxASAP, (MSchedGraphNode*) 0);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000619 visitedNodes.clear();
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000620 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000621
622 //Calculate MOB which depends on ASAP being totally calculated, also do depth and height
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000623 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
624 (I->second).MOB = std::max(0,(I->second).ALAP - (I->second).ASAP);
625
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000626 DEBUG(std::cerr << "MOB: " << (I->second).MOB << " (" << *(I->first) << ")\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000627 calculateDepth(I->first, (MSchedGraphNode*) 0);
628 calculateHeight(I->first, (MSchedGraphNode*) 0);
629 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000630
631
632}
633
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000634/// ignoreEdge - Checks to see if this edge of a recurrence should be ignored or not
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000635bool ModuloSchedulingPass::ignoreEdge(MSchedGraphNode *srcNode, MSchedGraphNode *destNode) {
636 if(destNode == 0 || srcNode ==0)
637 return false;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000638
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000639 bool findEdge = edgesToIgnore.count(std::make_pair(srcNode, destNode->getInEdgeNum(srcNode)));
Tanya Lattner4cffb582004-05-26 06:27:18 +0000640
Tanya Lattner9532ab92005-03-23 01:47:20 +0000641 DEBUG(std::cerr << "Ignoring edge? from: " << *srcNode << " to " << *destNode << "\n");
642
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000643 return findEdge;
644}
645
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000646
647/// calculateASAP - Calculates the
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000648int ModuloSchedulingPass::calculateASAP(MSchedGraphNode *node, int MII, MSchedGraphNode *destNode) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000649
650 DEBUG(std::cerr << "Calculating ASAP for " << *node << "\n");
651
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000652 //Get current node attributes
653 MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
654
655 if(attributes.ASAP != -1)
656 return attributes.ASAP;
657
658 int maxPredValue = 0;
659
660 //Iterate over all of the predecessors and find max
661 for(MSchedGraphNode::pred_iterator P = node->pred_begin(), E = node->pred_end(); P != E; ++P) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000662
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000663 //Only process if we are not ignoring the edge
664 if(!ignoreEdge(*P, node)) {
665 int predASAP = -1;
666 predASAP = calculateASAP(*P, MII, node);
667
668 assert(predASAP != -1 && "ASAP has not been calculated");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000669 int iteDiff = node->getInEdge(*P).getIteDiff();
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000670
671 int currentPredValue = predASAP + (*P)->getLatency() - (iteDiff * MII);
672 DEBUG(std::cerr << "pred ASAP: " << predASAP << ", iteDiff: " << iteDiff << ", PredLatency: " << (*P)->getLatency() << ", Current ASAP pred: " << currentPredValue << "\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000673 maxPredValue = std::max(maxPredValue, currentPredValue);
674 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000675 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000676
677 attributes.ASAP = maxPredValue;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000678
679 DEBUG(std::cerr << "ASAP: " << attributes.ASAP << " (" << *node << ")\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000680
681 return maxPredValue;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000682}
683
684
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000685int ModuloSchedulingPass::calculateALAP(MSchedGraphNode *node, int MII,
686 int maxASAP, MSchedGraphNode *srcNode) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000687
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000688 DEBUG(std::cerr << "Calculating ALAP for " << *node << "\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000689
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000690 MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
691
692 if(attributes.ALAP != -1)
693 return attributes.ALAP;
694
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000695 if(node->hasSuccessors()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000696
697 //Trying to deal with the issue where the node has successors, but
698 //we are ignoring all of the edges to them. So this is my hack for
699 //now.. there is probably a more elegant way of doing this (FIXME)
700 bool processedOneEdge = false;
701
702 //FIXME, set to something high to start
703 int minSuccValue = 9999999;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000704
705 //Iterate over all of the predecessors and fine max
706 for(MSchedGraphNode::succ_iterator P = node->succ_begin(),
707 E = node->succ_end(); P != E; ++P) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000708
709 //Only process if we are not ignoring the edge
710 if(!ignoreEdge(node, *P)) {
711 processedOneEdge = true;
712 int succALAP = -1;
713 succALAP = calculateALAP(*P, MII, maxASAP, node);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000714
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000715 assert(succALAP != -1 && "Successors ALAP should have been caclulated");
716
717 int iteDiff = P.getEdge().getIteDiff();
718
719 int currentSuccValue = succALAP - node->getLatency() + iteDiff * MII;
720
721 DEBUG(std::cerr << "succ ALAP: " << succALAP << ", iteDiff: " << iteDiff << ", SuccLatency: " << (*P)->getLatency() << ", Current ALAP succ: " << currentSuccValue << "\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000722
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000723 minSuccValue = std::min(minSuccValue, currentSuccValue);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000724 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000725 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000726
727 if(processedOneEdge)
728 attributes.ALAP = minSuccValue;
729
730 else
731 attributes.ALAP = maxASAP;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000732 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000733 else
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000734 attributes.ALAP = maxASAP;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000735
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000736 DEBUG(std::cerr << "ALAP: " << attributes.ALAP << " (" << *node << ")\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000737
738 if(attributes.ALAP < 0)
739 attributes.ALAP = 0;
740
741 return attributes.ALAP;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000742}
743
744int ModuloSchedulingPass::findMaxASAP() {
745 int maxASAP = 0;
746
747 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(),
748 E = nodeToAttributesMap.end(); I != E; ++I)
749 maxASAP = std::max(maxASAP, I->second.ASAP);
750 return maxASAP;
751}
752
753
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000754int ModuloSchedulingPass::calculateHeight(MSchedGraphNode *node,MSchedGraphNode *srcNode) {
755
756 MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000757
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000758 if(attributes.height != -1)
759 return attributes.height;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000760
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000761 int maxHeight = 0;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000762
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000763 //Iterate over all of the predecessors and find max
764 for(MSchedGraphNode::succ_iterator P = node->succ_begin(),
765 E = node->succ_end(); P != E; ++P) {
766
767
768 if(!ignoreEdge(node, *P)) {
769 int succHeight = calculateHeight(*P, node);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000770
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000771 assert(succHeight != -1 && "Successors Height should have been caclulated");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000772
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000773 int currentHeight = succHeight + node->getLatency();
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000774 maxHeight = std::max(maxHeight, currentHeight);
775 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000776 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000777 attributes.height = maxHeight;
778 DEBUG(std::cerr << "Height: " << attributes.height << " (" << *node << ")\n");
779 return maxHeight;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000780}
781
782
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000783int ModuloSchedulingPass::calculateDepth(MSchedGraphNode *node,
784 MSchedGraphNode *destNode) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000785
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000786 MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000787
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000788 if(attributes.depth != -1)
789 return attributes.depth;
790
791 int maxDepth = 0;
792
793 //Iterate over all of the predecessors and fine max
794 for(MSchedGraphNode::pred_iterator P = node->pred_begin(), E = node->pred_end(); P != E; ++P) {
795
796 if(!ignoreEdge(*P, node)) {
797 int predDepth = -1;
798 predDepth = calculateDepth(*P, node);
799
800 assert(predDepth != -1 && "Predecessors ASAP should have been caclulated");
801
802 int currentDepth = predDepth + (*P)->getLatency();
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000803 maxDepth = std::max(maxDepth, currentDepth);
804 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000805 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000806 attributes.depth = maxDepth;
807
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000808 DEBUG(std::cerr << "Depth: " << attributes.depth << " (" << *node << "*)\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000809 return maxDepth;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000810}
811
812
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000813
814void ModuloSchedulingPass::addReccurrence(std::vector<MSchedGraphNode*> &recurrence, int II, MSchedGraphNode *srcBENode, MSchedGraphNode *destBENode) {
815 //Check to make sure that this recurrence is unique
816 bool same = false;
817
818
819 //Loop over all recurrences already in our list
820 for(std::set<std::pair<int, std::vector<MSchedGraphNode*> > >::iterator R = recurrenceList.begin(), RE = recurrenceList.end(); R != RE; ++R) {
821
822 bool all_same = true;
823 //First compare size
824 if(R->second.size() == recurrence.size()) {
825
826 for(std::vector<MSchedGraphNode*>::const_iterator node = R->second.begin(), end = R->second.end(); node != end; ++node) {
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000827 if(std::find(recurrence.begin(), recurrence.end(), *node) == recurrence.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000828 all_same = all_same && false;
829 break;
830 }
831 else
832 all_same = all_same && true;
833 }
834 if(all_same) {
835 same = true;
836 break;
837 }
838 }
839 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000840
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000841 if(!same) {
Tanya Lattner4cffb582004-05-26 06:27:18 +0000842 srcBENode = recurrence.back();
843 destBENode = recurrence.front();
844
845 //FIXME
846 if(destBENode->getInEdge(srcBENode).getIteDiff() == 0) {
847 //DEBUG(std::cerr << "NOT A BACKEDGE\n");
848 //find actual backedge HACK HACK
849 for(unsigned i=0; i< recurrence.size()-1; ++i) {
850 if(recurrence[i+1]->getInEdge(recurrence[i]).getIteDiff() == 1) {
851 srcBENode = recurrence[i];
852 destBENode = recurrence[i+1];
853 break;
854 }
855
856 }
857
858 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000859 DEBUG(std::cerr << "Back Edge to Remove: " << *srcBENode << " to " << *destBENode << "\n");
860 edgesToIgnore.insert(std::make_pair(srcBENode, destBENode->getInEdgeNum(srcBENode)));
861 recurrenceList.insert(std::make_pair(II, recurrence));
862 }
863
864}
865
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000866int CircCount;
867
868void ModuloSchedulingPass::unblock(MSchedGraphNode *u, std::set<MSchedGraphNode*> &blocked,
869 std::map<MSchedGraphNode*, std::set<MSchedGraphNode*> > &B) {
870
871 //Unblock u
872 DEBUG(std::cerr << "Unblocking: " << *u << "\n");
873 blocked.erase(u);
874
875 //std::set<MSchedGraphNode*> toErase;
876 while (!B[u].empty()) {
877 MSchedGraphNode *W = *B[u].begin();
878 B[u].erase(W);
879 //toErase.insert(*W);
880 DEBUG(std::cerr << "Removed: " << *W << "from B-List\n");
881 if(blocked.count(W))
882 unblock(W, blocked, B);
883 }
884
885}
886
887bool ModuloSchedulingPass::circuit(MSchedGraphNode *v, std::vector<MSchedGraphNode*> &stack,
888 std::set<MSchedGraphNode*> &blocked, std::vector<MSchedGraphNode*> &SCC,
889 MSchedGraphNode *s, std::map<MSchedGraphNode*, std::set<MSchedGraphNode*> > &B,
890 int II, std::map<MSchedGraphNode*, MSchedGraphNode*> &newNodes) {
891 bool f = false;
892
893 DEBUG(std::cerr << "Finding Circuits Starting with: ( " << v << ")"<< *v << "\n");
894
895 //Push node onto the stack
896 stack.push_back(v);
897
898 //block this node
899 blocked.insert(v);
900
901 //Loop over all successors of node v that are in the scc, create Adjaceny list
902 std::set<MSchedGraphNode*> AkV;
903 for(MSchedGraphNode::succ_iterator I = v->succ_begin(), E = v->succ_end(); I != E; ++I) {
904 if((std::find(SCC.begin(), SCC.end(), *I) != SCC.end())) {
905 AkV.insert(*I);
906 }
907 }
908
909 for(std::set<MSchedGraphNode*>::iterator I = AkV.begin(), E = AkV.end(); I != E; ++I) {
910 if(*I == s) {
911 //We have a circuit, so add it to our list
912
913 std::vector<MSchedGraphNode*> recc;
914 //Dump recurrence for now
915 DEBUG(std::cerr << "Starting Recc\n");
916
917 int totalDelay = 0;
918 int totalDistance = 0;
919 MSchedGraphNode *lastN = 0;
Tanya Lattner9532ab92005-03-23 01:47:20 +0000920 MSchedGraphNode *start = 0;
921 MSchedGraphNode *end = 0;
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000922
923 //Loop over recurrence, get delay and distance
924 for(std::vector<MSchedGraphNode*>::iterator N = stack.begin(), NE = stack.end(); N != NE; ++N) {
925 totalDelay += (*N)->getLatency();
926 if(lastN) {
Tanya Lattner9532ab92005-03-23 01:47:20 +0000927 int iteDiff = (*N)->getInEdge(lastN).getIteDiff();
928 totalDistance += iteDiff;
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000929
Tanya Lattner9532ab92005-03-23 01:47:20 +0000930 if(iteDiff > 0) {
931 start = lastN;
932 end = *N;
933 }
934 }
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000935 //Get the original node
936 lastN = *N;
937 recc.push_back(newNodes[*N]);
938
939 DEBUG(std::cerr << *lastN << "\n");
940 }
941
942 //Get the loop edge
943 totalDistance += lastN->getIteDiff(*stack.begin());
944
945 DEBUG(std::cerr << "End Recc\n");
946 f = true;
947 CircCount++;
948
Tanya Lattner9532ab92005-03-23 01:47:20 +0000949 if(start && end) {
950 //Insert reccurrence into the list
951 DEBUG(std::cerr << "Ignore Edge from!!: " << *start << " to " << *end << "\n");
952 edgesToIgnore.insert(std::make_pair(newNodes[start], (newNodes[end])->getInEdgeNum(newNodes[start])));
953 }
954 else {
955 //Insert reccurrence into the list
956 DEBUG(std::cerr << "Ignore Edge from: " << *lastN << " to " << **stack.begin() << "\n");
957 edgesToIgnore.insert(std::make_pair(newNodes[lastN], newNodes[(*stack.begin())]->getInEdgeNum(newNodes[lastN])));
958
959 }
Tanya Lattnerdb40cf12005-02-10 17:02:58 +0000960 //Adjust II until we get close to the inequality delay - II*distance <= 0
961 int RecMII = II; //Starting value
962 int value = totalDelay-(RecMII * totalDistance);
963 int lastII = II;
964 while(value <= 0) {
965
966 lastII = RecMII;
967 RecMII--;
968 value = totalDelay-(RecMII * totalDistance);
969 }
970
971 recurrenceList.insert(std::make_pair(lastII, recc));
972
973 }
974 else if(!blocked.count(*I)) {
975 if(circuit(*I, stack, blocked, SCC, s, B, II, newNodes))
976 f = true;
977 }
978 else
979 DEBUG(std::cerr << "Blocked: " << **I << "\n");
980 }
981
982
983 if(f) {
984 unblock(v, blocked, B);
985 }
986 else {
987 for(std::set<MSchedGraphNode*>::iterator I = AkV.begin(), E = AkV.end(); I != E; ++I)
988 B[*I].insert(v);
989
990 }
991
992 //Pop v
993 stack.pop_back();
994
995 return f;
996
997}
998
999void ModuloSchedulingPass::findAllCircuits(MSchedGraph *g, int II) {
1000
1001 CircCount = 0;
1002
1003 //Keep old to new node mapping information
1004 std::map<MSchedGraphNode*, MSchedGraphNode*> newNodes;
1005
1006 //copy the graph
1007 MSchedGraph *MSG = new MSchedGraph(*g, newNodes);
1008
1009 DEBUG(std::cerr << "Finding All Circuits\n");
1010
1011 //Set of blocked nodes
1012 std::set<MSchedGraphNode*> blocked;
1013
1014 //Stack holding current circuit
1015 std::vector<MSchedGraphNode*> stack;
1016
1017 //Map for B Lists
1018 std::map<MSchedGraphNode*, std::set<MSchedGraphNode*> > B;
1019
1020 //current node
1021 MSchedGraphNode *s;
1022
1023
1024 //Iterate over the graph until its down to one node or empty
1025 while(MSG->size() > 1) {
1026
1027 //Write Graph out to file
1028 //WriteGraphToFile(std::cerr, "Graph" + utostr(MSG->size()), MSG);
1029
1030 DEBUG(std::cerr << "Graph Size: " << MSG->size() << "\n");
1031 DEBUG(std::cerr << "Finding strong component Vk with least vertex\n");
1032
1033 //Iterate over all the SCCs in the graph
1034 std::set<MSchedGraphNode*> Visited;
1035 std::vector<MSchedGraphNode*> Vk;
1036 MSchedGraphNode* s = 0;
1037
1038 //Find scc with the least vertex
1039 for (MSchedGraph::iterator GI = MSG->begin(), E = MSG->end(); GI != E; ++GI)
1040 if (Visited.insert(GI->second).second) {
1041 for (scc_iterator<MSchedGraphNode*> SCCI = scc_begin(GI->second),
1042 E = scc_end(GI->second); SCCI != E; ++SCCI) {
1043 std::vector<MSchedGraphNode*> &nextSCC = *SCCI;
1044
1045 if (Visited.insert(nextSCC[0]).second) {
1046 Visited.insert(nextSCC.begin()+1, nextSCC.end());
1047
1048 DEBUG(std::cerr << "SCC size: " << nextSCC.size() << "\n");
1049
1050 //Ignore self loops
1051 if(nextSCC.size() > 1) {
Tanya Lattner9532ab92005-03-23 01:47:20 +00001052
Tanya Lattnerdb40cf12005-02-10 17:02:58 +00001053 //Get least vertex in Vk
1054 if(!s) {
1055 s = nextSCC[0];
1056 Vk = nextSCC;
1057 }
1058
1059 for(unsigned i = 0; i < nextSCC.size(); ++i) {
1060 if(nextSCC[i] < s) {
1061 s = nextSCC[i];
1062 Vk = nextSCC;
1063 }
1064 }
1065 }
1066 }
1067 }
1068 }
1069
1070
1071
1072 //Process SCC
1073 DEBUG(for(std::vector<MSchedGraphNode*>::iterator N = Vk.begin(), NE = Vk.end();
1074 N != NE; ++N) { std::cerr << *((*N)->getInst()); });
1075
1076 //Iterate over all nodes in this scc
1077 for(std::vector<MSchedGraphNode*>::iterator N = Vk.begin(), NE = Vk.end();
1078 N != NE; ++N) {
1079 blocked.erase(*N);
1080 B[*N].clear();
1081 }
1082 if(Vk.size() > 1) {
1083 circuit(s, stack, blocked, Vk, s, B, II, newNodes);
1084
1085 //Find all nodes up to s and delete them
1086 std::vector<MSchedGraphNode*> nodesToRemove;
1087 nodesToRemove.push_back(s);
1088 for(MSchedGraph::iterator N = MSG->begin(), NE = MSG->end(); N != NE; ++N) {
1089 if(N->second < s )
1090 nodesToRemove.push_back(N->second);
1091 }
1092 for(std::vector<MSchedGraphNode*>::iterator N = nodesToRemove.begin(), NE = nodesToRemove.end(); N != NE; ++N) {
1093 DEBUG(std::cerr << "Deleting Node: " << **N << "\n");
1094 MSG->deleteNode(*N);
1095 }
1096 }
1097 else
1098 break;
1099 }
1100 DEBUG(std::cerr << "Num Circuits found: " << CircCount << "\n");
1101}
1102
1103
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001104void ModuloSchedulingPass::findAllReccurrences(MSchedGraphNode *node,
1105 std::vector<MSchedGraphNode*> &visitedNodes,
1106 int II) {
Tanya Lattnerdb40cf12005-02-10 17:02:58 +00001107
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001108
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001109 if(std::find(visitedNodes.begin(), visitedNodes.end(), node) != visitedNodes.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001110 std::vector<MSchedGraphNode*> recurrence;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001111 bool first = true;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001112 int delay = 0;
1113 int distance = 0;
1114 int RecMII = II; //Starting value
1115 MSchedGraphNode *last = node;
Chris Lattner46c2b3a2004-08-04 03:51:55 +00001116 MSchedGraphNode *srcBackEdge = 0;
1117 MSchedGraphNode *destBackEdge = 0;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001118
1119
1120
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001121 for(std::vector<MSchedGraphNode*>::iterator I = visitedNodes.begin(), E = visitedNodes.end();
1122 I !=E; ++I) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001123
1124 if(*I == node)
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001125 first = false;
1126 if(first)
1127 continue;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001128
1129 delay = delay + (*I)->getLatency();
1130
1131 if(*I != node) {
1132 int diff = (*I)->getInEdge(last).getIteDiff();
1133 distance += diff;
1134 if(diff > 0) {
1135 srcBackEdge = last;
1136 destBackEdge = *I;
1137 }
1138 }
1139
1140 recurrence.push_back(*I);
1141 last = *I;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001142 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001143
1144
1145
1146 //Get final distance calc
1147 distance += node->getInEdge(last).getIteDiff();
Tanya Lattnere1df2122004-11-22 20:41:24 +00001148 DEBUG(std::cerr << "Reccurrence Distance: " << distance << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001149
1150 //Adjust II until we get close to the inequality delay - II*distance <= 0
1151
1152 int value = delay-(RecMII * distance);
1153 int lastII = II;
1154 while(value <= 0) {
1155
1156 lastII = RecMII;
1157 RecMII--;
1158 value = delay-(RecMII * distance);
1159 }
1160
1161
1162 DEBUG(std::cerr << "Final II for this recurrence: " << lastII << "\n");
1163 addReccurrence(recurrence, lastII, srcBackEdge, destBackEdge);
1164 assert(distance != 0 && "Recurrence distance should not be zero");
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001165 return;
1166 }
1167
Tanya Lattner01114742005-01-18 04:15:41 +00001168 unsigned count = 0;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001169 for(MSchedGraphNode::succ_iterator I = node->succ_begin(), E = node->succ_end(); I != E; ++I) {
1170 visitedNodes.push_back(node);
Tanya Lattner01114742005-01-18 04:15:41 +00001171 //if(!edgesToIgnore.count(std::make_pair(node, count)))
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001172 findAllReccurrences(*I, visitedNodes, II);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001173 visitedNodes.pop_back();
Tanya Lattner01114742005-01-18 04:15:41 +00001174 count++;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001175 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001176}
1177
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001178void ModuloSchedulingPass::searchPath(MSchedGraphNode *node,
1179 std::vector<MSchedGraphNode*> &path,
1180 std::set<MSchedGraphNode*> &nodesToAdd) {
1181 //Push node onto the path
1182 path.push_back(node);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001183
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001184 //Loop over all successors and see if there is a path from this node to
1185 //a recurrence in the partial order, if so.. add all nodes to be added to recc
1186 for(MSchedGraphNode::succ_iterator S = node->succ_begin(), SE = node->succ_end(); S != SE;
1187 ++S) {
1188
1189 //If this node exists in a recurrence already in the partial order, then add all
1190 //nodes in the path to the set of nodes to add
1191 //Check if its already in our partial order, if not add it to the final vector
1192 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(),
1193 PE = partialOrder.end(); PO != PE; ++PO) {
1194
1195 //Check if we should ignore this edge first
1196 if(ignoreEdge(node,*S))
1197 continue;
1198
1199 if(PO->count(*S)) {
1200 nodesToAdd.insert(*S);
1201 }
Tanya Lattner9532ab92005-03-23 01:47:20 +00001202 //terminate
1203 else
1204 searchPath(*S, path, nodesToAdd);
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001205 }
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001206 }
1207
1208 //Pop Node off the path
1209 path.pop_back();
1210}
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001211
Tanya Lattner9532ab92005-03-23 01:47:20 +00001212void ModuloSchedulingPass::pathToRecc(MSchedGraphNode *node,
1213 std::vector<MSchedGraphNode*> &path,
1214 std::set<MSchedGraphNode*> &poSet,
1215 std::set<MSchedGraphNode*> &lastNodes) {
1216 //Push node onto the path
1217 path.push_back(node);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001218
Tanya Lattner9532ab92005-03-23 01:47:20 +00001219 DEBUG(std::cerr << "Current node: " << *node << "\n");
1220
1221 //Loop over all successors and see if there is a path from this node to
1222 //a recurrence in the partial order, if so.. add all nodes to be added to recc
1223 for(MSchedGraphNode::succ_iterator S = node->succ_begin(), SE = node->succ_end(); S != SE;
1224 ++S) {
1225 DEBUG(std::cerr << "Succ:" << **S << "\n");
1226 //Check if we should ignore this edge first
1227 if(ignoreEdge(node,*S))
1228 continue;
1229
1230 if(poSet.count(*S)) {
1231 DEBUG(std::cerr << "Found path to recc from no pred\n");
1232 //Loop over path, if it exists in lastNodes, then add to poset, and remove from lastNodes
1233 for(std::vector<MSchedGraphNode*>::iterator I = path.begin(), IE = path.end(); I != IE; ++I) {
1234 if(lastNodes.count(*I)) {
1235 DEBUG(std::cerr << "Inserting node into recc: " << **I << "\n");
1236 poSet.insert(*I);
1237 lastNodes.erase(*I);
1238 }
1239 }
1240 }
1241 else
1242 pathToRecc(*S, path, poSet, lastNodes);
1243 }
1244
1245 //Pop Node off the path
1246 path.pop_back();
1247}
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001248
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001249void ModuloSchedulingPass::computePartialOrder() {
Tanya Lattnera6ec8f52004-11-24 01:49:10 +00001250
Tanya Lattnerdb40cf12005-02-10 17:02:58 +00001251 TIME_REGION(X, "calculatePartialOrder");
1252
Tanya Lattnera6ec8f52004-11-24 01:49:10 +00001253 //Only push BA branches onto the final node order, we put other branches after it
1254 //FIXME: Should we really be pushing branches on it a specific order instead of relying
1255 //on BA being there?
Tanya Lattner58fe2f02004-11-29 04:39:47 +00001256 std::vector<MSchedGraphNode*> branches;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001257
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001258 //Steps to add a recurrence to the partial order
1259 // 1) Find reccurrence with the highest RecMII. Add it to the partial order.
1260 // 2) For each recurrence with decreasing RecMII, add it to the partial order along with
1261 // any nodes that connect this recurrence to recurrences already in the partial order
1262 for(std::set<std::pair<int, std::vector<MSchedGraphNode*> > >::reverse_iterator
1263 I = recurrenceList.rbegin(), E=recurrenceList.rend(); I !=E; ++I) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001264
Tanya Lattner260652a2004-10-30 00:39:07 +00001265 std::set<MSchedGraphNode*> new_recurrence;
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001266
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001267 //Loop through recurrence and remove any nodes already in the partial order
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001268 for(std::vector<MSchedGraphNode*>::const_iterator N = I->second.begin(),
1269 NE = I->second.end(); N != NE; ++N) {
1270
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001271 bool found = false;
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001272 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(),
1273 PE = partialOrder.end(); PO != PE; ++PO) {
Tanya Lattner260652a2004-10-30 00:39:07 +00001274 if(PO->count(*N))
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001275 found = true;
1276 }
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001277
1278 //Check if its a branch, and remove to handle special
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001279 if(!found) {
Tanya Lattner9532ab92005-03-23 01:47:20 +00001280 if((*N)->isBranch() && !(*N)->hasPredecessors()) {
Tanya Lattner58fe2f02004-11-29 04:39:47 +00001281 branches.push_back(*N);
Tanya Lattnera6ec8f52004-11-24 01:49:10 +00001282 }
1283 else
1284 new_recurrence.insert(*N);
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001285 }
1286
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001287 }
Tanya Lattnera6ec8f52004-11-24 01:49:10 +00001288
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001289
1290 if(new_recurrence.size() > 0) {
1291
1292 std::vector<MSchedGraphNode*> path;
1293 std::set<MSchedGraphNode*> nodesToAdd;
1294
1295 //Add nodes that connect this recurrence to recurrences in the partial path
1296 for(std::set<MSchedGraphNode*>::iterator N = new_recurrence.begin(),
Tanya Lattner9532ab92005-03-23 01:47:20 +00001297 NE = new_recurrence.end(); N != NE; ++N)
1298 searchPath(*N, path, nodesToAdd);
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001299
1300 //Add nodes to this recurrence if they are not already in the partial order
1301 for(std::set<MSchedGraphNode*>::iterator N = nodesToAdd.begin(), NE = nodesToAdd.end();
1302 N != NE; ++N) {
1303 bool found = false;
1304 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(),
1305 PE = partialOrder.end(); PO != PE; ++PO) {
1306 if(PO->count(*N))
1307 found = true;
1308 }
1309 if(!found) {
1310 assert("FOUND CONNECTOR");
1311 new_recurrence.insert(*N);
1312 }
1313 }
1314
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001315 partialOrder.push_back(new_recurrence);
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001316
1317 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001318 }
1319
1320 //Add any nodes that are not already in the partial order
Tanya Lattner260652a2004-10-30 00:39:07 +00001321 //Add them in a set, one set per connected component
1322 std::set<MSchedGraphNode*> lastNodes;
Tanya Lattner9532ab92005-03-23 01:47:20 +00001323 std::set<MSchedGraphNode*> noPredNodes;
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001324 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(),
1325 E = nodeToAttributesMap.end(); I != E; ++I) {
1326
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001327 bool found = false;
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001328
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001329 //Check if its already in our partial order, if not add it to the final vector
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001330 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(),
1331 PE = partialOrder.end(); PO != PE; ++PO) {
Tanya Lattner260652a2004-10-30 00:39:07 +00001332 if(PO->count(I->first))
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001333 found = true;
1334 }
Tanya Lattnera6ec8f52004-11-24 01:49:10 +00001335 if(!found) {
Tanya Lattner9532ab92005-03-23 01:47:20 +00001336 if(I->first->isBranch() && !I->first->hasPredecessors()) {
Tanya Lattner58fe2f02004-11-29 04:39:47 +00001337 if(std::find(branches.begin(), branches.end(), I->first) == branches.end())
1338 branches.push_back(I->first);
1339 }
Tanya Lattner9532ab92005-03-23 01:47:20 +00001340 else {
Tanya Lattnera6ec8f52004-11-24 01:49:10 +00001341 lastNodes.insert(I->first);
Tanya Lattner9532ab92005-03-23 01:47:20 +00001342 if(!I->first->hasPredecessors())
1343 noPredNodes.insert(I->first);
1344 }
Tanya Lattnera6ec8f52004-11-24 01:49:10 +00001345 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001346 }
1347
Tanya Lattner9532ab92005-03-23 01:47:20 +00001348 //For each node w/out preds, see if there is a path to one of the
1349 //recurrences, and if so add them to that current recc
1350 /*for(std::set<MSchedGraphNode*>::iterator N = noPredNodes.begin(), NE = noPredNodes.end();
1351 N != NE; ++N) {
1352 DEBUG(std::cerr << "No Pred Path from: " << **N << "\n");
1353 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(),
1354 PE = partialOrder.end(); PO != PE; ++PO) {
1355 std::vector<MSchedGraphNode*> path;
1356 pathToRecc(*N, path, *PO, lastNodes);
1357 }
1358 }*/
1359
1360
Tanya Lattner260652a2004-10-30 00:39:07 +00001361 //Break up remaining nodes that are not in the partial order
Tanya Lattner9532ab92005-03-23 01:47:20 +00001362 ///into their connected compoenents
1363 /*while(lastNodes.size() > 0) {
1364 std::set<MSchedGraphNode*> ccSet;
1365 connectedComponentSet(*(lastNodes.begin()),ccSet, lastNodes);
1366 if(ccSet.size() > 0)
1367 partialOrder.push_back(ccSet);
1368 }*/
1369 if(lastNodes.size() > 0)
1370 partialOrder.push_back(lastNodes);
1371
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001372
Tanya Lattnera6ec8f52004-11-24 01:49:10 +00001373 //Clean up branches by putting them in final order
Tanya Lattner58fe2f02004-11-29 04:39:47 +00001374 std::map<unsigned, MSchedGraphNode*> branchOrder;
1375 for(std::vector<MSchedGraphNode*>::iterator I = branches.begin(), E = branches.end(); I != E; ++I)
1376 branchOrder[(*I)->getIndex()] = *I;
1377
1378 for(std::map<unsigned, MSchedGraphNode*>::reverse_iterator I = branchOrder.rbegin(), E = branchOrder.rend(); I != E; ++I)
1379 FinalNodeOrder.push_back(I->second);
1380
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001381}
1382
1383
Tanya Lattner260652a2004-10-30 00:39:07 +00001384void ModuloSchedulingPass::connectedComponentSet(MSchedGraphNode *node, std::set<MSchedGraphNode*> &ccSet, std::set<MSchedGraphNode*> &lastNodes) {
1385
Tanya Lattnera6ec8f52004-11-24 01:49:10 +00001386//Add to final set
1387if( !ccSet.count(node) && lastNodes.count(node)) {
Tanya Lattner260652a2004-10-30 00:39:07 +00001388 lastNodes.erase(node);
Tanya Lattner9532ab92005-03-23 01:47:20 +00001389 if(node->isBranch() && !node->hasPredecessors())
Tanya Lattnera6ec8f52004-11-24 01:49:10 +00001390 FinalNodeOrder.push_back(node);
1391 else
1392 ccSet.insert(node);
Tanya Lattner260652a2004-10-30 00:39:07 +00001393 }
1394 else
1395 return;
1396
1397 //Loop over successors and recurse if we have not seen this node before
1398 for(MSchedGraphNode::succ_iterator node_succ = node->succ_begin(), end=node->succ_end(); node_succ != end; ++node_succ) {
1399 connectedComponentSet(*node_succ, ccSet, lastNodes);
1400 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001401
Tanya Lattner260652a2004-10-30 00:39:07 +00001402}
1403
1404void ModuloSchedulingPass::predIntersect(std::set<MSchedGraphNode*> &CurrentSet, std::set<MSchedGraphNode*> &IntersectResult) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001405
1406 for(unsigned j=0; j < FinalNodeOrder.size(); ++j) {
1407 for(MSchedGraphNode::pred_iterator P = FinalNodeOrder[j]->pred_begin(),
1408 E = FinalNodeOrder[j]->pred_end(); P != E; ++P) {
1409
1410 //Check if we are supposed to ignore this edge or not
1411 if(ignoreEdge(*P,FinalNodeOrder[j]))
1412 continue;
1413
Tanya Lattner260652a2004-10-30 00:39:07 +00001414 if(CurrentSet.count(*P))
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001415 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), *P) == FinalNodeOrder.end())
Tanya Lattner260652a2004-10-30 00:39:07 +00001416 IntersectResult.insert(*P);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001417 }
1418 }
1419}
1420
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001421
Tanya Lattner260652a2004-10-30 00:39:07 +00001422
1423
1424
1425void ModuloSchedulingPass::succIntersect(std::set<MSchedGraphNode*> &CurrentSet, std::set<MSchedGraphNode*> &IntersectResult) {
1426
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001427 for(unsigned j=0; j < FinalNodeOrder.size(); ++j) {
1428 for(MSchedGraphNode::succ_iterator P = FinalNodeOrder[j]->succ_begin(),
1429 E = FinalNodeOrder[j]->succ_end(); P != E; ++P) {
1430
1431 //Check if we are supposed to ignore this edge or not
1432 if(ignoreEdge(FinalNodeOrder[j],*P))
1433 continue;
1434
Tanya Lattner260652a2004-10-30 00:39:07 +00001435 if(CurrentSet.count(*P))
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001436 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), *P) == FinalNodeOrder.end())
Tanya Lattner260652a2004-10-30 00:39:07 +00001437 IntersectResult.insert(*P);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001438 }
1439 }
1440}
1441
Tanya Lattner260652a2004-10-30 00:39:07 +00001442void dumpIntersection(std::set<MSchedGraphNode*> &IntersectCurrent) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001443 std::cerr << "Intersection (";
Tanya Lattner260652a2004-10-30 00:39:07 +00001444 for(std::set<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(), E = IntersectCurrent.end(); I != E; ++I)
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001445 std::cerr << **I << ", ";
1446 std::cerr << ")\n";
1447}
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001448
1449
1450
1451void ModuloSchedulingPass::orderNodes() {
1452
Tanya Lattnerdb40cf12005-02-10 17:02:58 +00001453 TIME_REGION(X, "orderNodes");
1454
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001455 int BOTTOM_UP = 0;
1456 int TOP_DOWN = 1;
1457
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001458 //Set default order
1459 int order = BOTTOM_UP;
1460
Tanya Lattnera6ec8f52004-11-24 01:49:10 +00001461
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001462 //Loop over all the sets and place them in the final node order
Tanya Lattner260652a2004-10-30 00:39:07 +00001463 for(std::vector<std::set<MSchedGraphNode*> >::iterator CurrentSet = partialOrder.begin(), E= partialOrder.end(); CurrentSet != E; ++CurrentSet) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001464
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001465 DEBUG(std::cerr << "Processing set in S\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001466 DEBUG(dumpIntersection(*CurrentSet));
1467
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001468 //Result of intersection
Tanya Lattner260652a2004-10-30 00:39:07 +00001469 std::set<MSchedGraphNode*> IntersectCurrent;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001470
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001471 predIntersect(*CurrentSet, IntersectCurrent);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001472
1473 //If the intersection of predecessor and current set is not empty
1474 //sort nodes bottom up
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001475 if(IntersectCurrent.size() != 0) {
1476 DEBUG(std::cerr << "Final Node Order Predecessors and Current Set interesection is NOT empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001477 order = BOTTOM_UP;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001478 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001479 //If empty, use successors
1480 else {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001481 DEBUG(std::cerr << "Final Node Order Predecessors and Current Set interesection is empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001482
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001483 succIntersect(*CurrentSet, IntersectCurrent);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001484
1485 //sort top-down
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001486 if(IntersectCurrent.size() != 0) {
1487 DEBUG(std::cerr << "Final Node Order Successors and Current Set interesection is NOT empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001488 order = TOP_DOWN;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001489 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001490 else {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001491 DEBUG(std::cerr << "Final Node Order Successors and Current Set interesection is empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001492 //Find node with max ASAP in current Set
1493 MSchedGraphNode *node;
1494 int maxASAP = 0;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001495 DEBUG(std::cerr << "Using current set of size " << CurrentSet->size() << "to find max ASAP\n");
Tanya Lattner260652a2004-10-30 00:39:07 +00001496 for(std::set<MSchedGraphNode*>::iterator J = CurrentSet->begin(), JE = CurrentSet->end(); J != JE; ++J) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001497 //Get node attributes
Tanya Lattner260652a2004-10-30 00:39:07 +00001498 MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*J)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001499 //assert(nodeAttr != nodeToAttributesMap.end() && "Node not in attributes map!");
Tanya Lattner260652a2004-10-30 00:39:07 +00001500
1501 if(maxASAP <= nodeAttr.ASAP) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001502 maxASAP = nodeAttr.ASAP;
Tanya Lattner260652a2004-10-30 00:39:07 +00001503 node = *J;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001504 }
1505 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001506 assert(node != 0 && "In node ordering node should not be null");
Tanya Lattner260652a2004-10-30 00:39:07 +00001507 IntersectCurrent.insert(node);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001508 order = BOTTOM_UP;
1509 }
1510 }
1511
1512 //Repeat until all nodes are put into the final order from current set
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001513 while(IntersectCurrent.size() > 0) {
1514
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001515 if(order == TOP_DOWN) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001516 DEBUG(std::cerr << "Order is TOP DOWN\n");
1517
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001518 while(IntersectCurrent.size() > 0) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001519 DEBUG(std::cerr << "Intersection is not empty, so find heighest height\n");
1520
1521 int MOB = 0;
1522 int height = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +00001523 MSchedGraphNode *highestHeightNode = *(IntersectCurrent.begin());
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001524
1525 //Find node in intersection with highest heigh and lowest MOB
Tanya Lattner260652a2004-10-30 00:39:07 +00001526 for(std::set<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(),
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001527 E = IntersectCurrent.end(); I != E; ++I) {
1528
1529 //Get current nodes properties
1530 MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*I)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001531
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001532 if(height < nodeAttr.height) {
1533 highestHeightNode = *I;
1534 height = nodeAttr.height;
1535 MOB = nodeAttr.MOB;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001536 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001537 else if(height == nodeAttr.height) {
1538 if(MOB > nodeAttr.height) {
1539 highestHeightNode = *I;
1540 height = nodeAttr.height;
1541 MOB = nodeAttr.MOB;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001542 }
1543 }
1544 }
1545
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001546 //Append our node with greatest height to the NodeOrder
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001547 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), highestHeightNode) == FinalNodeOrder.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001548 DEBUG(std::cerr << "Adding node to Final Order: " << *highestHeightNode << "\n");
1549 FinalNodeOrder.push_back(highestHeightNode);
1550 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001551
1552 //Remove V from IntersectOrder
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001553 IntersectCurrent.erase(std::find(IntersectCurrent.begin(),
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001554 IntersectCurrent.end(), highestHeightNode));
1555
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001556
1557 //Intersect V's successors with CurrentSet
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001558 for(MSchedGraphNode::succ_iterator P = highestHeightNode->succ_begin(),
1559 E = highestHeightNode->succ_end(); P != E; ++P) {
1560 //if(lower_bound(CurrentSet->begin(),
1561 // CurrentSet->end(), *P) != CurrentSet->end()) {
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001562 if(std::find(CurrentSet->begin(), CurrentSet->end(), *P) != CurrentSet->end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001563 if(ignoreEdge(highestHeightNode, *P))
1564 continue;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001565 //If not already in Intersect, add
Tanya Lattner260652a2004-10-30 00:39:07 +00001566 if(!IntersectCurrent.count(*P))
1567 IntersectCurrent.insert(*P);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001568 }
1569 }
1570 } //End while loop over Intersect Size
1571
1572 //Change direction
1573 order = BOTTOM_UP;
1574
1575 //Reset Intersect to reflect changes in OrderNodes
1576 IntersectCurrent.clear();
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001577 predIntersect(*CurrentSet, IntersectCurrent);
1578
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001579 } //End If TOP_DOWN
1580
1581 //Begin if BOTTOM_UP
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001582 else {
1583 DEBUG(std::cerr << "Order is BOTTOM UP\n");
1584 while(IntersectCurrent.size() > 0) {
1585 DEBUG(std::cerr << "Intersection of size " << IntersectCurrent.size() << ", finding highest depth\n");
1586
1587 //dump intersection
1588 DEBUG(dumpIntersection(IntersectCurrent));
1589 //Get node with highest depth, if a tie, use one with lowest
1590 //MOB
1591 int MOB = 0;
1592 int depth = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +00001593 MSchedGraphNode *highestDepthNode = *(IntersectCurrent.begin());
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001594
Tanya Lattner260652a2004-10-30 00:39:07 +00001595 for(std::set<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(),
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001596 E = IntersectCurrent.end(); I != E; ++I) {
1597 //Find node attribute in graph
1598 MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*I)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001599
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001600 if(depth < nodeAttr.depth) {
1601 highestDepthNode = *I;
1602 depth = nodeAttr.depth;
1603 MOB = nodeAttr.MOB;
1604 }
1605 else if(depth == nodeAttr.depth) {
1606 if(MOB > nodeAttr.MOB) {
1607 highestDepthNode = *I;
1608 depth = nodeAttr.depth;
1609 MOB = nodeAttr.MOB;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001610 }
1611 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001612 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001613
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001614
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001615
1616 //Append highest depth node to the NodeOrder
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001617 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), highestDepthNode) == FinalNodeOrder.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001618 DEBUG(std::cerr << "Adding node to Final Order: " << *highestDepthNode << "\n");
1619 FinalNodeOrder.push_back(highestDepthNode);
1620 }
1621 //Remove heightestDepthNode from IntersectOrder
Tanya Lattner260652a2004-10-30 00:39:07 +00001622 IntersectCurrent.erase(highestDepthNode);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001623
1624
1625 //Intersect heightDepthNode's pred with CurrentSet
1626 for(MSchedGraphNode::pred_iterator P = highestDepthNode->pred_begin(),
1627 E = highestDepthNode->pred_end(); P != E; ++P) {
Tanya Lattner260652a2004-10-30 00:39:07 +00001628 if(CurrentSet->count(*P)) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001629 if(ignoreEdge(*P, highestDepthNode))
1630 continue;
1631
1632 //If not already in Intersect, add
Tanya Lattner260652a2004-10-30 00:39:07 +00001633 if(!IntersectCurrent.count(*P))
1634 IntersectCurrent.insert(*P);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001635 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001636 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001637
1638 } //End while loop over Intersect Size
1639
1640 //Change order
1641 order = TOP_DOWN;
1642
1643 //Reset IntersectCurrent to reflect changes in OrderNodes
1644 IntersectCurrent.clear();
1645 succIntersect(*CurrentSet, IntersectCurrent);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001646 } //End if BOTTOM_DOWN
1647
Tanya Lattner420025b2004-10-10 22:44:35 +00001648 DEBUG(std::cerr << "Current Intersection Size: " << IntersectCurrent.size() << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001649 }
1650 //End Wrapping while loop
Tanya Lattner420025b2004-10-10 22:44:35 +00001651 DEBUG(std::cerr << "Ending Size of Current Set: " << CurrentSet->size() << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001652 }//End for over all sets of nodes
Tanya Lattner420025b2004-10-10 22:44:35 +00001653
1654 //FIXME: As the algorithm stands it will NEVER add an instruction such as ba (with no
1655 //data dependencies) to the final order. We add this manually. It will always be
1656 //in the last set of S since its not part of a recurrence
1657 //Loop over all the sets and place them in the final node order
Tanya Lattner260652a2004-10-30 00:39:07 +00001658 std::vector<std::set<MSchedGraphNode*> > ::reverse_iterator LastSet = partialOrder.rbegin();
1659 for(std::set<MSchedGraphNode*>::iterator CurrentNode = LastSet->begin(), LastNode = LastSet->end();
Tanya Lattner420025b2004-10-10 22:44:35 +00001660 CurrentNode != LastNode; ++CurrentNode) {
1661 if((*CurrentNode)->getInst()->getOpcode() == V9::BA)
1662 FinalNodeOrder.push_back(*CurrentNode);
1663 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001664 //Return final Order
1665 //return FinalNodeOrder;
1666}
1667
Tanya Lattner9532ab92005-03-23 01:47:20 +00001668bool ModuloSchedulingPass::computeSchedule(const MachineBasicBlock *BB) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001669
Tanya Lattnerdb40cf12005-02-10 17:02:58 +00001670 TIME_REGION(X, "computeSchedule");
1671
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001672 bool success = false;
1673
Tanya Lattner260652a2004-10-30 00:39:07 +00001674 //FIXME: Should be set to max II of the original loop
1675 //Cap II in order to prevent infinite loop
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001676 int capII = 100;
Tanya Lattner260652a2004-10-30 00:39:07 +00001677
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001678 while(!success) {
Tanya Lattner58fe2f02004-11-29 04:39:47 +00001679
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001680 //Keep track of branches, but do not insert into the schedule
1681 std::vector<MSchedGraphNode*> branches;
Tanya Lattner58fe2f02004-11-29 04:39:47 +00001682
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001683 //Loop over the final node order and process each node
1684 for(std::vector<MSchedGraphNode*>::iterator I = FinalNodeOrder.begin(),
1685 E = FinalNodeOrder.end(); I != E; ++I) {
1686
1687 //CalculateEarly and Late start
1688 int EarlyStart = -1;
1689 int LateStart = 99999; //Set to something higher then we would ever expect (FIXME)
1690 bool hasSucc = false;
1691 bool hasPred = false;
Tanya Lattner9532ab92005-03-23 01:47:20 +00001692 bool sched;
1693
1694 if((*I)->isBranch())
1695 if((*I)->hasPredecessors())
1696 sched = true;
1697 else
1698 sched = false;
1699 else
1700 sched = true;
1701
1702 if(sched) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00001703 //Loop over nodes in the schedule and determine if they are predecessors
1704 //or successors of the node we are trying to schedule
1705 for(MSSchedule::schedule_iterator nodesByCycle = schedule.begin(), nodesByCycleEnd = schedule.end();
1706 nodesByCycle != nodesByCycleEnd; ++nodesByCycle) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001707
Tanya Lattner4cffb582004-05-26 06:27:18 +00001708 //For this cycle, get the vector of nodes schedule and loop over it
1709 for(std::vector<MSchedGraphNode*>::iterator schedNode = nodesByCycle->second.begin(), SNE = nodesByCycle->second.end(); schedNode != SNE; ++schedNode) {
1710
1711 if((*I)->isPredecessor(*schedNode)) {
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001712 int diff = (*I)->getInEdge(*schedNode).getIteDiff();
1713 int ES_Temp = nodesByCycle->first + (*schedNode)->getLatency() - diff * II;
1714 DEBUG(std::cerr << "Diff: " << diff << " Cycle: " << nodesByCycle->first << "\n");
1715 DEBUG(std::cerr << "Temp EarlyStart: " << ES_Temp << " Prev EarlyStart: " << EarlyStart << "\n");
1716 EarlyStart = std::max(EarlyStart, ES_Temp);
1717 hasPred = true;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001718 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001719 if((*I)->isSuccessor(*schedNode)) {
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001720 int diff = (*schedNode)->getInEdge(*I).getIteDiff();
1721 int LS_Temp = nodesByCycle->first - (*I)->getLatency() + diff * II;
1722 DEBUG(std::cerr << "Diff: " << diff << " Cycle: " << nodesByCycle->first << "\n");
1723 DEBUG(std::cerr << "Temp LateStart: " << LS_Temp << " Prev LateStart: " << LateStart << "\n");
1724 LateStart = std::min(LateStart, LS_Temp);
1725 hasSucc = true;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001726 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001727 }
1728 }
1729 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001730 else {
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001731 branches.push_back(*I);
1732 continue;
1733 }
1734
1735 //Check if this node is a pred or succ to a branch, and restrict its placement
1736 //even though the branch is not in the schedule
1737 int count = branches.size();
1738 for(std::vector<MSchedGraphNode*>::iterator B = branches.begin(), BE = branches.end();
1739 B != BE; ++B) {
1740 if((*I)->isPredecessor(*B)) {
1741 int diff = (*I)->getInEdge(*B).getIteDiff();
Tanya Lattner9532ab92005-03-23 01:47:20 +00001742 int ES_Temp = (II+count-1) + (*B)->getLatency() - diff * II;
1743 DEBUG(std::cerr << "Diff: " << diff << " Cycle: " << (II+count)-1 << "\n");
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001744 DEBUG(std::cerr << "Temp EarlyStart: " << ES_Temp << " Prev EarlyStart: " << EarlyStart << "\n");
1745 EarlyStart = std::max(EarlyStart, ES_Temp);
1746 hasPred = true;
Tanya Lattner420025b2004-10-10 22:44:35 +00001747 }
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001748
1749 if((*I)->isSuccessor(*B)) {
1750 int diff = (*B)->getInEdge(*I).getIteDiff();
Tanya Lattner9532ab92005-03-23 01:47:20 +00001751 int LS_Temp = (II+count-1) - (*I)->getLatency() + diff * II;
1752 DEBUG(std::cerr << "Diff: " << diff << " Cycle: " << (II+count-1) << "\n");
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001753 DEBUG(std::cerr << "Temp LateStart: " << LS_Temp << " Prev LateStart: " << LateStart << "\n");
1754 LateStart = std::min(LateStart, LS_Temp);
1755 hasSucc = true;
Tanya Lattner420025b2004-10-10 22:44:35 +00001756 }
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001757
1758 count--;
Tanya Lattner4cffb582004-05-26 06:27:18 +00001759 }
1760
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001761 //Check if the node has no pred or successors and set Early Start to its ASAP
1762 if(!hasSucc && !hasPred)
1763 EarlyStart = nodeToAttributesMap.find(*I)->second.ASAP;
1764
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001765 DEBUG(std::cerr << "Has Successors: " << hasSucc << ", Has Pred: " << hasPred << "\n");
1766 DEBUG(std::cerr << "EarlyStart: " << EarlyStart << ", LateStart: " << LateStart << "\n");
1767
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001768 //Now, try to schedule this node depending upon its pred and successor in the schedule
1769 //already
1770 if(!hasSucc && hasPred)
1771 success = scheduleNode(*I, EarlyStart, (EarlyStart + II -1));
1772 else if(!hasPred && hasSucc)
1773 success = scheduleNode(*I, LateStart, (LateStart - II +1));
Tanya Lattner01114742005-01-18 04:15:41 +00001774 else if(hasPred && hasSucc) {
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001775 if(EarlyStart > LateStart) {
Tanya Lattner9532ab92005-03-23 01:47:20 +00001776 success = false;
1777 //LateStart = EarlyStart;
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001778 DEBUG(std::cerr << "Early Start can not be later then the late start cycle, schedule fails\n");
1779 }
Tanya Lattner9532ab92005-03-23 01:47:20 +00001780 else
1781 success = scheduleNode(*I, EarlyStart, std::min(LateStart, (EarlyStart + II -1)));
Tanya Lattner01114742005-01-18 04:15:41 +00001782 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001783 else
1784 success = scheduleNode(*I, EarlyStart, EarlyStart + II - 1);
1785
1786 if(!success) {
Tanya Lattnere1df2122004-11-22 20:41:24 +00001787 ++IncreasedII;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001788 ++II;
1789 schedule.clear();
1790 break;
1791 }
1792
1793 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001794
Tanya Lattner260652a2004-10-30 00:39:07 +00001795 if(success) {
1796 DEBUG(std::cerr << "Constructing Schedule Kernel\n");
Tanya Lattner9532ab92005-03-23 01:47:20 +00001797 success = schedule.constructKernel(II, branches, indVarInstrs[BB]);
Tanya Lattner260652a2004-10-30 00:39:07 +00001798 DEBUG(std::cerr << "Done Constructing Schedule Kernel\n");
1799 if(!success) {
Tanya Lattnere1df2122004-11-22 20:41:24 +00001800 ++IncreasedII;
Tanya Lattner260652a2004-10-30 00:39:07 +00001801 ++II;
1802 schedule.clear();
1803 }
Tanya Lattner9532ab92005-03-23 01:47:20 +00001804 DEBUG(std::cerr << "Final II: " << II << "\n");
Tanya Lattner4cffb582004-05-26 06:27:18 +00001805 }
Tanya Lattner260652a2004-10-30 00:39:07 +00001806
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001807 if(II >= capII) {
1808 DEBUG(std::cerr << "Maximum II reached, giving up\n");
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001809 return false;
Tanya Lattner01b4abd2005-02-23 02:01:42 +00001810 }
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001811
Tanya Lattner260652a2004-10-30 00:39:07 +00001812 assert(II < capII && "The II should not exceed the original loop number of cycles");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001813 }
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001814 return true;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001815}
1816
1817
1818bool ModuloSchedulingPass::scheduleNode(MSchedGraphNode *node,
1819 int start, int end) {
1820 bool success = false;
1821
1822 DEBUG(std::cerr << *node << " (Start Cycle: " << start << ", End Cycle: " << end << ")\n");
1823
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001824 //Make sure start and end are not negative
Tanya Lattner9532ab92005-03-23 01:47:20 +00001825 //if(start < 0) {
1826 //start = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +00001827
Tanya Lattner9532ab92005-03-23 01:47:20 +00001828 //}
1829 //if(end < 0)
1830 //end = 0;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001831
1832 bool forward = true;
1833 if(start > end)
1834 forward = false;
1835
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001836 bool increaseSC = true;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001837 int cycle = start ;
1838
1839
1840 while(increaseSC) {
1841
1842 increaseSC = false;
1843
Tanya Lattner4cffb582004-05-26 06:27:18 +00001844 increaseSC = schedule.insert(node, cycle);
1845
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001846 if(!increaseSC)
1847 return true;
1848
1849 //Increment cycle to try again
1850 if(forward) {
1851 ++cycle;
1852 DEBUG(std::cerr << "Increase cycle: " << cycle << "\n");
1853 if(cycle > end)
1854 return false;
1855 }
1856 else {
1857 --cycle;
1858 DEBUG(std::cerr << "Decrease cycle: " << cycle << "\n");
1859 if(cycle < end)
1860 return false;
1861 }
1862 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001863
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001864 return success;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001865}
Tanya Lattner4cffb582004-05-26 06:27:18 +00001866
Tanya Lattner9532ab92005-03-23 01:47:20 +00001867void ModuloSchedulingPass::writePrologues(std::vector<MachineBasicBlock *> &prologues, MachineBasicBlock *origBB, std::vector<BasicBlock*> &llvm_prologues, std::map<const Value*, std::pair<const MachineInstr*, int> > &valuesToSave, std::map<Value*, std::map<int, Value*> > &newValues, std::map<Value*, MachineBasicBlock*> &newValLocation) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00001868
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001869 //Keep a map to easily know whats in the kernel
Tanya Lattner4cffb582004-05-26 06:27:18 +00001870 std::map<int, std::set<const MachineInstr*> > inKernel;
1871 int maxStageCount = 0;
1872
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001873 //Keep a map of new values we consumed in case they need to be added back
1874 std::map<Value*, std::map<int, Value*> > consumedValues;
1875
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001876 MSchedGraphNode *branch = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +00001877 MSchedGraphNode *BAbranch = 0;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001878
Tanya Lattner5e9f3522005-03-29 20:35:10 +00001879 DEBUG(schedule.print(std::cerr));
Tanya Lattnere1df2122004-11-22 20:41:24 +00001880
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001881 std::vector<MSchedGraphNode*> branches;
1882
Tanya Lattner4cffb582004-05-26 06:27:18 +00001883 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
1884 maxStageCount = std::max(maxStageCount, I->second);
1885
Tanya Lattner4cffb582004-05-26 06:27:18 +00001886 //Put int the map so we know what instructions in each stage are in the kernel
Tanya Lattner9532ab92005-03-23 01:47:20 +00001887 DEBUG(std::cerr << "Inserting instruction " << *(I->first) << " into map at stage " << I->second << "\n");
1888 inKernel[I->second].insert(I->first);
Tanya Lattner4cffb582004-05-26 06:27:18 +00001889 }
1890
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001891 //Get target information to look at machine operands
1892 const TargetInstrInfo *mii = target.getInstrInfo();
1893
1894 //Now write the prologues
1895 for(int i = 0; i < maxStageCount; ++i) {
1896 BasicBlock *llvmBB = new BasicBlock("PROLOGUE", (Function*) (origBB->getBasicBlock()->getParent()));
Tanya Lattner4cffb582004-05-26 06:27:18 +00001897 MachineBasicBlock *machineBB = new MachineBasicBlock(llvmBB);
1898
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001899 DEBUG(std::cerr << "i=" << i << "\n");
Tanya Lattner9532ab92005-03-23 01:47:20 +00001900 for(int j = i; j >= 0; --j) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001901 for(MachineBasicBlock::const_iterator MI = origBB->begin(), ME = origBB->end(); ME != MI; ++MI) {
1902 if(inKernel[j].count(&*MI)) {
Tanya Lattner420025b2004-10-10 22:44:35 +00001903 MachineInstr *instClone = MI->clone();
1904 machineBB->push_back(instClone);
Tanya Lattner9532ab92005-03-23 01:47:20 +00001905
1906 //If its a branch, insert a nop
1907 if(mii->isBranch(instClone->getOpcode()))
1908 BuildMI(machineBB, V9::NOP, 0);
1909
1910
Tanya Lattner420025b2004-10-10 22:44:35 +00001911 DEBUG(std::cerr << "Cloning: " << *MI << "\n");
1912
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001913 //After cloning, we may need to save the value that this instruction defines
1914 for(unsigned opNum=0; opNum < MI->getNumOperands(); ++opNum) {
Tanya Lattner9532ab92005-03-23 01:47:20 +00001915 Instruction *tmp;
1916
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001917 //get machine operand
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001918 MachineOperand &mOp = instClone->getOperand(opNum);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001919 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef()) {
1920
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001921 //Check if this is a value we should save
1922 if(valuesToSave.count(mOp.getVRegValue())) {
1923 //Save copy in tmpInstruction
1924 tmp = new TmpInstruction(mOp.getVRegValue());
1925
Tanya Lattner80f08552004-11-02 21:04:56 +00001926 //Add TmpInstruction to safe LLVM Instruction MCFI
1927 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001928 tempMvec.addTemp((Value*) tmp);
1929
Tanya Lattner420025b2004-10-10 22:44:35 +00001930 DEBUG(std::cerr << "Value: " << *(mOp.getVRegValue()) << " New Value: " << *tmp << " Stage: " << i << "\n");
1931
1932 newValues[mOp.getVRegValue()][i]= tmp;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001933 newValLocation[tmp] = machineBB;
1934
Tanya Lattner420025b2004-10-10 22:44:35 +00001935 DEBUG(std::cerr << "Machine Instr Operands: " << *(mOp.getVRegValue()) << ", 0, " << *tmp << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001936
1937 //Create machine instruction and put int machineBB
Tanya Lattner9532ab92005-03-23 01:47:20 +00001938 MachineInstr *saveValue;
1939 if(mOp.getVRegValue()->getType() == Type::FloatTy)
1940 saveValue = BuildMI(machineBB, V9::FMOVS, 3).addReg(mOp.getVRegValue()).addRegDef(tmp);
1941 else if(mOp.getVRegValue()->getType() == Type::DoubleTy)
1942 saveValue = BuildMI(machineBB, V9::FMOVD, 3).addReg(mOp.getVRegValue()).addRegDef(tmp);
1943 else
1944 saveValue = BuildMI(machineBB, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
1945
1946
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001947 DEBUG(std::cerr << "Created new machine instr: " << *saveValue << "\n");
1948 }
1949 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001950
1951 //We may also need to update the value that we use if its from an earlier prologue
1952 if(j != 0) {
1953 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse()) {
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001954 if(newValues.count(mOp.getVRegValue())) {
1955 if(newValues[mOp.getVRegValue()].count(i-1)) {
1956 Value *oldV = mOp.getVRegValue();
Tanya Lattner420025b2004-10-10 22:44:35 +00001957 DEBUG(std::cerr << "Replaced this value: " << mOp.getVRegValue() << " With:" << (newValues[mOp.getVRegValue()][i-1]) << "\n");
1958 //Update the operand with the right value
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001959 mOp.setValueReg(newValues[mOp.getVRegValue()][i-1]);
1960
1961 //Remove this value since we have consumed it
1962 //NOTE: Should this only be done if j != maxStage?
1963 consumedValues[oldV][i-1] = (newValues[oldV][i-1]);
1964 DEBUG(std::cerr << "Deleted value: " << consumedValues[oldV][i-1] << "\n");
1965 newValues[oldV].erase(i-1);
Tanya Lattner420025b2004-10-10 22:44:35 +00001966 }
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001967 }
1968 else
1969 if(consumedValues.count(mOp.getVRegValue()))
1970 assert(!consumedValues[mOp.getVRegValue()].count(i-1) && "Found a case where we need the value");
Tanya Lattner420025b2004-10-10 22:44:35 +00001971 }
1972 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001973 }
1974 }
Tanya Lattner20890832004-05-28 20:14:12 +00001975 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001976 }
1977
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001978
Tanya Lattner9532ab92005-03-23 01:47:20 +00001979 /*for(std::vector<MSchedGraphNode*>::iterator BR = branches.begin(), BE = branches.end(); BR != BE; ++BR) {
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001980
1981 //Stick in branch at the end
1982 machineBB->push_back((*BR)->getInst()->clone());
Tanya Lattner260652a2004-10-30 00:39:07 +00001983
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001984 //Add nop
1985 BuildMI(machineBB, V9::NOP, 0);
Tanya Lattner9532ab92005-03-23 01:47:20 +00001986 }*/
Tanya Lattner260652a2004-10-30 00:39:07 +00001987
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001988
1989 (((MachineBasicBlock*)origBB)->getParent())->getBasicBlockList().push_back(machineBB);
Tanya Lattner4cffb582004-05-26 06:27:18 +00001990 prologues.push_back(machineBB);
1991 llvm_prologues.push_back(llvmBB);
1992 }
1993}
1994
Tanya Lattner9532ab92005-03-23 01:47:20 +00001995void ModuloSchedulingPass::writeEpilogues(std::vector<MachineBasicBlock *> &epilogues, const MachineBasicBlock *origBB, std::vector<BasicBlock*> &llvm_epilogues, std::map<const Value*, std::pair<const MachineInstr*, 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 +00001996
Tanya Lattner20890832004-05-28 20:14:12 +00001997 std::map<int, std::set<const MachineInstr*> > inKernel;
Tanya Lattner420025b2004-10-10 22:44:35 +00001998
Tanya Lattner20890832004-05-28 20:14:12 +00001999 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
Tanya Lattner20890832004-05-28 20:14:12 +00002000
2001 //Ignore the branch, we will handle this separately
Tanya Lattner9532ab92005-03-23 01:47:20 +00002002 //if(I->first->isBranch())
2003 //continue;
Tanya Lattner20890832004-05-28 20:14:12 +00002004
2005 //Put int the map so we know what instructions in each stage are in the kernel
Tanya Lattner9532ab92005-03-23 01:47:20 +00002006 inKernel[I->second].insert(I->first);
Tanya Lattner20890832004-05-28 20:14:12 +00002007 }
2008
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002009 std::map<Value*, Value*> valPHIs;
2010
Tanya Lattner420025b2004-10-10 22:44:35 +00002011 //some debug stuff, will remove later
2012 DEBUG(for(std::map<Value*, std::map<int, Value*> >::iterator V = newValues.begin(), E = newValues.end(); V !=E; ++V) {
2013 std::cerr << "Old Value: " << *(V->first) << "\n";
2014 for(std::map<int, Value*>::iterator I = V->second.begin(), IE = V->second.end(); I != IE; ++I)
2015 std::cerr << "Stage: " << I->first << " Value: " << *(I->second) << "\n";
2016 });
2017
2018 //some debug stuff, will remove later
2019 DEBUG(for(std::map<Value*, std::map<int, Value*> >::iterator V = kernelPHIs.begin(), E = kernelPHIs.end(); V !=E; ++V) {
2020 std::cerr << "Old Value: " << *(V->first) << "\n";
2021 for(std::map<int, Value*>::iterator I = V->second.begin(), IE = V->second.end(); I != IE; ++I)
2022 std::cerr << "Stage: " << I->first << " Value: " << *(I->second) << "\n";
2023 });
2024
Tanya Lattner20890832004-05-28 20:14:12 +00002025 //Now write the epilogues
Tanya Lattner420025b2004-10-10 22:44:35 +00002026 for(int i = schedule.getMaxStage()-1; i >= 0; --i) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002027 BasicBlock *llvmBB = new BasicBlock("EPILOGUE", (Function*) (origBB->getBasicBlock()->getParent()));
Tanya Lattner20890832004-05-28 20:14:12 +00002028 MachineBasicBlock *machineBB = new MachineBasicBlock(llvmBB);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002029
Tanya Lattner420025b2004-10-10 22:44:35 +00002030 DEBUG(std::cerr << " Epilogue #: " << i << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002031
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002032
Tanya Lattnera6457502004-10-14 06:04:28 +00002033 std::map<Value*, int> inEpilogue;
Tanya Lattner420025b2004-10-10 22:44:35 +00002034
2035 for(MachineBasicBlock::const_iterator MI = origBB->begin(), ME = origBB->end(); ME != MI; ++MI) {
2036 for(int j=schedule.getMaxStage(); j > i; --j) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002037 if(inKernel[j].count(&*MI)) {
2038 DEBUG(std::cerr << "Cloning instruction " << *MI << "\n");
2039 MachineInstr *clone = MI->clone();
2040
2041 //Update operands that need to use the result from the phi
Tanya Lattner420025b2004-10-10 22:44:35 +00002042 for(unsigned opNum=0; opNum < clone->getNumOperands(); ++opNum) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002043 //get machine operand
Tanya Lattner420025b2004-10-10 22:44:35 +00002044 const MachineOperand &mOp = clone->getOperand(opNum);
Tanya Lattner420025b2004-10-10 22:44:35 +00002045
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002046 if((mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse())) {
Tanya Lattner420025b2004-10-10 22:44:35 +00002047
Tanya Lattner9532ab92005-03-23 01:47:20 +00002048 DEBUG(std::cerr << "Writing PHI for " << (mOp.getVRegValue()) << "\n");
Tanya Lattnera6457502004-10-14 06:04:28 +00002049
2050 //If this is the last instructions for the max iterations ago, don't update operands
2051 if(inEpilogue.count(mOp.getVRegValue()))
2052 if(inEpilogue[mOp.getVRegValue()] == i)
2053 continue;
Tanya Lattner420025b2004-10-10 22:44:35 +00002054
2055 //Quickly write appropriate phis for this operand
2056 if(newValues.count(mOp.getVRegValue())) {
2057 if(newValues[mOp.getVRegValue()].count(i)) {
2058 Instruction *tmp = new TmpInstruction(newValues[mOp.getVRegValue()][i]);
Tanya Lattnera6457502004-10-14 06:04:28 +00002059
2060 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00002061 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00002062 tempMvec.addTemp((Value*) tmp);
2063
Tanya Lattner9532ab92005-03-23 01:47:20 +00002064 //assert of no kernelPHI for this value
2065 assert(kernelPHIs[mOp.getVRegValue()][i] !=0 && "Must have final kernel phi to construct epilogue phi");
2066
Tanya Lattner420025b2004-10-10 22:44:35 +00002067 MachineInstr *saveValue = BuildMI(machineBB, V9::PHI, 3).addReg(newValues[mOp.getVRegValue()][i]).addReg(kernelPHIs[mOp.getVRegValue()][i]).addRegDef(tmp);
2068 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
2069 valPHIs[mOp.getVRegValue()] = tmp;
2070 }
2071 }
2072
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002073 if(valPHIs.count(mOp.getVRegValue())) {
2074 //Update the operand in the cloned instruction
Tanya Lattner420025b2004-10-10 22:44:35 +00002075 clone->getOperand(opNum).setValueReg(valPHIs[mOp.getVRegValue()]);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002076 }
2077 }
Tanya Lattnera6457502004-10-14 06:04:28 +00002078 else if((mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef())) {
2079 inEpilogue[mOp.getVRegValue()] = i;
2080 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002081 }
2082 machineBB->push_back(clone);
2083 }
2084 }
Tanya Lattner420025b2004-10-10 22:44:35 +00002085 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002086
Tanya Lattner20890832004-05-28 20:14:12 +00002087 (((MachineBasicBlock*)origBB)->getParent())->getBasicBlockList().push_back(machineBB);
2088 epilogues.push_back(machineBB);
2089 llvm_epilogues.push_back(llvmBB);
Tanya Lattner420025b2004-10-10 22:44:35 +00002090
2091 DEBUG(std::cerr << "EPILOGUE #" << i << "\n");
2092 DEBUG(machineBB->print(std::cerr));
Tanya Lattner20890832004-05-28 20:14:12 +00002093 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002094}
2095
Tanya Lattner9532ab92005-03-23 01:47:20 +00002096void ModuloSchedulingPass::writeKernel(BasicBlock *llvmBB, MachineBasicBlock *machineBB, std::map<const Value*, std::pair<const MachineInstr*, 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 +00002097
2098 //Keep track of operands that are read and saved from a previous iteration. The new clone
2099 //instruction will use the result of the phi instead.
2100 std::map<Value*, Value*> finalPHIValue;
2101 std::map<Value*, Value*> kernelValue;
2102
Tanya Lattnerf3fa55f2004-12-03 05:25:22 +00002103 //Branches are a special case
2104 std::vector<MachineInstr*> branches;
2105
Tanya Lattner9532ab92005-03-23 01:47:20 +00002106 //Get target information to look at machine operands
2107 const TargetInstrInfo *mii = target.getInstrInfo();
2108
2109 //Create TmpInstructions for the final phis
2110 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002111
Tanya Lattner9532ab92005-03-23 01:47:20 +00002112 DEBUG(std::cerr << "Stage: " << I->second << " Inst: " << *(I->first) << "\n";);
Tanya Lattner420025b2004-10-10 22:44:35 +00002113
Tanya Lattner9532ab92005-03-23 01:47:20 +00002114 /*if(I->first->isBranch()) {
Tanya Lattnerf3fa55f2004-12-03 05:25:22 +00002115 //Clone instruction
2116 const MachineInstr *inst = I->first->getInst();
2117 MachineInstr *instClone = inst->clone();
2118 branches.push_back(instClone);
Tanya Lattner01114742005-01-18 04:15:41 +00002119 continue;
Tanya Lattner9532ab92005-03-23 01:47:20 +00002120 }*/
Tanya Lattnerf3fa55f2004-12-03 05:25:22 +00002121
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002122 //Clone instruction
Tanya Lattner9532ab92005-03-23 01:47:20 +00002123 const MachineInstr *inst = I->first;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002124 MachineInstr *instClone = inst->clone();
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002125
Tanya Lattner420025b2004-10-10 22:44:35 +00002126 //Insert into machine basic block
2127 machineBB->push_back(instClone);
2128
Tanya Lattner9532ab92005-03-23 01:47:20 +00002129 if(mii->isBranch(instClone->getOpcode()))
2130 BuildMI(machineBB, V9::NOP, 0);
2131
Tanya Lattnerced82222004-11-16 21:31:37 +00002132 DEBUG(std::cerr << "Cloned Inst: " << *instClone << "\n");
2133
Tanya Lattner420025b2004-10-10 22:44:35 +00002134 //Loop over Machine Operands
2135 for(unsigned i=0; i < inst->getNumOperands(); ++i) {
2136 //get machine operand
2137 const MachineOperand &mOp = inst->getOperand(i);
2138
2139 if(I->second != 0) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002140 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse()) {
Tanya Lattner420025b2004-10-10 22:44:35 +00002141
2142 //Check to see where this operand is defined if this instruction is from max stage
2143 if(I->second == schedule.getMaxStage()) {
2144 DEBUG(std::cerr << "VREG: " << *(mOp.getVRegValue()) << "\n");
2145 }
2146
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002147 //If its in the value saved, we need to create a temp instruction and use that instead
2148 if(valuesToSave.count(mOp.getVRegValue())) {
Tanya Lattnerced82222004-11-16 21:31:37 +00002149
2150 //Check if we already have a final PHI value for this
2151 if(!finalPHIValue.count(mOp.getVRegValue())) {
2152 TmpInstruction *tmp = new TmpInstruction(mOp.getVRegValue());
2153
2154 //Get machine code for this instruction
2155 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
2156 tempMvec.addTemp((Value*) tmp);
2157
2158 //Update the operand in the cloned instruction
2159 instClone->getOperand(i).setValueReg(tmp);
2160
2161 //save this as our final phi
2162 finalPHIValue[mOp.getVRegValue()] = tmp;
2163 newValLocation[tmp] = machineBB;
2164 }
2165 else {
2166 //Use the previous final phi value
2167 instClone->getOperand(i).setValueReg(finalPHIValue[mOp.getVRegValue()]);
2168 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002169 }
2170 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002171 }
Tanya Lattner420025b2004-10-10 22:44:35 +00002172 if(I->second != schedule.getMaxStage()) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002173 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef()) {
2174 if(valuesToSave.count(mOp.getVRegValue())) {
2175
2176 TmpInstruction *tmp = new TmpInstruction(mOp.getVRegValue());
2177
Tanya Lattnera6457502004-10-14 06:04:28 +00002178 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00002179 MachineCodeForInstruction & tempVec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00002180 tempVec.addTemp((Value*) tmp);
2181
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002182 //Create new machine instr and put in MBB
Tanya Lattner9532ab92005-03-23 01:47:20 +00002183 MachineInstr *saveValue;
2184 if(mOp.getVRegValue()->getType() == Type::FloatTy)
2185 saveValue = BuildMI(machineBB, V9::FMOVS, 3).addReg(mOp.getVRegValue()).addRegDef(tmp);
2186 else if(mOp.getVRegValue()->getType() == Type::DoubleTy)
2187 saveValue = BuildMI(machineBB, V9::FMOVD, 3).addReg(mOp.getVRegValue()).addRegDef(tmp);
2188 else
2189 saveValue = BuildMI(machineBB, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
2190
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002191
2192 //Save for future cleanup
2193 kernelValue[mOp.getVRegValue()] = tmp;
2194 newValLocation[tmp] = machineBB;
Tanya Lattner420025b2004-10-10 22:44:35 +00002195 kernelPHIs[mOp.getVRegValue()][schedule.getMaxStage()-1] = tmp;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002196 }
2197 }
2198 }
2199 }
Tanya Lattner420025b2004-10-10 22:44:35 +00002200
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002201 }
2202
Tanya Lattnerf3fa55f2004-12-03 05:25:22 +00002203 //Add branches
2204 for(std::vector<MachineInstr*>::iterator I = branches.begin(), E = branches.end(); I != E; ++I) {
2205 machineBB->push_back(*I);
2206 BuildMI(machineBB, V9::NOP, 0);
2207 }
2208
2209
Tanya Lattner420025b2004-10-10 22:44:35 +00002210 DEBUG(std::cerr << "KERNEL before PHIs\n");
2211 DEBUG(machineBB->print(std::cerr));
2212
2213
2214 //Loop over each value we need to generate phis for
2215 for(std::map<Value*, std::map<int, Value*> >::iterator V = newValues.begin(),
2216 E = newValues.end(); V != E; ++V) {
2217
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002218
2219 DEBUG(std::cerr << "Writing phi for" << *(V->first));
Tanya Lattner420025b2004-10-10 22:44:35 +00002220 DEBUG(std::cerr << "\nMap of Value* for this phi\n");
2221 DEBUG(for(std::map<int, Value*>::iterator I = V->second.begin(),
2222 IE = V->second.end(); I != IE; ++I) {
2223 std::cerr << "Stage: " << I->first;
2224 std::cerr << " Value: " << *(I->second) << "\n";
2225 });
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002226
Tanya Lattner420025b2004-10-10 22:44:35 +00002227 //If we only have one current iteration live, its safe to set lastPhi = to kernel value
2228 if(V->second.size() == 1) {
2229 assert(kernelValue[V->first] != 0 && "Kernel value* must exist to create phi");
2230 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(),V9::PHI, 3).addReg(V->second.begin()->second).addReg(kernelValue[V->first]).addRegDef(finalPHIValue[V->first]);
Tanya Lattner9532ab92005-03-23 01:47:20 +00002231 DEBUG(std::cerr << "Resulting PHI (one live): " << *saveValue << "\n");
2232 kernelPHIs[V->first][V->second.begin()->first] = kernelValue[V->first];
2233 DEBUG(std::cerr << "Put kernel phi in at stage: " << schedule.getMaxStage()-1 << " (map stage = " << V->second.begin()->first << ")\n");
2234 }
Tanya Lattner420025b2004-10-10 22:44:35 +00002235 else {
2236
2237 //Keep track of last phi created.
2238 Instruction *lastPhi = 0;
2239
2240 unsigned count = 1;
2241 //Loop over the the map backwards to generate phis
2242 for(std::map<int, Value*>::reverse_iterator I = V->second.rbegin(), IE = V->second.rend();
2243 I != IE; ++I) {
2244
2245 if(count < (V->second).size()) {
2246 if(lastPhi == 0) {
2247 lastPhi = new TmpInstruction(I->second);
Tanya Lattnera6457502004-10-14 06:04:28 +00002248
2249 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00002250 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00002251 tempMvec.addTemp((Value*) lastPhi);
2252
Tanya Lattner420025b2004-10-10 22:44:35 +00002253 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(), V9::PHI, 3).addReg(kernelValue[V->first]).addReg(I->second).addRegDef(lastPhi);
2254 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
2255 newValLocation[lastPhi] = machineBB;
2256 }
2257 else {
2258 Instruction *tmp = new TmpInstruction(I->second);
Tanya Lattnera6457502004-10-14 06:04:28 +00002259
2260 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00002261 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00002262 tempMvec.addTemp((Value*) tmp);
2263
2264
Tanya Lattner420025b2004-10-10 22:44:35 +00002265 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(), V9::PHI, 3).addReg(lastPhi).addReg(I->second).addRegDef(tmp);
2266 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
2267 lastPhi = tmp;
2268 kernelPHIs[V->first][I->first] = lastPhi;
2269 newValLocation[lastPhi] = machineBB;
2270 }
2271 }
2272 //Final phi value
2273 else {
2274 //The resulting value must be the Value* we created earlier
2275 assert(lastPhi != 0 && "Last phi is NULL!\n");
2276 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(), V9::PHI, 3).addReg(lastPhi).addReg(I->second).addRegDef(finalPHIValue[V->first]);
2277 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
2278 kernelPHIs[V->first][I->first] = finalPHIValue[V->first];
2279 }
2280
2281 ++count;
2282 }
2283
2284 }
2285 }
2286
2287 DEBUG(std::cerr << "KERNEL after PHIs\n");
2288 DEBUG(machineBB->print(std::cerr));
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002289}
2290
Tanya Lattner420025b2004-10-10 22:44:35 +00002291
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002292void ModuloSchedulingPass::removePHIs(const MachineBasicBlock *origBB, std::vector<MachineBasicBlock *> &prologues, std::vector<MachineBasicBlock *> &epilogues, MachineBasicBlock *kernelBB, std::map<Value*, MachineBasicBlock*> &newValLocation) {
2293
2294 //Worklist to delete things
2295 std::vector<std::pair<MachineBasicBlock*, MachineBasicBlock::iterator> > worklist;
Tanya Lattnera6457502004-10-14 06:04:28 +00002296
2297 //Worklist of TmpInstructions that need to be added to a MCFI
2298 std::vector<Instruction*> addToMCFI;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002299
Tanya Lattnera6457502004-10-14 06:04:28 +00002300 //Worklist to add OR instructions to end of kernel so not to invalidate the iterator
2301 //std::vector<std::pair<Instruction*, Value*> > newORs;
2302
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002303 const TargetInstrInfo *TMI = target.getInstrInfo();
2304
2305 //Start with the kernel and for each phi insert a copy for the phi def and for each arg
2306 for(MachineBasicBlock::iterator I = kernelBB->begin(), E = kernelBB->end(); I != E; ++I) {
Tanya Lattnera6457502004-10-14 06:04:28 +00002307
Tanya Lattner80f08552004-11-02 21:04:56 +00002308 DEBUG(std::cerr << "Looking at Instr: " << *I << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002309 //Get op code and check if its a phi
Tanya Lattnera6457502004-10-14 06:04:28 +00002310 if(I->getOpcode() == V9::PHI) {
2311
2312 DEBUG(std::cerr << "Replacing PHI: " << *I << "\n");
2313 Instruction *tmp = 0;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002314
Tanya Lattnera6457502004-10-14 06:04:28 +00002315 for(unsigned i = 0; i < I->getNumOperands(); ++i) {
2316 //Get Operand
2317 const MachineOperand &mOp = I->getOperand(i);
2318 assert(mOp.getType() == MachineOperand::MO_VirtualRegister && "Should be a Value*\n");
2319
2320 if(!tmp) {
2321 tmp = new TmpInstruction(mOp.getVRegValue());
2322 addToMCFI.push_back(tmp);
2323 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002324
Tanya Lattnera6457502004-10-14 06:04:28 +00002325 //Now for all our arguments we read, OR to the new TmpInstruction that we created
2326 if(mOp.isUse()) {
2327 DEBUG(std::cerr << "Use: " << mOp << "\n");
2328 //Place a copy at the end of its BB but before the branches
2329 assert(newValLocation.count(mOp.getVRegValue()) && "We must know where this value is located\n");
2330 //Reverse iterate to find the branches, we can safely assume no instructions have been
2331 //put in the nop positions
2332 for(MachineBasicBlock::iterator inst = --(newValLocation[mOp.getVRegValue()])->end(), endBB = (newValLocation[mOp.getVRegValue()])->begin(); inst != endBB; --inst) {
2333 MachineOpCode opc = inst->getOpcode();
2334 if(TMI->isBranch(opc) || TMI->isNop(opc))
2335 continue;
2336 else {
Tanya Lattner9532ab92005-03-23 01:47:20 +00002337 if(mOp.getVRegValue()->getType() == Type::FloatTy)
2338 BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::FMOVS, 3).addReg(mOp.getVRegValue()).addRegDef(tmp);
2339 else if(mOp.getVRegValue()->getType() == Type::DoubleTy)
2340 BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::FMOVD, 3).addReg(mOp.getVRegValue()).addRegDef(tmp);
2341 else
2342 BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
2343
Tanya Lattnera6457502004-10-14 06:04:28 +00002344 break;
2345 }
2346
2347 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002348
Tanya Lattnera6457502004-10-14 06:04:28 +00002349 }
2350 else {
2351 //Remove the phi and replace it with an OR
2352 DEBUG(std::cerr << "Def: " << mOp << "\n");
2353 //newORs.push_back(std::make_pair(tmp, mOp.getVRegValue()));
Tanya Lattner9532ab92005-03-23 01:47:20 +00002354 if(tmp->getType() == Type::FloatTy)
2355 BuildMI(*kernelBB, I, V9::FMOVS, 3).addReg(tmp).addRegDef(mOp.getVRegValue());
2356 else if(tmp->getType() == Type::DoubleTy)
2357 BuildMI(*kernelBB, I, V9::FMOVD, 3).addReg(tmp).addRegDef(mOp.getVRegValue());
2358 else
2359 BuildMI(*kernelBB, I, V9::ORr, 3).addReg(tmp).addImm(0).addRegDef(mOp.getVRegValue());
2360
2361
Tanya Lattnera6457502004-10-14 06:04:28 +00002362 worklist.push_back(std::make_pair(kernelBB, I));
2363 }
2364
2365 }
2366
2367 }
2368
Tanya Lattnera6457502004-10-14 06:04:28 +00002369
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002370 }
2371
Tanya Lattner80f08552004-11-02 21:04:56 +00002372 //Add TmpInstructions to some MCFI
2373 if(addToMCFI.size() > 0) {
2374 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
2375 for(unsigned x = 0; x < addToMCFI.size(); ++x) {
2376 tempMvec.addTemp(addToMCFI[x]);
2377 }
2378 addToMCFI.clear();
2379 }
2380
Tanya Lattnera6457502004-10-14 06:04:28 +00002381
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002382 //Remove phis from epilogue
2383 for(std::vector<MachineBasicBlock*>::iterator MB = epilogues.begin(), ME = epilogues.end(); MB != ME; ++MB) {
2384 for(MachineBasicBlock::iterator I = (*MB)->begin(), E = (*MB)->end(); I != E; ++I) {
Tanya Lattner80f08552004-11-02 21:04:56 +00002385
2386 DEBUG(std::cerr << "Looking at Instr: " << *I << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002387 //Get op code and check if its a phi
Brian Gaeke418379e2004-08-18 20:04:24 +00002388 if(I->getOpcode() == V9::PHI) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002389 Instruction *tmp = 0;
Tanya Lattnera6457502004-10-14 06:04:28 +00002390
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002391 for(unsigned i = 0; i < I->getNumOperands(); ++i) {
2392 //Get Operand
2393 const MachineOperand &mOp = I->getOperand(i);
2394 assert(mOp.getType() == MachineOperand::MO_VirtualRegister && "Should be a Value*\n");
2395
2396 if(!tmp) {
2397 tmp = new TmpInstruction(mOp.getVRegValue());
Tanya Lattnera6457502004-10-14 06:04:28 +00002398 addToMCFI.push_back(tmp);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002399 }
2400
2401 //Now for all our arguments we read, OR to the new TmpInstruction that we created
2402 if(mOp.isUse()) {
2403 DEBUG(std::cerr << "Use: " << mOp << "\n");
2404 //Place a copy at the end of its BB but before the branches
2405 assert(newValLocation.count(mOp.getVRegValue()) && "We must know where this value is located\n");
2406 //Reverse iterate to find the branches, we can safely assume no instructions have been
2407 //put in the nop positions
2408 for(MachineBasicBlock::iterator inst = --(newValLocation[mOp.getVRegValue()])->end(), endBB = (newValLocation[mOp.getVRegValue()])->begin(); inst != endBB; --inst) {
2409 MachineOpCode opc = inst->getOpcode();
2410 if(TMI->isBranch(opc) || TMI->isNop(opc))
2411 continue;
2412 else {
Tanya Lattner9532ab92005-03-23 01:47:20 +00002413 if(mOp.getVRegValue()->getType() == Type::FloatTy)
2414 BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::FMOVS, 3).addReg(mOp.getVRegValue()).addRegDef(tmp);
2415 else if(mOp.getVRegValue()->getType() == Type::DoubleTy)
2416 BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::FMOVD, 3).addReg(mOp.getVRegValue()).addRegDef(tmp);
2417 else
2418 BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
2419
2420
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002421 break;
2422 }
2423
2424 }
Tanya Lattnera6457502004-10-14 06:04:28 +00002425
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002426 }
2427 else {
2428 //Remove the phi and replace it with an OR
2429 DEBUG(std::cerr << "Def: " << mOp << "\n");
Tanya Lattner9532ab92005-03-23 01:47:20 +00002430 if(tmp->getType() == Type::FloatTy)
2431 BuildMI(**MB, I, V9::FMOVS, 3).addReg(tmp).addRegDef(mOp.getVRegValue());
2432 else if(tmp->getType() == Type::DoubleTy)
2433 BuildMI(**MB, I, V9::FMOVD, 3).addReg(tmp).addRegDef(mOp.getVRegValue());
2434 else
2435 BuildMI(**MB, I, V9::ORr, 3).addReg(tmp).addImm(0).addRegDef(mOp.getVRegValue());
2436
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002437 worklist.push_back(std::make_pair(*MB,I));
2438 }
2439
2440 }
2441 }
Tanya Lattnera6457502004-10-14 06:04:28 +00002442
Tanya Lattner80f08552004-11-02 21:04:56 +00002443
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002444 }
2445 }
2446
Tanya Lattner80f08552004-11-02 21:04:56 +00002447
2448 if(addToMCFI.size() > 0) {
2449 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
2450 for(unsigned x = 0; x < addToMCFI.size(); ++x) {
2451 tempMvec.addTemp(addToMCFI[x]);
2452 }
2453 addToMCFI.clear();
2454 }
2455
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002456 //Delete the phis
2457 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 +00002458
2459 DEBUG(std::cerr << "Deleting PHI " << *I->second << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002460 I->first->erase(I->second);
2461
2462 }
2463
Tanya Lattnera6457502004-10-14 06:04:28 +00002464
2465 assert((addToMCFI.size() == 0) && "We should have added all TmpInstructions to some MachineCodeForInstruction");
Tanya Lattner20890832004-05-28 20:14:12 +00002466}
2467
2468
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002469void ModuloSchedulingPass::reconstructLoop(MachineBasicBlock *BB) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00002470
Tanya Lattnerdb40cf12005-02-10 17:02:58 +00002471 TIME_REGION(X, "reconstructLoop");
2472
2473
Tanya Lattner420025b2004-10-10 22:44:35 +00002474 DEBUG(std::cerr << "Reconstructing Loop\n");
2475
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002476 //First find the value *'s that we need to "save"
Tanya Lattner9532ab92005-03-23 01:47:20 +00002477 std::map<const Value*, std::pair<const MachineInstr*, int> > valuesToSave;
Tanya Lattner4cffb582004-05-26 06:27:18 +00002478
Tanya Lattner420025b2004-10-10 22:44:35 +00002479 //Keep track of instructions we have already seen and their stage because
2480 //we don't want to "save" values if they are used in the kernel immediately
2481 std::map<const MachineInstr*, int> lastInstrs;
2482
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002483 //Loop over kernel and only look at instructions from a stage > 0
2484 //Look at its operands and save values *'s that are read
Tanya Lattner4cffb582004-05-26 06:27:18 +00002485 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00002486
Tanya Lattner420025b2004-10-10 22:44:35 +00002487 if(I->second !=0) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00002488 //For this instruction, get the Value*'s that it reads and put them into the set.
2489 //Assert if there is an operand of another type that we need to save
Tanya Lattner9532ab92005-03-23 01:47:20 +00002490 const MachineInstr *inst = I->first;
Tanya Lattner420025b2004-10-10 22:44:35 +00002491 lastInstrs[inst] = I->second;
2492
Tanya Lattner4cffb582004-05-26 06:27:18 +00002493 for(unsigned i=0; i < inst->getNumOperands(); ++i) {
2494 //get machine operand
2495 const MachineOperand &mOp = inst->getOperand(i);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002496
Tanya Lattner4cffb582004-05-26 06:27:18 +00002497 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse()) {
2498 //find the value in the map
Tanya Lattner420025b2004-10-10 22:44:35 +00002499 if (const Value* srcI = mOp.getVRegValue()) {
2500
Tanya Lattnerced82222004-11-16 21:31:37 +00002501 if(isa<Constant>(srcI) || isa<Argument>(srcI) || isa<PHINode>(srcI))
Tanya Lattner80f08552004-11-02 21:04:56 +00002502 continue;
2503
Tanya Lattner420025b2004-10-10 22:44:35 +00002504 //Before we declare this Value* one that we should save
2505 //make sure its def is not of the same stage as this instruction
2506 //because it will be consumed before its used
2507 Instruction *defInst = (Instruction*) srcI;
2508
2509 //Should we save this value?
2510 bool save = true;
2511
Tanya Lattnerced82222004-11-16 21:31:37 +00002512 //Continue if not in the def map, loop invariant code does not need to be saved
2513 if(!defMap.count(srcI))
2514 continue;
2515
Tanya Lattner80f08552004-11-02 21:04:56 +00002516 MachineInstr *defInstr = defMap[srcI];
2517
Tanya Lattnerced82222004-11-16 21:31:37 +00002518
Tanya Lattner80f08552004-11-02 21:04:56 +00002519 if(lastInstrs.count(defInstr)) {
Tanya Lattnerced82222004-11-16 21:31:37 +00002520 if(lastInstrs[defInstr] == I->second) {
Tanya Lattner80f08552004-11-02 21:04:56 +00002521 save = false;
Tanya Lattnerced82222004-11-16 21:31:37 +00002522
2523 }
Tanya Lattner420025b2004-10-10 22:44:35 +00002524 }
Tanya Lattner80f08552004-11-02 21:04:56 +00002525
Tanya Lattner420025b2004-10-10 22:44:35 +00002526 if(save)
2527 valuesToSave[srcI] = std::make_pair(I->first, i);
2528 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00002529 }
2530
2531 if(mOp.getType() != MachineOperand::MO_VirtualRegister && mOp.isUse()) {
2532 assert("Our assumption is wrong. We have another type of register that needs to be saved\n");
2533 }
2534 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00002535 }
2536 }
2537
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002538 //The new loop will consist of one or more prologues, the kernel, and one or more epilogues.
2539
2540 //Map to keep track of old to new values
Tanya Lattner420025b2004-10-10 22:44:35 +00002541 std::map<Value*, std::map<int, Value*> > newValues;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002542
Tanya Lattner420025b2004-10-10 22:44:35 +00002543 //Map to keep track of old to new values in kernel
2544 std::map<Value*, std::map<int, Value*> > kernelPHIs;
2545
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002546 //Another map to keep track of what machine basic blocks these new value*s are in since
2547 //they have no llvm instruction equivalent
2548 std::map<Value*, MachineBasicBlock*> newValLocation;
2549
2550 std::vector<MachineBasicBlock*> prologues;
2551 std::vector<BasicBlock*> llvm_prologues;
2552
2553
2554 //Write prologue
2555 writePrologues(prologues, BB, llvm_prologues, valuesToSave, newValues, newValLocation);
Tanya Lattner420025b2004-10-10 22:44:35 +00002556
2557 //Print out epilogues and prologue
2558 DEBUG(for(std::vector<MachineBasicBlock*>::iterator I = prologues.begin(), E = prologues.end();
2559 I != E; ++I) {
2560 std::cerr << "PROLOGUE\n";
2561 (*I)->print(std::cerr);
2562 });
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002563
2564 BasicBlock *llvmKernelBB = new BasicBlock("Kernel", (Function*) (BB->getBasicBlock()->getParent()));
2565 MachineBasicBlock *machineKernelBB = new MachineBasicBlock(llvmKernelBB);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002566 (((MachineBasicBlock*)BB)->getParent())->getBasicBlockList().push_back(machineKernelBB);
Tanya Lattner420025b2004-10-10 22:44:35 +00002567 writeKernel(llvmKernelBB, machineKernelBB, valuesToSave, newValues, newValLocation, kernelPHIs);
2568
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002569
2570 std::vector<MachineBasicBlock*> epilogues;
2571 std::vector<BasicBlock*> llvm_epilogues;
2572
2573 //Write epilogues
Tanya Lattner420025b2004-10-10 22:44:35 +00002574 writeEpilogues(epilogues, BB, llvm_epilogues, valuesToSave, newValues, newValLocation, kernelPHIs);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002575
2576
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002577 //Fix our branches
2578 fixBranches(prologues, llvm_prologues, machineKernelBB, llvmKernelBB, epilogues, llvm_epilogues, BB);
2579
2580 //Remove phis
2581 removePHIs(BB, prologues, epilogues, machineKernelBB, newValLocation);
2582
2583 //Print out epilogues and prologue
2584 DEBUG(for(std::vector<MachineBasicBlock*>::iterator I = prologues.begin(), E = prologues.end();
2585 I != E; ++I) {
2586 std::cerr << "PROLOGUE\n";
2587 (*I)->print(std::cerr);
2588 });
2589
2590 DEBUG(std::cerr << "KERNEL\n");
2591 DEBUG(machineKernelBB->print(std::cerr));
2592
2593 DEBUG(for(std::vector<MachineBasicBlock*>::iterator I = epilogues.begin(), E = epilogues.end();
2594 I != E; ++I) {
2595 std::cerr << "EPILOGUE\n";
2596 (*I)->print(std::cerr);
2597 });
2598
2599
2600 DEBUG(std::cerr << "New Machine Function" << "\n");
2601 DEBUG(std::cerr << BB->getParent() << "\n");
2602
2603
2604}
2605
2606void 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) {
2607
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002608 const TargetInstrInfo *TMI = target.getInstrInfo();
2609
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002610 //Fix prologue branches
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002611 for(unsigned I = 0; I < prologues.size(); ++I) {
2612
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002613 //Find terminator since getFirstTerminator does not work!
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002614 for(MachineBasicBlock::reverse_iterator mInst = prologues[I]->rbegin(), mInstEnd = prologues[I]->rend(); mInst != mInstEnd; ++mInst) {
2615 MachineOpCode OC = mInst->getOpcode();
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002616 //If its a branch update its branchto
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002617 if(TMI->isBranch(OC)) {
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002618 for(unsigned opNum = 0; opNum < mInst->getNumOperands(); ++opNum) {
2619 MachineOperand &mOp = mInst->getOperand(opNum);
2620 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2621 //Check if we are branching to the kernel, if not branch to epilogue
2622 if(mOp.getVRegValue() == BB->getBasicBlock()) {
2623 if(I == prologues.size()-1)
2624 mOp.setValueReg(llvmKernelBB);
2625 else
2626 mOp.setValueReg(llvm_prologues[I+1]);
2627 }
2628 else {
2629 mOp.setValueReg(llvm_epilogues[(llvm_epilogues.size()-1-I)]);
2630 }
2631 }
2632 }
2633
2634 DEBUG(std::cerr << "New Prologue Branch: " << *mInst << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002635 }
2636 }
2637
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002638
2639 //Update llvm basic block with our new branch instr
2640 DEBUG(std::cerr << BB->getBasicBlock()->getTerminator() << "\n");
2641 const BranchInst *branchVal = dyn_cast<BranchInst>(BB->getBasicBlock()->getTerminator());
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002642
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002643 if(I == prologues.size()-1) {
2644 TerminatorInst *newBranch = new BranchInst(llvmKernelBB,
2645 llvm_epilogues[(llvm_epilogues.size()-1-I)],
Tanya Lattnera6457502004-10-14 06:04:28 +00002646 branchVal->getCondition(),
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002647 llvm_prologues[I]);
2648 }
2649 else
2650 TerminatorInst *newBranch = new BranchInst(llvm_prologues[I+1],
2651 llvm_epilogues[(llvm_epilogues.size()-1-I)],
Tanya Lattnera6457502004-10-14 06:04:28 +00002652 branchVal->getCondition(),
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002653 llvm_prologues[I]);
2654
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002655 }
2656
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002657 Value *origBranchExit = 0;
Tanya Lattnera6457502004-10-14 06:04:28 +00002658
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002659 //Fix up kernel machine branches
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002660 for(MachineBasicBlock::reverse_iterator mInst = machineKernelBB->rbegin(), mInstEnd = machineKernelBB->rend(); mInst != mInstEnd; ++mInst) {
2661 MachineOpCode OC = mInst->getOpcode();
2662 if(TMI->isBranch(OC)) {
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002663 for(unsigned opNum = 0; opNum < mInst->getNumOperands(); ++opNum) {
2664 MachineOperand &mOp = mInst->getOperand(opNum);
2665
2666 if(mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2667 if(mOp.getVRegValue() == BB->getBasicBlock())
2668 mOp.setValueReg(llvmKernelBB);
2669 else
2670 if(llvm_epilogues.size() > 0) {
2671 assert(origBranchExit == 0 && "There should only be one branch out of the loop");
2672
2673 origBranchExit = mOp.getVRegValue();
2674 mOp.setValueReg(llvm_epilogues[0]);
2675 }
2676 }
Tanya Lattnera6457502004-10-14 06:04:28 +00002677 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002678 }
2679 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002680
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002681 //Update kernelLLVM branches
2682 const BranchInst *branchVal = dyn_cast<BranchInst>(BB->getBasicBlock()->getTerminator());
Tanya Lattnera6457502004-10-14 06:04:28 +00002683
Tanya Lattner260652a2004-10-30 00:39:07 +00002684 assert(llvm_epilogues.size() != 0 && "We must have epilogues!");
2685
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002686 TerminatorInst *newBranch = new BranchInst(llvmKernelBB,
2687 llvm_epilogues[0],
Tanya Lattnera6457502004-10-14 06:04:28 +00002688 branchVal->getCondition(),
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002689 llvmKernelBB);
2690
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002691
2692 //Lastly add unconditional branches for the epilogues
2693 for(unsigned I = 0; I < epilogues.size(); ++I) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00002694
Tanya Lattnera6457502004-10-14 06:04:28 +00002695 //Now since we don't have fall throughs, add a unconditional branch to the next prologue
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002696 if(I != epilogues.size()-1) {
Tanya Lattner420025b2004-10-10 22:44:35 +00002697 BuildMI(epilogues[I], V9::BA, 1).addPCDisp(llvm_epilogues[I+1]);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002698 //Add unconditional branch to end of epilogue
2699 TerminatorInst *newBranch = new BranchInst(llvm_epilogues[I+1],
2700 llvm_epilogues[I]);
2701
Tanya Lattner4cffb582004-05-26 06:27:18 +00002702 }
Tanya Lattnera6457502004-10-14 06:04:28 +00002703 else {
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002704 BuildMI(epilogues[I], V9::BA, 1).addPCDisp(origBranchExit);
Tanya Lattnera6457502004-10-14 06:04:28 +00002705
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002706
Tanya Lattnera6457502004-10-14 06:04:28 +00002707 //Update last epilogue exit branch
2708 BranchInst *branchVal = (BranchInst*) dyn_cast<BranchInst>(BB->getBasicBlock()->getTerminator());
2709 //Find where we are supposed to branch to
2710 BasicBlock *nextBlock = 0;
2711 for(unsigned j=0; j <branchVal->getNumSuccessors(); ++j) {
2712 if(branchVal->getSuccessor(j) != BB->getBasicBlock())
2713 nextBlock = branchVal->getSuccessor(j);
2714 }
2715
2716 assert((nextBlock != 0) && "Next block should not be null!");
2717 TerminatorInst *newBranch = new BranchInst(nextBlock, llvm_epilogues[I]);
2718 }
2719 //Add one more nop!
2720 BuildMI(epilogues[I], V9::NOP, 0);
2721
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002722 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00002723
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002724 //FIX UP Machine BB entry!!
2725 //We are looking at the predecesor of our loop basic block and we want to change its ba instruction
2726
Tanya Lattner4cffb582004-05-26 06:27:18 +00002727
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002728 //Find all llvm basic blocks that branch to the loop entry and change to our first prologue.
2729 const BasicBlock *llvmBB = BB->getBasicBlock();
2730
Tanya Lattner260652a2004-10-30 00:39:07 +00002731 std::vector<const BasicBlock*>Preds (pred_begin(llvmBB), pred_end(llvmBB));
2732
2733 //for(pred_const_iterator P = pred_begin(llvmBB), PE = pred_end(llvmBB); P != PE; ++PE) {
2734 for(std::vector<const BasicBlock*>::iterator P = Preds.begin(), PE = Preds.end(); P != PE; ++P) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002735 if(*P == llvmBB)
2736 continue;
2737 else {
2738 DEBUG(std::cerr << "Found our entry BB\n");
2739 //Get the Terminator instruction for this basic block and print it out
2740 DEBUG(std::cerr << *((*P)->getTerminator()) << "\n");
2741 //Update the terminator
2742 TerminatorInst *term = ((BasicBlock*)*P)->getTerminator();
2743 for(unsigned i=0; i < term->getNumSuccessors(); ++i) {
2744 if(term->getSuccessor(i) == llvmBB) {
2745 DEBUG(std::cerr << "Replacing successor bb\n");
2746 if(llvm_prologues.size() > 0) {
2747 term->setSuccessor(i, llvm_prologues[0]);
2748 //Also update its corresponding machine instruction
2749 MachineCodeForInstruction & tempMvec =
2750 MachineCodeForInstruction::get(term);
2751 for (unsigned j = 0; j < tempMvec.size(); j++) {
2752 MachineInstr *temp = tempMvec[j];
2753 MachineOpCode opc = temp->getOpcode();
2754 if(TMI->isBranch(opc)) {
2755 DEBUG(std::cerr << *temp << "\n");
2756 //Update branch
2757 for(unsigned opNum = 0; opNum < temp->getNumOperands(); ++opNum) {
2758 MachineOperand &mOp = temp->getOperand(opNum);
2759 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2760 mOp.setValueReg(llvm_prologues[0]);
2761 }
2762 }
2763 }
2764 }
2765 }
2766 else {
2767 term->setSuccessor(i, llvmKernelBB);
2768 //Also update its corresponding machine instruction
2769 MachineCodeForInstruction & tempMvec =
2770 MachineCodeForInstruction::get(term);
2771 for (unsigned j = 0; j < tempMvec.size(); j++) {
2772 MachineInstr *temp = tempMvec[j];
2773 MachineOpCode opc = temp->getOpcode();
2774 if(TMI->isBranch(opc)) {
2775 DEBUG(std::cerr << *temp << "\n");
2776 //Update branch
2777 for(unsigned opNum = 0; opNum < temp->getNumOperands(); ++opNum) {
2778 MachineOperand &mOp = temp->getOperand(opNum);
2779 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2780 mOp.setValueReg(llvmKernelBB);
2781 }
2782 }
2783 }
2784 }
2785 }
2786 }
2787 }
2788 break;
2789 }
2790 }
2791
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002792
Tanya Lattner420025b2004-10-10 22:44:35 +00002793 //BB->getParent()->getBasicBlockList().erase(BB);
Tanya Lattner4cffb582004-05-26 06:27:18 +00002794
2795}
2796