blob: 7a3f267450dfb2d6e262f66424ebac64b4899580 [file] [log] [blame]
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001//===-- ModuloScheduling.cpp - ModuloScheduling ----------------*- C++ -*-===//
2//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Tanya Lattnerd14b8372004-03-01 02:50:01 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Tanya Lattnerd14b8372004-03-01 02:50:01 +00009//
Tanya Lattner0a88d2d2004-07-30 23:36:10 +000010// This ModuloScheduling pass is based on the Swing Modulo Scheduling
11// algorithm.
Misha Brukman82fd8d82004-08-02 13:59:10 +000012//
Guochun Shif1c154f2003-03-27 17:57:44 +000013//===----------------------------------------------------------------------===//
14
Tanya Lattnerd14b8372004-03-01 02:50:01 +000015#define DEBUG_TYPE "ModuloSched"
16
17#include "ModuloScheduling.h"
Tanya Lattner0a88d2d2004-07-30 23:36:10 +000018#include "llvm/Instructions.h"
19#include "llvm/Function.h"
Tanya Lattnerd14b8372004-03-01 02:50:01 +000020#include "llvm/CodeGen/MachineFunction.h"
21#include "llvm/CodeGen/Passes.h"
22#include "llvm/Support/CFG.h"
23#include "llvm/Target/TargetSchedInfo.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000024#include "llvm/Support/Debug.h"
25#include "llvm/Support/GraphWriter.h"
26#include "llvm/ADT/StringExtras.h"
Tanya Lattnere1df2122004-11-22 20:41:24 +000027#include "llvm/ADT/Statistic.h"
Misha Brukman82fd8d82004-08-02 13:59:10 +000028#include <cmath>
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +000029#include <algorithm>
Tanya Lattnerd14b8372004-03-01 02:50:01 +000030#include <fstream>
31#include <sstream>
Misha Brukman82fd8d82004-08-02 13:59:10 +000032#include <utility>
33#include <vector>
Misha Brukman7da1e6e2004-10-10 23:34:50 +000034#include "../MachineCodeForInstruction.h"
35#include "../SparcV9TmpInstr.h"
36#include "../SparcV9Internals.h"
37#include "../SparcV9RegisterInfo.h"
Tanya Lattnerd14b8372004-03-01 02:50:01 +000038using namespace llvm;
39
40/// Create ModuloSchedulingPass
41///
42FunctionPass *llvm::createModuloSchedulingPass(TargetMachine & targ) {
43 DEBUG(std::cerr << "Created ModuloSchedulingPass\n");
44 return new ModuloSchedulingPass(targ);
45}
46
Tanya Lattner0a88d2d2004-07-30 23:36:10 +000047
48//Graph Traits for printing out the dependence graph
Tanya Lattnerd14b8372004-03-01 02:50:01 +000049template<typename GraphType>
50static void WriteGraphToFile(std::ostream &O, const std::string &GraphName,
51 const GraphType &GT) {
52 std::string Filename = GraphName + ".dot";
53 O << "Writing '" << Filename << "'...";
54 std::ofstream F(Filename.c_str());
55
56 if (F.good())
57 WriteGraph(F, GT);
58 else
59 O << " error opening file for writing!";
60 O << "\n";
61};
Guochun Shif1c154f2003-03-27 17:57:44 +000062
Tanya Lattner0a88d2d2004-07-30 23:36:10 +000063//Graph Traits for printing out the dependence graph
Brian Gaeked0fde302003-11-11 22:41:34 +000064namespace llvm {
Tanya Lattnere1df2122004-11-22 20:41:24 +000065 Statistic<> ValidLoops("modulosched-validLoops", "Number of candidate loops modulo-scheduled");
66 Statistic<> MSLoops("modulosched-schedLoops", "Number of loops successfully modulo-scheduled");
67 Statistic<> IncreasedII("modulosched-increasedII", "Number of times we had to increase II");
Brian Gaeked0fde302003-11-11 22:41:34 +000068
Tanya Lattnerd14b8372004-03-01 02:50:01 +000069 template<>
70 struct DOTGraphTraits<MSchedGraph*> : public DefaultDOTGraphTraits {
71 static std::string getGraphName(MSchedGraph *F) {
72 return "Dependence Graph";
73 }
Guochun Shi8f1d4ab2003-06-08 23:16:07 +000074
Tanya Lattnerd14b8372004-03-01 02:50:01 +000075 static std::string getNodeLabel(MSchedGraphNode *Node, MSchedGraph *Graph) {
76 if (Node->getInst()) {
77 std::stringstream ss;
78 ss << *(Node->getInst());
79 return ss.str(); //((MachineInstr*)Node->getInst());
80 }
81 else
82 return "No Inst";
83 }
84 static std::string getEdgeSourceLabel(MSchedGraphNode *Node,
85 MSchedGraphNode::succ_iterator I) {
86 //Label each edge with the type of dependence
87 std::string edgelabel = "";
88 switch (I.getEdge().getDepOrderType()) {
89
90 case MSchedGraphEdge::TrueDep:
91 edgelabel = "True";
92 break;
93
94 case MSchedGraphEdge::AntiDep:
95 edgelabel = "Anti";
96 break;
97
98 case MSchedGraphEdge::OutputDep:
99 edgelabel = "Output";
100 break;
101
102 default:
103 edgelabel = "Unknown";
104 break;
105 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000106
107 //FIXME
108 int iteDiff = I.getEdge().getIteDiff();
109 std::string intStr = "(IteDiff: ";
110 intStr += itostr(iteDiff);
111
112 intStr += ")";
113 edgelabel += intStr;
114
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000115 return edgelabel;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000116 }
Guochun Shif1c154f2003-03-27 17:57:44 +0000117 };
Guochun Shif1c154f2003-03-27 17:57:44 +0000118}
Tanya Lattner4f839cc2003-08-28 17:12:14 +0000119
Misha Brukmanaa41c3c2003-10-10 17:41:32 +0000120/// ModuloScheduling::runOnFunction - main transformation entry point
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000121/// The Swing Modulo Schedule algorithm has three basic steps:
122/// 1) Computation and Analysis of the dependence graph
123/// 2) Ordering of the nodes
124/// 3) Scheduling
125///
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000126bool ModuloSchedulingPass::runOnFunction(Function &F) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000127
Tanya Lattner4f839cc2003-08-28 17:12:14 +0000128 bool Changed = false;
Tanya Lattnerced82222004-11-16 21:31:37 +0000129 int numMS = 0;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000130
Tanya Lattner420025b2004-10-10 22:44:35 +0000131 DEBUG(std::cerr << "Creating ModuloSchedGraph for each valid BasicBlock in " + F.getName() + "\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000132
133 //Get MachineFunction
134 MachineFunction &MF = MachineFunction::get(&F);
Tanya Lattner260652a2004-10-30 00:39:07 +0000135
136
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000137 //Worklist
138 std::vector<MachineBasicBlock*> Worklist;
139
140 //Iterate over BasicBlocks and put them into our worklist if they are valid
141 for (MachineFunction::iterator BI = MF.begin(); BI != MF.end(); ++BI)
Tanya Lattnere1df2122004-11-22 20:41:24 +0000142 if(MachineBBisValid(BI)) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000143 Worklist.push_back(&*BI);
Tanya Lattnere1df2122004-11-22 20:41:24 +0000144 ++ValidLoops;
145 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000146
Tanya Lattner80f08552004-11-02 21:04:56 +0000147 defaultInst = 0;
148
Tanya Lattner420025b2004-10-10 22:44:35 +0000149 DEBUG(if(Worklist.size() == 0) std::cerr << "No single basic block loops in function to ModuloSchedule\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000150
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000151 //Iterate over the worklist and perform scheduling
152 for(std::vector<MachineBasicBlock*>::iterator BI = Worklist.begin(),
153 BE = Worklist.end(); BI != BE; ++BI) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000154
Tanya Lattnerced82222004-11-16 21:31:37 +0000155 CreateDefMap(*BI);
156
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000157 MSchedGraph *MSG = new MSchedGraph(*BI, target);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000158
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000159 //Write Graph out to file
160 DEBUG(WriteGraphToFile(std::cerr, F.getName(), MSG));
161
162 //Print out BB for debugging
Tanya Lattner420025b2004-10-10 22:44:35 +0000163 DEBUG(std::cerr << "ModuloScheduling BB: \n"; (*BI)->print(std::cerr));
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000164
165 //Calculate Resource II
166 int ResMII = calculateResMII(*BI);
167
168 //Calculate Recurrence II
169 int RecMII = calculateRecMII(MSG, ResMII);
170
171 //Our starting initiation interval is the maximum of RecMII and ResMII
172 II = std::max(RecMII, ResMII);
173
174 //Print out II, RecMII, and ResMII
Tanya Lattner260652a2004-10-30 00:39:07 +0000175 DEBUG(std::cerr << "II starts out as " << II << " ( RecMII=" << RecMII << " and ResMII=" << ResMII << ")\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000176
Tanya Lattner260652a2004-10-30 00:39:07 +0000177 //Dump node properties if in debug mode
178 DEBUG(for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(),
179 E = nodeToAttributesMap.end(); I !=E; ++I) {
180 std::cerr << "Node: " << *(I->first) << " ASAP: " << I->second.ASAP << " ALAP: "
181 << I->second.ALAP << " MOB: " << I->second.MOB << " Depth: " << I->second.depth
182 << " Height: " << I->second.height << "\n";
183 });
184
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000185 //Calculate Node Properties
186 calculateNodeAttributes(MSG, ResMII);
187
188 //Dump node properties if in debug mode
189 DEBUG(for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(),
190 E = nodeToAttributesMap.end(); I !=E; ++I) {
191 std::cerr << "Node: " << *(I->first) << " ASAP: " << I->second.ASAP << " ALAP: "
192 << I->second.ALAP << " MOB: " << I->second.MOB << " Depth: " << I->second.depth
193 << " Height: " << I->second.height << "\n";
194 });
195
196 //Put nodes in order to schedule them
197 computePartialOrder();
198
199 //Dump out partial order
Tanya Lattner260652a2004-10-30 00:39:07 +0000200 DEBUG(for(std::vector<std::set<MSchedGraphNode*> >::iterator I = partialOrder.begin(),
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000201 E = partialOrder.end(); I !=E; ++I) {
202 std::cerr << "Start set in PO\n";
Tanya Lattner260652a2004-10-30 00:39:07 +0000203 for(std::set<MSchedGraphNode*>::iterator J = I->begin(), JE = I->end(); J != JE; ++J)
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000204 std::cerr << "PO:" << **J << "\n";
205 });
206
207 //Place nodes in final order
208 orderNodes();
209
210 //Dump out order of nodes
211 DEBUG(for(std::vector<MSchedGraphNode*>::iterator I = FinalNodeOrder.begin(), E = FinalNodeOrder.end(); I != E; ++I) {
212 std::cerr << "FO:" << **I << "\n";
213 });
214
215 //Finally schedule nodes
Tanya Lattnerad7654f2004-12-02 07:22:15 +0000216 bool haveSched = computeSchedule();
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000217
218 //Print out final schedule
219 DEBUG(schedule.print(std::cerr));
220
Tanya Lattner260652a2004-10-30 00:39:07 +0000221 //Final scheduling step is to reconstruct the loop only if we actual have
222 //stage > 0
Tanya Lattnerad7654f2004-12-02 07:22:15 +0000223 if(schedule.getMaxStage() != 0 && haveSched) {
Tanya Lattner260652a2004-10-30 00:39:07 +0000224 reconstructLoop(*BI);
Tanya Lattnere1df2122004-11-22 20:41:24 +0000225 ++MSLoops;
Tanya Lattnerced82222004-11-16 21:31:37 +0000226 Changed = true;
227 }
Tanya Lattner260652a2004-10-30 00:39:07 +0000228 else
Tanya Lattnerad7654f2004-12-02 07:22:15 +0000229 DEBUG(std::cerr << "Max stage is 0, so no change in loop or reached cap\n");
Tanya Lattner260652a2004-10-30 00:39:07 +0000230
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000231 //Clear out our maps for the next basic block that is processed
232 nodeToAttributesMap.clear();
233 partialOrder.clear();
234 recurrenceList.clear();
235 FinalNodeOrder.clear();
236 schedule.clear();
Tanya Lattnerced82222004-11-16 21:31:37 +0000237 defMap.clear();
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000238 //Clean up. Nuke old MachineBB and llvmBB
239 //BasicBlock *llvmBB = (BasicBlock*) (*BI)->getBasicBlock();
240 //Function *parent = (Function*) llvmBB->getParent();
241 //Should't std::find work??
242 //parent->getBasicBlockList().erase(std::find(parent->getBasicBlockList().begin(), parent->getBasicBlockList().end(), *llvmBB));
243 //parent->getBasicBlockList().erase(llvmBB);
244
245 //delete(llvmBB);
246 //delete(*BI);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000247 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000248
Tanya Lattner4f839cc2003-08-28 17:12:14 +0000249 return Changed;
250}
Brian Gaeked0fde302003-11-11 22:41:34 +0000251
Tanya Lattnerced82222004-11-16 21:31:37 +0000252void ModuloSchedulingPass::CreateDefMap(MachineBasicBlock *BI) {
253 defaultInst = 0;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000254
Tanya Lattnerced82222004-11-16 21:31:37 +0000255 for(MachineBasicBlock::iterator I = BI->begin(), E = BI->end(); I != E; ++I) {
256 for(unsigned opNum = 0; opNum < I->getNumOperands(); ++opNum) {
257 const MachineOperand &mOp = I->getOperand(opNum);
258 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef()) {
Tanya Lattnere1df2122004-11-22 20:41:24 +0000259 //assert if this is the second def we have seen
260 DEBUG(std::cerr << "Putting " << *(mOp.getVRegValue()) << " into map\n");
261 assert(!defMap.count(mOp.getVRegValue()) && "Def already in the map");
262
Tanya Lattnerced82222004-11-16 21:31:37 +0000263 defMap[mOp.getVRegValue()] = &*I;
264 }
265
266 //See if we can use this Value* as our defaultInst
267 if(!defaultInst && mOp.getType() == MachineOperand::MO_VirtualRegister) {
268 Value *V = mOp.getVRegValue();
269 if(!isa<TmpInstruction>(V) && !isa<Argument>(V) && !isa<Constant>(V) && !isa<PHINode>(V))
270 defaultInst = (Instruction*) V;
271 }
272 }
273 }
Tanya Lattnere1df2122004-11-22 20:41:24 +0000274
Tanya Lattnerced82222004-11-16 21:31:37 +0000275 assert(defaultInst && "We must have a default instruction to use as our main point to add to machine code for instruction\n");
276
277}
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000278/// This function checks if a Machine Basic Block is valid for modulo
279/// scheduling. This means that it has no control flow (if/else or
280/// calls) in the block. Currently ModuloScheduling only works on
281/// single basic block loops.
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000282bool ModuloSchedulingPass::MachineBBisValid(const MachineBasicBlock *BI) {
283
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000284 bool isLoop = false;
285
286 //Check first if its a valid loop
287 for(succ_const_iterator I = succ_begin(BI->getBasicBlock()),
288 E = succ_end(BI->getBasicBlock()); I != E; ++I) {
289 if (*I == BI->getBasicBlock()) // has single block loop
290 isLoop = true;
291 }
292
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000293 if(!isLoop)
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000294 return false;
Tanya Lattnerad7654f2004-12-02 07:22:15 +0000295
296 //Check that we have a conditional branch (avoiding MS infinite loops)
297 if(BranchInst *b = dyn_cast<BranchInst>(((BasicBlock*) BI->getBasicBlock())->getTerminator()))
298 if(b->isUnconditional())
299 return false;
300
Tanya Lattnere1df2122004-11-22 20:41:24 +0000301 //Check size of our basic block.. make sure we have more then just the terminator in it
302 if(BI->getBasicBlock()->size() == 1)
303 return false;
304
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000305 //Get Target machine instruction info
306 const TargetInstrInfo *TMI = target.getInstrInfo();
307
308 //Check each instruction and look for calls
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000309 for(MachineBasicBlock::const_iterator I = BI->begin(), E = BI->end(); I != E; ++I) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000310 //Get opcode to check instruction type
311 MachineOpCode OC = I->getOpcode();
312 if(TMI->isCall(OC))
313 return false;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000314 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000315 return true;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000316}
317
318//ResMII is calculated by determining the usage count for each resource
319//and using the maximum.
320//FIXME: In future there should be a way to get alternative resources
321//for each instruction
322int ModuloSchedulingPass::calculateResMII(const MachineBasicBlock *BI) {
323
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000324 const TargetInstrInfo *mii = target.getInstrInfo();
325 const TargetSchedInfo *msi = target.getSchedInfo();
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000326
327 int ResMII = 0;
328
329 //Map to keep track of usage count of each resource
330 std::map<unsigned, unsigned> resourceUsageCount;
331
332 for(MachineBasicBlock::const_iterator I = BI->begin(), E = BI->end(); I != E; ++I) {
333
334 //Get resource usage for this instruction
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000335 InstrRUsage rUsage = msi->getInstrRUsage(I->getOpcode());
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000336 std::vector<std::vector<resourceId_t> > resources = rUsage.resourcesByCycle;
337
338 //Loop over resources in each cycle and increments their usage count
339 for(unsigned i=0; i < resources.size(); ++i)
340 for(unsigned j=0; j < resources[i].size(); ++j) {
341 if( resourceUsageCount.find(resources[i][j]) == resourceUsageCount.end()) {
342 resourceUsageCount[resources[i][j]] = 1;
343 }
344 else {
345 resourceUsageCount[resources[i][j]] = resourceUsageCount[resources[i][j]] + 1;
346 }
347 }
348 }
349
350 //Find maximum usage count
351
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000352 //Get max number of instructions that can be issued at once. (FIXME)
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000353 int issueSlots = msi->maxNumIssueTotal;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000354
355 for(std::map<unsigned,unsigned>::iterator RB = resourceUsageCount.begin(), RE = resourceUsageCount.end(); RB != RE; ++RB) {
Tanya Lattner4cffb582004-05-26 06:27:18 +0000356
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000357 //Get the total number of the resources in our cpu
Tanya Lattner4cffb582004-05-26 06:27:18 +0000358 int resourceNum = CPUResource::getCPUResource(RB->first)->maxNumUsers;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000359
360 //Get total usage count for this resources
361 unsigned usageCount = RB->second;
362
363 //Divide the usage count by either the max number we can issue or the number of
364 //resources (whichever is its upper bound)
365 double finalUsageCount;
Tanya Lattner4cffb582004-05-26 06:27:18 +0000366 if( resourceNum <= issueSlots)
367 finalUsageCount = ceil(1.0 * usageCount / resourceNum);
368 else
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000369 finalUsageCount = ceil(1.0 * usageCount / issueSlots);
370
371
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000372 //Only keep track of the max
373 ResMII = std::max( (int) finalUsageCount, ResMII);
374
375 }
376
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000377 return ResMII;
378
379}
380
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000381/// calculateRecMII - Calculates the value of the highest recurrence
382/// By value we mean the total latency
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000383int ModuloSchedulingPass::calculateRecMII(MSchedGraph *graph, int MII) {
384 std::vector<MSchedGraphNode*> vNodes;
385 //Loop over all nodes in the graph
386 for(MSchedGraph::iterator I = graph->begin(), E = graph->end(); I != E; ++I) {
387 findAllReccurrences(I->second, vNodes, MII);
388 vNodes.clear();
389 }
390
391 int RecMII = 0;
392
393 for(std::set<std::pair<int, std::vector<MSchedGraphNode*> > >::iterator I = recurrenceList.begin(), E=recurrenceList.end(); I !=E; ++I) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000394 DEBUG(for(std::vector<MSchedGraphNode*>::const_iterator N = I->second.begin(), NE = I->second.end(); N != NE; ++N) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000395 std::cerr << **N << "\n";
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000396 });
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000397 RecMII = std::max(RecMII, I->first);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000398 }
399
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000400 return MII;
401}
402
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000403/// calculateNodeAttributes - The following properties are calculated for
404/// each node in the dependence graph: ASAP, ALAP, Depth, Height, and
405/// MOB.
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000406void ModuloSchedulingPass::calculateNodeAttributes(MSchedGraph *graph, int MII) {
407
Tanya Lattner260652a2004-10-30 00:39:07 +0000408 assert(nodeToAttributesMap.empty() && "Node attribute map was not cleared");
409
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000410 //Loop over the nodes and add them to the map
411 for(MSchedGraph::iterator I = graph->begin(), E = graph->end(); I != E; ++I) {
Tanya Lattner260652a2004-10-30 00:39:07 +0000412
413 DEBUG(std::cerr << "Inserting node into attribute map: " << *I->second << "\n");
414
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000415 //Assert if its already in the map
Tanya Lattner260652a2004-10-30 00:39:07 +0000416 assert(nodeToAttributesMap.count(I->second) == 0 &&
417 "Node attributes are already in the map");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000418
419 //Put into the map with default attribute values
420 nodeToAttributesMap[I->second] = MSNodeAttributes();
421 }
422
423 //Create set to deal with reccurrences
424 std::set<MSchedGraphNode*> visitedNodes;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000425
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000426 //Now Loop over map and calculate the node attributes
427 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000428 calculateASAP(I->first, MII, (MSchedGraphNode*) 0);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000429 visitedNodes.clear();
430 }
431
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000432 int maxASAP = findMaxASAP();
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000433 //Calculate ALAP which depends on ASAP being totally calculated
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000434 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
435 calculateALAP(I->first, MII, maxASAP, (MSchedGraphNode*) 0);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000436 visitedNodes.clear();
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000437 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000438
439 //Calculate MOB which depends on ASAP being totally calculated, also do depth and height
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000440 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
441 (I->second).MOB = std::max(0,(I->second).ALAP - (I->second).ASAP);
442
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000443 DEBUG(std::cerr << "MOB: " << (I->second).MOB << " (" << *(I->first) << ")\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000444 calculateDepth(I->first, (MSchedGraphNode*) 0);
445 calculateHeight(I->first, (MSchedGraphNode*) 0);
446 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000447
448
449}
450
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000451/// ignoreEdge - Checks to see if this edge of a recurrence should be ignored or not
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000452bool ModuloSchedulingPass::ignoreEdge(MSchedGraphNode *srcNode, MSchedGraphNode *destNode) {
453 if(destNode == 0 || srcNode ==0)
454 return false;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000455
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000456 bool findEdge = edgesToIgnore.count(std::make_pair(srcNode, destNode->getInEdgeNum(srcNode)));
Tanya Lattner4cffb582004-05-26 06:27:18 +0000457
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000458 return findEdge;
459}
460
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000461
462/// calculateASAP - Calculates the
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000463int ModuloSchedulingPass::calculateASAP(MSchedGraphNode *node, int MII, MSchedGraphNode *destNode) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000464
465 DEBUG(std::cerr << "Calculating ASAP for " << *node << "\n");
466
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000467 //Get current node attributes
468 MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
469
470 if(attributes.ASAP != -1)
471 return attributes.ASAP;
472
473 int maxPredValue = 0;
474
475 //Iterate over all of the predecessors and find max
476 for(MSchedGraphNode::pred_iterator P = node->pred_begin(), E = node->pred_end(); P != E; ++P) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000477
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000478 //Only process if we are not ignoring the edge
479 if(!ignoreEdge(*P, node)) {
480 int predASAP = -1;
481 predASAP = calculateASAP(*P, MII, node);
482
483 assert(predASAP != -1 && "ASAP has not been calculated");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000484 int iteDiff = node->getInEdge(*P).getIteDiff();
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000485
486 int currentPredValue = predASAP + (*P)->getLatency() - (iteDiff * MII);
487 DEBUG(std::cerr << "pred ASAP: " << predASAP << ", iteDiff: " << iteDiff << ", PredLatency: " << (*P)->getLatency() << ", Current ASAP pred: " << currentPredValue << "\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000488 maxPredValue = std::max(maxPredValue, currentPredValue);
489 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000490 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000491
492 attributes.ASAP = maxPredValue;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000493
494 DEBUG(std::cerr << "ASAP: " << attributes.ASAP << " (" << *node << ")\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000495
496 return maxPredValue;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000497}
498
499
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000500int ModuloSchedulingPass::calculateALAP(MSchedGraphNode *node, int MII,
501 int maxASAP, MSchedGraphNode *srcNode) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000502
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000503 DEBUG(std::cerr << "Calculating ALAP for " << *node << "\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000504
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000505 MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
506
507 if(attributes.ALAP != -1)
508 return attributes.ALAP;
509
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000510 if(node->hasSuccessors()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000511
512 //Trying to deal with the issue where the node has successors, but
513 //we are ignoring all of the edges to them. So this is my hack for
514 //now.. there is probably a more elegant way of doing this (FIXME)
515 bool processedOneEdge = false;
516
517 //FIXME, set to something high to start
518 int minSuccValue = 9999999;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000519
520 //Iterate over all of the predecessors and fine max
521 for(MSchedGraphNode::succ_iterator P = node->succ_begin(),
522 E = node->succ_end(); P != E; ++P) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000523
524 //Only process if we are not ignoring the edge
525 if(!ignoreEdge(node, *P)) {
526 processedOneEdge = true;
527 int succALAP = -1;
528 succALAP = calculateALAP(*P, MII, maxASAP, node);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000529
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000530 assert(succALAP != -1 && "Successors ALAP should have been caclulated");
531
532 int iteDiff = P.getEdge().getIteDiff();
533
534 int currentSuccValue = succALAP - node->getLatency() + iteDiff * MII;
535
536 DEBUG(std::cerr << "succ ALAP: " << succALAP << ", iteDiff: " << iteDiff << ", SuccLatency: " << (*P)->getLatency() << ", Current ALAP succ: " << currentSuccValue << "\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000537
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000538 minSuccValue = std::min(minSuccValue, currentSuccValue);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000539 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000540 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000541
542 if(processedOneEdge)
543 attributes.ALAP = minSuccValue;
544
545 else
546 attributes.ALAP = maxASAP;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000547 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000548 else
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000549 attributes.ALAP = maxASAP;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000550
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000551 DEBUG(std::cerr << "ALAP: " << attributes.ALAP << " (" << *node << ")\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000552
553 if(attributes.ALAP < 0)
554 attributes.ALAP = 0;
555
556 return attributes.ALAP;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000557}
558
559int ModuloSchedulingPass::findMaxASAP() {
560 int maxASAP = 0;
561
562 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(),
563 E = nodeToAttributesMap.end(); I != E; ++I)
564 maxASAP = std::max(maxASAP, I->second.ASAP);
565 return maxASAP;
566}
567
568
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000569int ModuloSchedulingPass::calculateHeight(MSchedGraphNode *node,MSchedGraphNode *srcNode) {
570
571 MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000572
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000573 if(attributes.height != -1)
574 return attributes.height;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000575
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000576 int maxHeight = 0;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000577
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000578 //Iterate over all of the predecessors and find max
579 for(MSchedGraphNode::succ_iterator P = node->succ_begin(),
580 E = node->succ_end(); P != E; ++P) {
581
582
583 if(!ignoreEdge(node, *P)) {
584 int succHeight = calculateHeight(*P, node);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000585
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000586 assert(succHeight != -1 && "Successors Height should have been caclulated");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000587
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000588 int currentHeight = succHeight + node->getLatency();
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000589 maxHeight = std::max(maxHeight, currentHeight);
590 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000591 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000592 attributes.height = maxHeight;
593 DEBUG(std::cerr << "Height: " << attributes.height << " (" << *node << ")\n");
594 return maxHeight;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000595}
596
597
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000598int ModuloSchedulingPass::calculateDepth(MSchedGraphNode *node,
599 MSchedGraphNode *destNode) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000600
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000601 MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000602
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000603 if(attributes.depth != -1)
604 return attributes.depth;
605
606 int maxDepth = 0;
607
608 //Iterate over all of the predecessors and fine max
609 for(MSchedGraphNode::pred_iterator P = node->pred_begin(), E = node->pred_end(); P != E; ++P) {
610
611 if(!ignoreEdge(*P, node)) {
612 int predDepth = -1;
613 predDepth = calculateDepth(*P, node);
614
615 assert(predDepth != -1 && "Predecessors ASAP should have been caclulated");
616
617 int currentDepth = predDepth + (*P)->getLatency();
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000618 maxDepth = std::max(maxDepth, currentDepth);
619 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000620 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000621 attributes.depth = maxDepth;
622
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000623 DEBUG(std::cerr << "Depth: " << attributes.depth << " (" << *node << "*)\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000624 return maxDepth;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000625}
626
627
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000628
629void ModuloSchedulingPass::addReccurrence(std::vector<MSchedGraphNode*> &recurrence, int II, MSchedGraphNode *srcBENode, MSchedGraphNode *destBENode) {
630 //Check to make sure that this recurrence is unique
631 bool same = false;
632
633
634 //Loop over all recurrences already in our list
635 for(std::set<std::pair<int, std::vector<MSchedGraphNode*> > >::iterator R = recurrenceList.begin(), RE = recurrenceList.end(); R != RE; ++R) {
636
637 bool all_same = true;
638 //First compare size
639 if(R->second.size() == recurrence.size()) {
640
641 for(std::vector<MSchedGraphNode*>::const_iterator node = R->second.begin(), end = R->second.end(); node != end; ++node) {
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000642 if(std::find(recurrence.begin(), recurrence.end(), *node) == recurrence.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000643 all_same = all_same && false;
644 break;
645 }
646 else
647 all_same = all_same && true;
648 }
649 if(all_same) {
650 same = true;
651 break;
652 }
653 }
654 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000655
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000656 if(!same) {
Tanya Lattner4cffb582004-05-26 06:27:18 +0000657 srcBENode = recurrence.back();
658 destBENode = recurrence.front();
659
660 //FIXME
661 if(destBENode->getInEdge(srcBENode).getIteDiff() == 0) {
662 //DEBUG(std::cerr << "NOT A BACKEDGE\n");
663 //find actual backedge HACK HACK
664 for(unsigned i=0; i< recurrence.size()-1; ++i) {
665 if(recurrence[i+1]->getInEdge(recurrence[i]).getIteDiff() == 1) {
666 srcBENode = recurrence[i];
667 destBENode = recurrence[i+1];
668 break;
669 }
670
671 }
672
673 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000674 DEBUG(std::cerr << "Back Edge to Remove: " << *srcBENode << " to " << *destBENode << "\n");
675 edgesToIgnore.insert(std::make_pair(srcBENode, destBENode->getInEdgeNum(srcBENode)));
676 recurrenceList.insert(std::make_pair(II, recurrence));
677 }
678
679}
680
681void ModuloSchedulingPass::findAllReccurrences(MSchedGraphNode *node,
682 std::vector<MSchedGraphNode*> &visitedNodes,
683 int II) {
684
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000685 if(std::find(visitedNodes.begin(), visitedNodes.end(), node) != visitedNodes.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000686 std::vector<MSchedGraphNode*> recurrence;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000687 bool first = true;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000688 int delay = 0;
689 int distance = 0;
690 int RecMII = II; //Starting value
691 MSchedGraphNode *last = node;
Chris Lattner46c2b3a2004-08-04 03:51:55 +0000692 MSchedGraphNode *srcBackEdge = 0;
693 MSchedGraphNode *destBackEdge = 0;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000694
695
696
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000697 for(std::vector<MSchedGraphNode*>::iterator I = visitedNodes.begin(), E = visitedNodes.end();
698 I !=E; ++I) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000699
700 if(*I == node)
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000701 first = false;
702 if(first)
703 continue;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000704
705 delay = delay + (*I)->getLatency();
706
707 if(*I != node) {
708 int diff = (*I)->getInEdge(last).getIteDiff();
709 distance += diff;
710 if(diff > 0) {
711 srcBackEdge = last;
712 destBackEdge = *I;
713 }
714 }
715
716 recurrence.push_back(*I);
717 last = *I;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000718 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000719
720
721
722 //Get final distance calc
723 distance += node->getInEdge(last).getIteDiff();
Tanya Lattnere1df2122004-11-22 20:41:24 +0000724 DEBUG(std::cerr << "Reccurrence Distance: " << distance << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000725
726 //Adjust II until we get close to the inequality delay - II*distance <= 0
727
728 int value = delay-(RecMII * distance);
729 int lastII = II;
730 while(value <= 0) {
731
732 lastII = RecMII;
733 RecMII--;
734 value = delay-(RecMII * distance);
735 }
736
737
738 DEBUG(std::cerr << "Final II for this recurrence: " << lastII << "\n");
739 addReccurrence(recurrence, lastII, srcBackEdge, destBackEdge);
740 assert(distance != 0 && "Recurrence distance should not be zero");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000741 return;
742 }
743
744 for(MSchedGraphNode::succ_iterator I = node->succ_begin(), E = node->succ_end(); I != E; ++I) {
745 visitedNodes.push_back(node);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000746 findAllReccurrences(*I, visitedNodes, II);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000747 visitedNodes.pop_back();
748 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000749}
750
751
752
753
754
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000755void ModuloSchedulingPass::computePartialOrder() {
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000756
757 //Only push BA branches onto the final node order, we put other branches after it
758 //FIXME: Should we really be pushing branches on it a specific order instead of relying
759 //on BA being there?
Tanya Lattner58fe2f02004-11-29 04:39:47 +0000760 std::vector<MSchedGraphNode*> branches;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000761
762 //Loop over all recurrences and add to our partial order
763 //be sure to remove nodes that are already in the partial order in
764 //a different recurrence and don't add empty recurrences.
765 for(std::set<std::pair<int, std::vector<MSchedGraphNode*> > >::reverse_iterator I = recurrenceList.rbegin(), E=recurrenceList.rend(); I !=E; ++I) {
766
767 //Add nodes that connect this recurrence to the previous recurrence
768
769 //If this is the first recurrence in the partial order, add all predecessors
770 for(std::vector<MSchedGraphNode*>::const_iterator N = I->second.begin(), NE = I->second.end(); N != NE; ++N) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000771
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000772 }
773
774
Tanya Lattner260652a2004-10-30 00:39:07 +0000775 std::set<MSchedGraphNode*> new_recurrence;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000776 //Loop through recurrence and remove any nodes already in the partial order
777 for(std::vector<MSchedGraphNode*>::const_iterator N = I->second.begin(), NE = I->second.end(); N != NE; ++N) {
778 bool found = false;
Tanya Lattner260652a2004-10-30 00:39:07 +0000779 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(), PE = partialOrder.end(); PO != PE; ++PO) {
780 if(PO->count(*N))
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000781 found = true;
782 }
783 if(!found) {
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000784 if((*N)->isBranch()) {
Tanya Lattner58fe2f02004-11-29 04:39:47 +0000785 branches.push_back(*N);
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000786 }
787 else
788 new_recurrence.insert(*N);
789 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000790 if(partialOrder.size() == 0)
791 //For each predecessors, add it to this recurrence ONLY if it is not already in it
792 for(MSchedGraphNode::pred_iterator P = (*N)->pred_begin(),
793 PE = (*N)->pred_end(); P != PE; ++P) {
794
795 //Check if we are supposed to ignore this edge or not
796 if(!ignoreEdge(*P, *N))
797 //Check if already in this recurrence
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000798 if(std::find(I->second.begin(), I->second.end(), *P) == I->second.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000799 //Also need to check if in partial order
800 bool predFound = false;
Tanya Lattner260652a2004-10-30 00:39:07 +0000801 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(), PEND = partialOrder.end(); PO != PEND; ++PO) {
802 if(PO->count(*P))
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000803 predFound = true;
804 }
805
806 if(!predFound)
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000807 if(!new_recurrence.count(*P)) {
808 if((*P)->isBranch()) {
Tanya Lattner58fe2f02004-11-29 04:39:47 +0000809 branches.push_back(*P);
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000810 }
811 else
812 new_recurrence.insert(*P);
813
814 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000815 }
816 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000817 }
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000818
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000819 if(new_recurrence.size() > 0)
820 partialOrder.push_back(new_recurrence);
821 }
822
823 //Add any nodes that are not already in the partial order
Tanya Lattner260652a2004-10-30 00:39:07 +0000824 //Add them in a set, one set per connected component
825 std::set<MSchedGraphNode*> lastNodes;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000826 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
827 bool found = false;
828 //Check if its already in our partial order, if not add it to the final vector
Tanya Lattner260652a2004-10-30 00:39:07 +0000829 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(), PE = partialOrder.end(); PO != PE; ++PO) {
830 if(PO->count(I->first))
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000831 found = true;
832 }
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000833 if(!found) {
834 if(I->first->isBranch()) {
Tanya Lattner58fe2f02004-11-29 04:39:47 +0000835 if(std::find(branches.begin(), branches.end(), I->first) == branches.end())
836 branches.push_back(I->first);
837 }
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000838 else
839 lastNodes.insert(I->first);
840 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000841 }
842
Tanya Lattner260652a2004-10-30 00:39:07 +0000843 //Break up remaining nodes that are not in the partial order
844 //into their connected compoenents
845 while(lastNodes.size() > 0) {
846 std::set<MSchedGraphNode*> ccSet;
847 connectedComponentSet(*(lastNodes.begin()),ccSet, lastNodes);
848 if(ccSet.size() > 0)
849 partialOrder.push_back(ccSet);
850 }
851 //if(lastNodes.size() > 0)
852 //partialOrder.push_back(lastNodes);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000853
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000854 //Clean up branches by putting them in final order
Tanya Lattner58fe2f02004-11-29 04:39:47 +0000855 std::map<unsigned, MSchedGraphNode*> branchOrder;
856 for(std::vector<MSchedGraphNode*>::iterator I = branches.begin(), E = branches.end(); I != E; ++I)
857 branchOrder[(*I)->getIndex()] = *I;
858
859 for(std::map<unsigned, MSchedGraphNode*>::reverse_iterator I = branchOrder.rbegin(), E = branchOrder.rend(); I != E; ++I)
860 FinalNodeOrder.push_back(I->second);
861
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000862}
863
864
Tanya Lattner260652a2004-10-30 00:39:07 +0000865void ModuloSchedulingPass::connectedComponentSet(MSchedGraphNode *node, std::set<MSchedGraphNode*> &ccSet, std::set<MSchedGraphNode*> &lastNodes) {
866
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000867//Add to final set
868if( !ccSet.count(node) && lastNodes.count(node)) {
Tanya Lattner260652a2004-10-30 00:39:07 +0000869 lastNodes.erase(node);
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000870if(node->isBranch())
871 FinalNodeOrder.push_back(node);
872 else
873 ccSet.insert(node);
Tanya Lattner260652a2004-10-30 00:39:07 +0000874 }
875 else
876 return;
877
878 //Loop over successors and recurse if we have not seen this node before
879 for(MSchedGraphNode::succ_iterator node_succ = node->succ_begin(), end=node->succ_end(); node_succ != end; ++node_succ) {
880 connectedComponentSet(*node_succ, ccSet, lastNodes);
881 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000882
Tanya Lattner260652a2004-10-30 00:39:07 +0000883}
884
885void ModuloSchedulingPass::predIntersect(std::set<MSchedGraphNode*> &CurrentSet, std::set<MSchedGraphNode*> &IntersectResult) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000886
887 for(unsigned j=0; j < FinalNodeOrder.size(); ++j) {
888 for(MSchedGraphNode::pred_iterator P = FinalNodeOrder[j]->pred_begin(),
889 E = FinalNodeOrder[j]->pred_end(); P != E; ++P) {
890
891 //Check if we are supposed to ignore this edge or not
892 if(ignoreEdge(*P,FinalNodeOrder[j]))
893 continue;
894
Tanya Lattner260652a2004-10-30 00:39:07 +0000895 if(CurrentSet.count(*P))
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000896 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), *P) == FinalNodeOrder.end())
Tanya Lattner260652a2004-10-30 00:39:07 +0000897 IntersectResult.insert(*P);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000898 }
899 }
900}
901
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000902
Tanya Lattner260652a2004-10-30 00:39:07 +0000903
904
905
906void ModuloSchedulingPass::succIntersect(std::set<MSchedGraphNode*> &CurrentSet, std::set<MSchedGraphNode*> &IntersectResult) {
907
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000908 for(unsigned j=0; j < FinalNodeOrder.size(); ++j) {
909 for(MSchedGraphNode::succ_iterator P = FinalNodeOrder[j]->succ_begin(),
910 E = FinalNodeOrder[j]->succ_end(); P != E; ++P) {
911
912 //Check if we are supposed to ignore this edge or not
913 if(ignoreEdge(FinalNodeOrder[j],*P))
914 continue;
915
Tanya Lattner260652a2004-10-30 00:39:07 +0000916 if(CurrentSet.count(*P))
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000917 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), *P) == FinalNodeOrder.end())
Tanya Lattner260652a2004-10-30 00:39:07 +0000918 IntersectResult.insert(*P);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000919 }
920 }
921}
922
Tanya Lattner260652a2004-10-30 00:39:07 +0000923void dumpIntersection(std::set<MSchedGraphNode*> &IntersectCurrent) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000924 std::cerr << "Intersection (";
Tanya Lattner260652a2004-10-30 00:39:07 +0000925 for(std::set<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(), E = IntersectCurrent.end(); I != E; ++I)
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000926 std::cerr << **I << ", ";
927 std::cerr << ")\n";
928}
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000929
930
931
932void ModuloSchedulingPass::orderNodes() {
933
934 int BOTTOM_UP = 0;
935 int TOP_DOWN = 1;
936
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000937 //Set default order
938 int order = BOTTOM_UP;
939
Tanya Lattnera6ec8f52004-11-24 01:49:10 +0000940
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000941 //Loop over all the sets and place them in the final node order
Tanya Lattner260652a2004-10-30 00:39:07 +0000942 for(std::vector<std::set<MSchedGraphNode*> >::iterator CurrentSet = partialOrder.begin(), E= partialOrder.end(); CurrentSet != E; ++CurrentSet) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000943
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000944 DEBUG(std::cerr << "Processing set in S\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000945 DEBUG(dumpIntersection(*CurrentSet));
946
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000947 //Result of intersection
Tanya Lattner260652a2004-10-30 00:39:07 +0000948 std::set<MSchedGraphNode*> IntersectCurrent;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000949
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000950 predIntersect(*CurrentSet, IntersectCurrent);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000951
952 //If the intersection of predecessor and current set is not empty
953 //sort nodes bottom up
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000954 if(IntersectCurrent.size() != 0) {
955 DEBUG(std::cerr << "Final Node Order Predecessors and Current Set interesection is NOT empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000956 order = BOTTOM_UP;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000957 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000958 //If empty, use successors
959 else {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000960 DEBUG(std::cerr << "Final Node Order Predecessors and Current Set interesection is empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000961
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000962 succIntersect(*CurrentSet, IntersectCurrent);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000963
964 //sort top-down
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000965 if(IntersectCurrent.size() != 0) {
966 DEBUG(std::cerr << "Final Node Order Successors and Current Set interesection is NOT empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000967 order = TOP_DOWN;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000968 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000969 else {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000970 DEBUG(std::cerr << "Final Node Order Successors and Current Set interesection is empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000971 //Find node with max ASAP in current Set
972 MSchedGraphNode *node;
973 int maxASAP = 0;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000974 DEBUG(std::cerr << "Using current set of size " << CurrentSet->size() << "to find max ASAP\n");
Tanya Lattner260652a2004-10-30 00:39:07 +0000975 for(std::set<MSchedGraphNode*>::iterator J = CurrentSet->begin(), JE = CurrentSet->end(); J != JE; ++J) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000976 //Get node attributes
Tanya Lattner260652a2004-10-30 00:39:07 +0000977 MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*J)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000978 //assert(nodeAttr != nodeToAttributesMap.end() && "Node not in attributes map!");
Tanya Lattner260652a2004-10-30 00:39:07 +0000979
980 if(maxASAP <= nodeAttr.ASAP) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000981 maxASAP = nodeAttr.ASAP;
Tanya Lattner260652a2004-10-30 00:39:07 +0000982 node = *J;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000983 }
984 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000985 assert(node != 0 && "In node ordering node should not be null");
Tanya Lattner260652a2004-10-30 00:39:07 +0000986 IntersectCurrent.insert(node);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000987 order = BOTTOM_UP;
988 }
989 }
990
991 //Repeat until all nodes are put into the final order from current set
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000992 while(IntersectCurrent.size() > 0) {
993
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000994 if(order == TOP_DOWN) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000995 DEBUG(std::cerr << "Order is TOP DOWN\n");
996
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000997 while(IntersectCurrent.size() > 0) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000998 DEBUG(std::cerr << "Intersection is not empty, so find heighest height\n");
999
1000 int MOB = 0;
1001 int height = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +00001002 MSchedGraphNode *highestHeightNode = *(IntersectCurrent.begin());
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001003
1004 //Find node in intersection with highest heigh and lowest MOB
Tanya Lattner260652a2004-10-30 00:39:07 +00001005 for(std::set<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(),
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001006 E = IntersectCurrent.end(); I != E; ++I) {
1007
1008 //Get current nodes properties
1009 MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*I)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001010
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001011 if(height < nodeAttr.height) {
1012 highestHeightNode = *I;
1013 height = nodeAttr.height;
1014 MOB = nodeAttr.MOB;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001015 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001016 else if(height == nodeAttr.height) {
1017 if(MOB > nodeAttr.height) {
1018 highestHeightNode = *I;
1019 height = nodeAttr.height;
1020 MOB = nodeAttr.MOB;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001021 }
1022 }
1023 }
1024
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001025 //Append our node with greatest height to the NodeOrder
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001026 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), highestHeightNode) == FinalNodeOrder.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001027 DEBUG(std::cerr << "Adding node to Final Order: " << *highestHeightNode << "\n");
1028 FinalNodeOrder.push_back(highestHeightNode);
1029 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001030
1031 //Remove V from IntersectOrder
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001032 IntersectCurrent.erase(std::find(IntersectCurrent.begin(),
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001033 IntersectCurrent.end(), highestHeightNode));
1034
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001035
1036 //Intersect V's successors with CurrentSet
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001037 for(MSchedGraphNode::succ_iterator P = highestHeightNode->succ_begin(),
1038 E = highestHeightNode->succ_end(); P != E; ++P) {
1039 //if(lower_bound(CurrentSet->begin(),
1040 // CurrentSet->end(), *P) != CurrentSet->end()) {
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001041 if(std::find(CurrentSet->begin(), CurrentSet->end(), *P) != CurrentSet->end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001042 if(ignoreEdge(highestHeightNode, *P))
1043 continue;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001044 //If not already in Intersect, add
Tanya Lattner260652a2004-10-30 00:39:07 +00001045 if(!IntersectCurrent.count(*P))
1046 IntersectCurrent.insert(*P);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001047 }
1048 }
1049 } //End while loop over Intersect Size
1050
1051 //Change direction
1052 order = BOTTOM_UP;
1053
1054 //Reset Intersect to reflect changes in OrderNodes
1055 IntersectCurrent.clear();
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001056 predIntersect(*CurrentSet, IntersectCurrent);
1057
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001058 } //End If TOP_DOWN
1059
1060 //Begin if BOTTOM_UP
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001061 else {
1062 DEBUG(std::cerr << "Order is BOTTOM UP\n");
1063 while(IntersectCurrent.size() > 0) {
1064 DEBUG(std::cerr << "Intersection of size " << IntersectCurrent.size() << ", finding highest depth\n");
1065
1066 //dump intersection
1067 DEBUG(dumpIntersection(IntersectCurrent));
1068 //Get node with highest depth, if a tie, use one with lowest
1069 //MOB
1070 int MOB = 0;
1071 int depth = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +00001072 MSchedGraphNode *highestDepthNode = *(IntersectCurrent.begin());
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001073
Tanya Lattner260652a2004-10-30 00:39:07 +00001074 for(std::set<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(),
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001075 E = IntersectCurrent.end(); I != E; ++I) {
1076 //Find node attribute in graph
1077 MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*I)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001078
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001079 if(depth < nodeAttr.depth) {
1080 highestDepthNode = *I;
1081 depth = nodeAttr.depth;
1082 MOB = nodeAttr.MOB;
1083 }
1084 else if(depth == nodeAttr.depth) {
1085 if(MOB > nodeAttr.MOB) {
1086 highestDepthNode = *I;
1087 depth = nodeAttr.depth;
1088 MOB = nodeAttr.MOB;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001089 }
1090 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001091 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001092
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001093
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001094
1095 //Append highest depth node to the NodeOrder
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001096 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), highestDepthNode) == FinalNodeOrder.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001097 DEBUG(std::cerr << "Adding node to Final Order: " << *highestDepthNode << "\n");
1098 FinalNodeOrder.push_back(highestDepthNode);
1099 }
1100 //Remove heightestDepthNode from IntersectOrder
Tanya Lattner260652a2004-10-30 00:39:07 +00001101 IntersectCurrent.erase(highestDepthNode);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001102
1103
1104 //Intersect heightDepthNode's pred with CurrentSet
1105 for(MSchedGraphNode::pred_iterator P = highestDepthNode->pred_begin(),
1106 E = highestDepthNode->pred_end(); P != E; ++P) {
Tanya Lattner260652a2004-10-30 00:39:07 +00001107 if(CurrentSet->count(*P)) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001108 if(ignoreEdge(*P, highestDepthNode))
1109 continue;
1110
1111 //If not already in Intersect, add
Tanya Lattner260652a2004-10-30 00:39:07 +00001112 if(!IntersectCurrent.count(*P))
1113 IntersectCurrent.insert(*P);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001114 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001115 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001116
1117 } //End while loop over Intersect Size
1118
1119 //Change order
1120 order = TOP_DOWN;
1121
1122 //Reset IntersectCurrent to reflect changes in OrderNodes
1123 IntersectCurrent.clear();
1124 succIntersect(*CurrentSet, IntersectCurrent);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001125 } //End if BOTTOM_DOWN
1126
Tanya Lattner420025b2004-10-10 22:44:35 +00001127 DEBUG(std::cerr << "Current Intersection Size: " << IntersectCurrent.size() << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001128 }
1129 //End Wrapping while loop
Tanya Lattner420025b2004-10-10 22:44:35 +00001130 DEBUG(std::cerr << "Ending Size of Current Set: " << CurrentSet->size() << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001131 }//End for over all sets of nodes
Tanya Lattner420025b2004-10-10 22:44:35 +00001132
1133 //FIXME: As the algorithm stands it will NEVER add an instruction such as ba (with no
1134 //data dependencies) to the final order. We add this manually. It will always be
1135 //in the last set of S since its not part of a recurrence
1136 //Loop over all the sets and place them in the final node order
Tanya Lattner260652a2004-10-30 00:39:07 +00001137 std::vector<std::set<MSchedGraphNode*> > ::reverse_iterator LastSet = partialOrder.rbegin();
1138 for(std::set<MSchedGraphNode*>::iterator CurrentNode = LastSet->begin(), LastNode = LastSet->end();
Tanya Lattner420025b2004-10-10 22:44:35 +00001139 CurrentNode != LastNode; ++CurrentNode) {
1140 if((*CurrentNode)->getInst()->getOpcode() == V9::BA)
1141 FinalNodeOrder.push_back(*CurrentNode);
1142 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001143 //Return final Order
1144 //return FinalNodeOrder;
1145}
1146
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001147bool ModuloSchedulingPass::computeSchedule() {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001148
1149 bool success = false;
1150
Tanya Lattner260652a2004-10-30 00:39:07 +00001151 //FIXME: Should be set to max II of the original loop
1152 //Cap II in order to prevent infinite loop
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001153 int capII = 100;
Tanya Lattner260652a2004-10-30 00:39:07 +00001154
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001155 while(!success) {
Tanya Lattner58fe2f02004-11-29 04:39:47 +00001156
1157 int branchES = II - 1;
1158 int branchLS = II - 1;
1159 bool lastBranch = true;
1160
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001161 //Loop over the final node order and process each node
1162 for(std::vector<MSchedGraphNode*>::iterator I = FinalNodeOrder.begin(),
1163 E = FinalNodeOrder.end(); I != E; ++I) {
1164
1165 //CalculateEarly and Late start
1166 int EarlyStart = -1;
1167 int LateStart = 99999; //Set to something higher then we would ever expect (FIXME)
1168 bool hasSucc = false;
1169 bool hasPred = false;
Tanya Lattner4cffb582004-05-26 06:27:18 +00001170
1171 if(!(*I)->isBranch()) {
1172 //Loop over nodes in the schedule and determine if they are predecessors
1173 //or successors of the node we are trying to schedule
1174 for(MSSchedule::schedule_iterator nodesByCycle = schedule.begin(), nodesByCycleEnd = schedule.end();
1175 nodesByCycle != nodesByCycleEnd; ++nodesByCycle) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001176
Tanya Lattner4cffb582004-05-26 06:27:18 +00001177 //For this cycle, get the vector of nodes schedule and loop over it
1178 for(std::vector<MSchedGraphNode*>::iterator schedNode = nodesByCycle->second.begin(), SNE = nodesByCycle->second.end(); schedNode != SNE; ++schedNode) {
1179
1180 if((*I)->isPredecessor(*schedNode)) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001181 if(!ignoreEdge(*schedNode, *I)) {
1182 int diff = (*I)->getInEdge(*schedNode).getIteDiff();
Tanya Lattner4cffb582004-05-26 06:27:18 +00001183 int ES_Temp = nodesByCycle->first + (*schedNode)->getLatency() - diff * II;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001184 DEBUG(std::cerr << "Diff: " << diff << " Cycle: " << nodesByCycle->first << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001185 DEBUG(std::cerr << "Temp EarlyStart: " << ES_Temp << " Prev EarlyStart: " << EarlyStart << "\n");
1186 EarlyStart = std::max(EarlyStart, ES_Temp);
1187 hasPred = true;
1188 }
1189 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001190 if((*I)->isSuccessor(*schedNode)) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001191 if(!ignoreEdge(*I,*schedNode)) {
1192 int diff = (*schedNode)->getInEdge(*I).getIteDiff();
Tanya Lattner4cffb582004-05-26 06:27:18 +00001193 int LS_Temp = nodesByCycle->first - (*I)->getLatency() + diff * II;
1194 DEBUG(std::cerr << "Diff: " << diff << " Cycle: " << nodesByCycle->first << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001195 DEBUG(std::cerr << "Temp LateStart: " << LS_Temp << " Prev LateStart: " << LateStart << "\n");
1196 LateStart = std::min(LateStart, LS_Temp);
1197 hasSucc = true;
1198 }
1199 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001200 }
1201 }
1202 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001203 else {
Tanya Lattner58fe2f02004-11-29 04:39:47 +00001204 if(lastBranch) {
1205 EarlyStart = branchES;
1206 LateStart = branchLS;
1207 lastBranch = false;
1208 --branchES;
1209 branchLS = 0;
Tanya Lattner420025b2004-10-10 22:44:35 +00001210 }
1211 else {
Tanya Lattner58fe2f02004-11-29 04:39:47 +00001212 EarlyStart = branchES;
1213 LateStart = branchLS;
Tanya Lattner420025b2004-10-10 22:44:35 +00001214 assert( (EarlyStart >= 0) && (LateStart >=0) && "EarlyStart and LateStart must be greater then 0");
Tanya Lattner58fe2f02004-11-29 04:39:47 +00001215 --branchES;
Tanya Lattner420025b2004-10-10 22:44:35 +00001216 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001217 hasPred = 1;
1218 hasSucc = 1;
1219 }
1220
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001221
1222 DEBUG(std::cerr << "Has Successors: " << hasSucc << ", Has Pred: " << hasPred << "\n");
1223 DEBUG(std::cerr << "EarlyStart: " << EarlyStart << ", LateStart: " << LateStart << "\n");
1224
1225 //Check if the node has no pred or successors and set Early Start to its ASAP
1226 if(!hasSucc && !hasPred)
1227 EarlyStart = nodeToAttributesMap.find(*I)->second.ASAP;
1228
1229 //Now, try to schedule this node depending upon its pred and successor in the schedule
1230 //already
1231 if(!hasSucc && hasPred)
1232 success = scheduleNode(*I, EarlyStart, (EarlyStart + II -1));
1233 else if(!hasPred && hasSucc)
1234 success = scheduleNode(*I, LateStart, (LateStart - II +1));
1235 else if(hasPred && hasSucc)
1236 success = scheduleNode(*I, EarlyStart, std::min(LateStart, (EarlyStart + II -1)));
1237 else
1238 success = scheduleNode(*I, EarlyStart, EarlyStart + II - 1);
1239
1240 if(!success) {
Tanya Lattnere1df2122004-11-22 20:41:24 +00001241 ++IncreasedII;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001242 ++II;
1243 schedule.clear();
1244 break;
1245 }
1246
1247 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001248
Tanya Lattner260652a2004-10-30 00:39:07 +00001249 if(success) {
1250 DEBUG(std::cerr << "Constructing Schedule Kernel\n");
1251 success = schedule.constructKernel(II);
1252 DEBUG(std::cerr << "Done Constructing Schedule Kernel\n");
1253 if(!success) {
Tanya Lattnere1df2122004-11-22 20:41:24 +00001254 ++IncreasedII;
Tanya Lattner260652a2004-10-30 00:39:07 +00001255 ++II;
1256 schedule.clear();
1257 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001258 }
Tanya Lattner260652a2004-10-30 00:39:07 +00001259
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001260 if(II >= capII)
1261 return false;
1262
Tanya Lattner260652a2004-10-30 00:39:07 +00001263 assert(II < capII && "The II should not exceed the original loop number of cycles");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001264 }
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001265 return true;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001266}
1267
1268
1269bool ModuloSchedulingPass::scheduleNode(MSchedGraphNode *node,
1270 int start, int end) {
1271 bool success = false;
1272
1273 DEBUG(std::cerr << *node << " (Start Cycle: " << start << ", End Cycle: " << end << ")\n");
1274
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001275 //Make sure start and end are not negative
Tanya Lattner260652a2004-10-30 00:39:07 +00001276 if(start < 0) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001277 start = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +00001278
1279 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001280 if(end < 0)
1281 end = 0;
1282
1283 bool forward = true;
1284 if(start > end)
1285 forward = false;
1286
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001287 bool increaseSC = true;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001288 int cycle = start ;
1289
1290
1291 while(increaseSC) {
1292
1293 increaseSC = false;
1294
Tanya Lattner4cffb582004-05-26 06:27:18 +00001295 increaseSC = schedule.insert(node, cycle);
1296
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001297 if(!increaseSC)
1298 return true;
1299
1300 //Increment cycle to try again
1301 if(forward) {
1302 ++cycle;
1303 DEBUG(std::cerr << "Increase cycle: " << cycle << "\n");
1304 if(cycle > end)
1305 return false;
1306 }
1307 else {
1308 --cycle;
1309 DEBUG(std::cerr << "Decrease cycle: " << cycle << "\n");
1310 if(cycle < end)
1311 return false;
1312 }
1313 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001314
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001315 return success;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001316}
Tanya Lattner4cffb582004-05-26 06:27:18 +00001317
Tanya Lattner420025b2004-10-10 22:44:35 +00001318void ModuloSchedulingPass::writePrologues(std::vector<MachineBasicBlock *> &prologues, MachineBasicBlock *origBB, std::vector<BasicBlock*> &llvm_prologues, std::map<const Value*, std::pair<const MSchedGraphNode*, int> > &valuesToSave, std::map<Value*, std::map<int, Value*> > &newValues, std::map<Value*, MachineBasicBlock*> &newValLocation) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00001319
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001320 //Keep a map to easily know whats in the kernel
Tanya Lattner4cffb582004-05-26 06:27:18 +00001321 std::map<int, std::set<const MachineInstr*> > inKernel;
1322 int maxStageCount = 0;
1323
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001324 //Keep a map of new values we consumed in case they need to be added back
1325 std::map<Value*, std::map<int, Value*> > consumedValues;
1326
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001327 MSchedGraphNode *branch = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +00001328 MSchedGraphNode *BAbranch = 0;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001329
Tanya Lattnere1df2122004-11-22 20:41:24 +00001330 schedule.print(std::cerr);
1331
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001332 std::vector<MSchedGraphNode*> branches;
1333
Tanya Lattner4cffb582004-05-26 06:27:18 +00001334 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
1335 maxStageCount = std::max(maxStageCount, I->second);
1336
1337 //Ignore the branch, we will handle this separately
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001338 if(I->first->isBranch()) {
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001339 branches.push_back(I->first);
Tanya Lattner4cffb582004-05-26 06:27:18 +00001340 continue;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001341 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001342
1343 //Put int the map so we know what instructions in each stage are in the kernel
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001344 DEBUG(std::cerr << "Inserting instruction " << *(I->first->getInst()) << " into map at stage " << I->second << "\n");
1345 inKernel[I->second].insert(I->first->getInst());
Tanya Lattner4cffb582004-05-26 06:27:18 +00001346 }
1347
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001348 //Get target information to look at machine operands
1349 const TargetInstrInfo *mii = target.getInstrInfo();
1350
1351 //Now write the prologues
1352 for(int i = 0; i < maxStageCount; ++i) {
1353 BasicBlock *llvmBB = new BasicBlock("PROLOGUE", (Function*) (origBB->getBasicBlock()->getParent()));
Tanya Lattner4cffb582004-05-26 06:27:18 +00001354 MachineBasicBlock *machineBB = new MachineBasicBlock(llvmBB);
1355
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001356 DEBUG(std::cerr << "i=" << i << "\n");
1357 for(int j = 0; j <= i; ++j) {
1358 for(MachineBasicBlock::const_iterator MI = origBB->begin(), ME = origBB->end(); ME != MI; ++MI) {
1359 if(inKernel[j].count(&*MI)) {
Tanya Lattner420025b2004-10-10 22:44:35 +00001360 MachineInstr *instClone = MI->clone();
1361 machineBB->push_back(instClone);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001362
Tanya Lattner420025b2004-10-10 22:44:35 +00001363 DEBUG(std::cerr << "Cloning: " << *MI << "\n");
1364
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001365 Instruction *tmp;
1366
1367 //After cloning, we may need to save the value that this instruction defines
1368 for(unsigned opNum=0; opNum < MI->getNumOperands(); ++opNum) {
1369 //get machine operand
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001370 MachineOperand &mOp = instClone->getOperand(opNum);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001371 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef()) {
1372
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001373 //Check if this is a value we should save
1374 if(valuesToSave.count(mOp.getVRegValue())) {
1375 //Save copy in tmpInstruction
1376 tmp = new TmpInstruction(mOp.getVRegValue());
1377
Tanya Lattner80f08552004-11-02 21:04:56 +00001378 //Add TmpInstruction to safe LLVM Instruction MCFI
1379 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001380 tempMvec.addTemp((Value*) tmp);
1381
Tanya Lattner420025b2004-10-10 22:44:35 +00001382 DEBUG(std::cerr << "Value: " << *(mOp.getVRegValue()) << " New Value: " << *tmp << " Stage: " << i << "\n");
1383
1384 newValues[mOp.getVRegValue()][i]= tmp;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001385 newValLocation[tmp] = machineBB;
1386
Tanya Lattner420025b2004-10-10 22:44:35 +00001387 DEBUG(std::cerr << "Machine Instr Operands: " << *(mOp.getVRegValue()) << ", 0, " << *tmp << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001388
1389 //Create machine instruction and put int machineBB
1390 MachineInstr *saveValue = BuildMI(machineBB, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
1391
1392 DEBUG(std::cerr << "Created new machine instr: " << *saveValue << "\n");
1393 }
1394 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001395
1396 //We may also need to update the value that we use if its from an earlier prologue
1397 if(j != 0) {
1398 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse()) {
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001399 if(newValues.count(mOp.getVRegValue())) {
1400 if(newValues[mOp.getVRegValue()].count(i-1)) {
1401 Value *oldV = mOp.getVRegValue();
Tanya Lattner420025b2004-10-10 22:44:35 +00001402 DEBUG(std::cerr << "Replaced this value: " << mOp.getVRegValue() << " With:" << (newValues[mOp.getVRegValue()][i-1]) << "\n");
1403 //Update the operand with the right value
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001404 mOp.setValueReg(newValues[mOp.getVRegValue()][i-1]);
1405
1406 //Remove this value since we have consumed it
1407 //NOTE: Should this only be done if j != maxStage?
1408 consumedValues[oldV][i-1] = (newValues[oldV][i-1]);
1409 DEBUG(std::cerr << "Deleted value: " << consumedValues[oldV][i-1] << "\n");
1410 newValues[oldV].erase(i-1);
Tanya Lattner420025b2004-10-10 22:44:35 +00001411 }
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001412 }
1413 else
1414 if(consumedValues.count(mOp.getVRegValue()))
1415 assert(!consumedValues[mOp.getVRegValue()].count(i-1) && "Found a case where we need the value");
Tanya Lattner420025b2004-10-10 22:44:35 +00001416 }
1417 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001418 }
1419 }
Tanya Lattner20890832004-05-28 20:14:12 +00001420 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001421 }
1422
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001423
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001424 for(std::vector<MSchedGraphNode*>::iterator BR = branches.begin(), BE = branches.end(); BR != BE; ++BR) {
1425
1426 //Stick in branch at the end
1427 machineBB->push_back((*BR)->getInst()->clone());
Tanya Lattner260652a2004-10-30 00:39:07 +00001428
Tanya Lattnerad7654f2004-12-02 07:22:15 +00001429 //Add nop
1430 BuildMI(machineBB, V9::NOP, 0);
1431 }
Tanya Lattner260652a2004-10-30 00:39:07 +00001432
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001433
1434 (((MachineBasicBlock*)origBB)->getParent())->getBasicBlockList().push_back(machineBB);
Tanya Lattner4cffb582004-05-26 06:27:18 +00001435 prologues.push_back(machineBB);
1436 llvm_prologues.push_back(llvmBB);
1437 }
1438}
1439
Tanya Lattner420025b2004-10-10 22:44:35 +00001440void ModuloSchedulingPass::writeEpilogues(std::vector<MachineBasicBlock *> &epilogues, const MachineBasicBlock *origBB, std::vector<BasicBlock*> &llvm_epilogues, std::map<const Value*, std::pair<const MSchedGraphNode*, int> > &valuesToSave, std::map<Value*, std::map<int, Value*> > &newValues,std::map<Value*, MachineBasicBlock*> &newValLocation, std::map<Value*, std::map<int, Value*> > &kernelPHIs ) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001441
Tanya Lattner20890832004-05-28 20:14:12 +00001442 std::map<int, std::set<const MachineInstr*> > inKernel;
Tanya Lattner420025b2004-10-10 22:44:35 +00001443
Tanya Lattner20890832004-05-28 20:14:12 +00001444 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
Tanya Lattner20890832004-05-28 20:14:12 +00001445
1446 //Ignore the branch, we will handle this separately
1447 if(I->first->isBranch())
1448 continue;
1449
1450 //Put int the map so we know what instructions in each stage are in the kernel
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001451 inKernel[I->second].insert(I->first->getInst());
Tanya Lattner20890832004-05-28 20:14:12 +00001452 }
1453
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001454 std::map<Value*, Value*> valPHIs;
1455
Tanya Lattner420025b2004-10-10 22:44:35 +00001456 //some debug stuff, will remove later
1457 DEBUG(for(std::map<Value*, std::map<int, Value*> >::iterator V = newValues.begin(), E = newValues.end(); V !=E; ++V) {
1458 std::cerr << "Old Value: " << *(V->first) << "\n";
1459 for(std::map<int, Value*>::iterator I = V->second.begin(), IE = V->second.end(); I != IE; ++I)
1460 std::cerr << "Stage: " << I->first << " Value: " << *(I->second) << "\n";
1461 });
1462
1463 //some debug stuff, will remove later
1464 DEBUG(for(std::map<Value*, std::map<int, Value*> >::iterator V = kernelPHIs.begin(), E = kernelPHIs.end(); V !=E; ++V) {
1465 std::cerr << "Old Value: " << *(V->first) << "\n";
1466 for(std::map<int, Value*>::iterator I = V->second.begin(), IE = V->second.end(); I != IE; ++I)
1467 std::cerr << "Stage: " << I->first << " Value: " << *(I->second) << "\n";
1468 });
1469
Tanya Lattner20890832004-05-28 20:14:12 +00001470 //Now write the epilogues
Tanya Lattner420025b2004-10-10 22:44:35 +00001471 for(int i = schedule.getMaxStage()-1; i >= 0; --i) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001472 BasicBlock *llvmBB = new BasicBlock("EPILOGUE", (Function*) (origBB->getBasicBlock()->getParent()));
Tanya Lattner20890832004-05-28 20:14:12 +00001473 MachineBasicBlock *machineBB = new MachineBasicBlock(llvmBB);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001474
Tanya Lattner420025b2004-10-10 22:44:35 +00001475 DEBUG(std::cerr << " Epilogue #: " << i << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001476
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001477
Tanya Lattnera6457502004-10-14 06:04:28 +00001478 std::map<Value*, int> inEpilogue;
Tanya Lattner420025b2004-10-10 22:44:35 +00001479
1480 for(MachineBasicBlock::const_iterator MI = origBB->begin(), ME = origBB->end(); ME != MI; ++MI) {
1481 for(int j=schedule.getMaxStage(); j > i; --j) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001482 if(inKernel[j].count(&*MI)) {
1483 DEBUG(std::cerr << "Cloning instruction " << *MI << "\n");
1484 MachineInstr *clone = MI->clone();
1485
1486 //Update operands that need to use the result from the phi
Tanya Lattner420025b2004-10-10 22:44:35 +00001487 for(unsigned opNum=0; opNum < clone->getNumOperands(); ++opNum) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001488 //get machine operand
Tanya Lattner420025b2004-10-10 22:44:35 +00001489 const MachineOperand &mOp = clone->getOperand(opNum);
Tanya Lattner420025b2004-10-10 22:44:35 +00001490
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001491 if((mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse())) {
Tanya Lattner420025b2004-10-10 22:44:35 +00001492
1493 DEBUG(std::cerr << "Writing PHI for " << *(mOp.getVRegValue()) << "\n");
Tanya Lattnera6457502004-10-14 06:04:28 +00001494
1495 //If this is the last instructions for the max iterations ago, don't update operands
1496 if(inEpilogue.count(mOp.getVRegValue()))
1497 if(inEpilogue[mOp.getVRegValue()] == i)
1498 continue;
Tanya Lattner420025b2004-10-10 22:44:35 +00001499
1500 //Quickly write appropriate phis for this operand
1501 if(newValues.count(mOp.getVRegValue())) {
1502 if(newValues[mOp.getVRegValue()].count(i)) {
1503 Instruction *tmp = new TmpInstruction(newValues[mOp.getVRegValue()][i]);
Tanya Lattnera6457502004-10-14 06:04:28 +00001504
1505 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00001506 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001507 tempMvec.addTemp((Value*) tmp);
1508
Tanya Lattner420025b2004-10-10 22:44:35 +00001509 MachineInstr *saveValue = BuildMI(machineBB, V9::PHI, 3).addReg(newValues[mOp.getVRegValue()][i]).addReg(kernelPHIs[mOp.getVRegValue()][i]).addRegDef(tmp);
1510 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
1511 valPHIs[mOp.getVRegValue()] = tmp;
1512 }
1513 }
1514
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001515 if(valPHIs.count(mOp.getVRegValue())) {
1516 //Update the operand in the cloned instruction
Tanya Lattner420025b2004-10-10 22:44:35 +00001517 clone->getOperand(opNum).setValueReg(valPHIs[mOp.getVRegValue()]);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001518 }
1519 }
Tanya Lattnera6457502004-10-14 06:04:28 +00001520 else if((mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef())) {
1521 inEpilogue[mOp.getVRegValue()] = i;
1522 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001523 }
1524 machineBB->push_back(clone);
1525 }
1526 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001527 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001528
Tanya Lattner20890832004-05-28 20:14:12 +00001529 (((MachineBasicBlock*)origBB)->getParent())->getBasicBlockList().push_back(machineBB);
1530 epilogues.push_back(machineBB);
1531 llvm_epilogues.push_back(llvmBB);
Tanya Lattner420025b2004-10-10 22:44:35 +00001532
1533 DEBUG(std::cerr << "EPILOGUE #" << i << "\n");
1534 DEBUG(machineBB->print(std::cerr));
Tanya Lattner20890832004-05-28 20:14:12 +00001535 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001536}
1537
Tanya Lattner420025b2004-10-10 22:44:35 +00001538void ModuloSchedulingPass::writeKernel(BasicBlock *llvmBB, MachineBasicBlock *machineBB, std::map<const Value*, std::pair<const MSchedGraphNode*, int> > &valuesToSave, std::map<Value*, std::map<int, Value*> > &newValues, std::map<Value*, MachineBasicBlock*> &newValLocation, std::map<Value*, std::map<int, Value*> > &kernelPHIs) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001539
1540 //Keep track of operands that are read and saved from a previous iteration. The new clone
1541 //instruction will use the result of the phi instead.
1542 std::map<Value*, Value*> finalPHIValue;
1543 std::map<Value*, Value*> kernelValue;
1544
1545 //Create TmpInstructions for the final phis
1546 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
1547
Tanya Lattner420025b2004-10-10 22:44:35 +00001548 DEBUG(std::cerr << "Stage: " << I->second << " Inst: " << *(I->first->getInst()) << "\n";);
1549
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001550 //Clone instruction
1551 const MachineInstr *inst = I->first->getInst();
1552 MachineInstr *instClone = inst->clone();
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001553
Tanya Lattner420025b2004-10-10 22:44:35 +00001554 //Insert into machine basic block
1555 machineBB->push_back(instClone);
1556
Tanya Lattnerced82222004-11-16 21:31:37 +00001557 DEBUG(std::cerr << "Cloned Inst: " << *instClone << "\n");
1558
Tanya Lattnera6457502004-10-14 06:04:28 +00001559 if(I->first->isBranch()) {
1560 //Add kernel noop
1561 BuildMI(machineBB, V9::NOP, 0);
1562 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001563
1564 //Loop over Machine Operands
1565 for(unsigned i=0; i < inst->getNumOperands(); ++i) {
1566 //get machine operand
1567 const MachineOperand &mOp = inst->getOperand(i);
1568
1569 if(I->second != 0) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001570 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse()) {
Tanya Lattner420025b2004-10-10 22:44:35 +00001571
1572 //Check to see where this operand is defined if this instruction is from max stage
1573 if(I->second == schedule.getMaxStage()) {
1574 DEBUG(std::cerr << "VREG: " << *(mOp.getVRegValue()) << "\n");
1575 }
1576
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001577 //If its in the value saved, we need to create a temp instruction and use that instead
1578 if(valuesToSave.count(mOp.getVRegValue())) {
Tanya Lattnerced82222004-11-16 21:31:37 +00001579
1580 //Check if we already have a final PHI value for this
1581 if(!finalPHIValue.count(mOp.getVRegValue())) {
1582 TmpInstruction *tmp = new TmpInstruction(mOp.getVRegValue());
1583
1584 //Get machine code for this instruction
1585 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
1586 tempMvec.addTemp((Value*) tmp);
1587
1588 //Update the operand in the cloned instruction
1589 instClone->getOperand(i).setValueReg(tmp);
1590
1591 //save this as our final phi
1592 finalPHIValue[mOp.getVRegValue()] = tmp;
1593 newValLocation[tmp] = machineBB;
1594 }
1595 else {
1596 //Use the previous final phi value
1597 instClone->getOperand(i).setValueReg(finalPHIValue[mOp.getVRegValue()]);
1598 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001599 }
1600 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001601 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001602 if(I->second != schedule.getMaxStage()) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001603 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef()) {
1604 if(valuesToSave.count(mOp.getVRegValue())) {
1605
1606 TmpInstruction *tmp = new TmpInstruction(mOp.getVRegValue());
1607
Tanya Lattnera6457502004-10-14 06:04:28 +00001608 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00001609 MachineCodeForInstruction & tempVec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001610 tempVec.addTemp((Value*) tmp);
1611
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001612 //Create new machine instr and put in MBB
1613 MachineInstr *saveValue = BuildMI(machineBB, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
1614
1615 //Save for future cleanup
1616 kernelValue[mOp.getVRegValue()] = tmp;
1617 newValLocation[tmp] = machineBB;
Tanya Lattner420025b2004-10-10 22:44:35 +00001618 kernelPHIs[mOp.getVRegValue()][schedule.getMaxStage()-1] = tmp;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001619 }
1620 }
1621 }
1622 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001623
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001624 }
1625
Tanya Lattner420025b2004-10-10 22:44:35 +00001626 DEBUG(std::cerr << "KERNEL before PHIs\n");
1627 DEBUG(machineBB->print(std::cerr));
1628
1629
1630 //Loop over each value we need to generate phis for
1631 for(std::map<Value*, std::map<int, Value*> >::iterator V = newValues.begin(),
1632 E = newValues.end(); V != E; ++V) {
1633
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001634
1635 DEBUG(std::cerr << "Writing phi for" << *(V->first));
Tanya Lattner420025b2004-10-10 22:44:35 +00001636 DEBUG(std::cerr << "\nMap of Value* for this phi\n");
1637 DEBUG(for(std::map<int, Value*>::iterator I = V->second.begin(),
1638 IE = V->second.end(); I != IE; ++I) {
1639 std::cerr << "Stage: " << I->first;
1640 std::cerr << " Value: " << *(I->second) << "\n";
1641 });
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001642
Tanya Lattner420025b2004-10-10 22:44:35 +00001643 //If we only have one current iteration live, its safe to set lastPhi = to kernel value
1644 if(V->second.size() == 1) {
1645 assert(kernelValue[V->first] != 0 && "Kernel value* must exist to create phi");
1646 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(),V9::PHI, 3).addReg(V->second.begin()->second).addReg(kernelValue[V->first]).addRegDef(finalPHIValue[V->first]);
1647 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
1648 kernelPHIs[V->first][schedule.getMaxStage()-1] = kernelValue[V->first];
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001649 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001650 else {
1651
1652 //Keep track of last phi created.
1653 Instruction *lastPhi = 0;
1654
1655 unsigned count = 1;
1656 //Loop over the the map backwards to generate phis
1657 for(std::map<int, Value*>::reverse_iterator I = V->second.rbegin(), IE = V->second.rend();
1658 I != IE; ++I) {
1659
1660 if(count < (V->second).size()) {
1661 if(lastPhi == 0) {
1662 lastPhi = new TmpInstruction(I->second);
Tanya Lattnera6457502004-10-14 06:04:28 +00001663
1664 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00001665 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001666 tempMvec.addTemp((Value*) lastPhi);
1667
Tanya Lattner420025b2004-10-10 22:44:35 +00001668 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(), V9::PHI, 3).addReg(kernelValue[V->first]).addReg(I->second).addRegDef(lastPhi);
1669 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
1670 newValLocation[lastPhi] = machineBB;
1671 }
1672 else {
1673 Instruction *tmp = new TmpInstruction(I->second);
Tanya Lattnera6457502004-10-14 06:04:28 +00001674
1675 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00001676 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001677 tempMvec.addTemp((Value*) tmp);
1678
1679
Tanya Lattner420025b2004-10-10 22:44:35 +00001680 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(), V9::PHI, 3).addReg(lastPhi).addReg(I->second).addRegDef(tmp);
1681 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
1682 lastPhi = tmp;
1683 kernelPHIs[V->first][I->first] = lastPhi;
1684 newValLocation[lastPhi] = machineBB;
1685 }
1686 }
1687 //Final phi value
1688 else {
1689 //The resulting value must be the Value* we created earlier
1690 assert(lastPhi != 0 && "Last phi is NULL!\n");
1691 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(), V9::PHI, 3).addReg(lastPhi).addReg(I->second).addRegDef(finalPHIValue[V->first]);
1692 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
1693 kernelPHIs[V->first][I->first] = finalPHIValue[V->first];
1694 }
1695
1696 ++count;
1697 }
1698
1699 }
1700 }
1701
1702 DEBUG(std::cerr << "KERNEL after PHIs\n");
1703 DEBUG(machineBB->print(std::cerr));
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001704}
1705
Tanya Lattner420025b2004-10-10 22:44:35 +00001706
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001707void ModuloSchedulingPass::removePHIs(const MachineBasicBlock *origBB, std::vector<MachineBasicBlock *> &prologues, std::vector<MachineBasicBlock *> &epilogues, MachineBasicBlock *kernelBB, std::map<Value*, MachineBasicBlock*> &newValLocation) {
1708
1709 //Worklist to delete things
1710 std::vector<std::pair<MachineBasicBlock*, MachineBasicBlock::iterator> > worklist;
Tanya Lattnera6457502004-10-14 06:04:28 +00001711
1712 //Worklist of TmpInstructions that need to be added to a MCFI
1713 std::vector<Instruction*> addToMCFI;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001714
Tanya Lattnera6457502004-10-14 06:04:28 +00001715 //Worklist to add OR instructions to end of kernel so not to invalidate the iterator
1716 //std::vector<std::pair<Instruction*, Value*> > newORs;
1717
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001718 const TargetInstrInfo *TMI = target.getInstrInfo();
1719
1720 //Start with the kernel and for each phi insert a copy for the phi def and for each arg
1721 for(MachineBasicBlock::iterator I = kernelBB->begin(), E = kernelBB->end(); I != E; ++I) {
Tanya Lattnera6457502004-10-14 06:04:28 +00001722
Tanya Lattner80f08552004-11-02 21:04:56 +00001723 DEBUG(std::cerr << "Looking at Instr: " << *I << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001724 //Get op code and check if its a phi
Tanya Lattnera6457502004-10-14 06:04:28 +00001725 if(I->getOpcode() == V9::PHI) {
1726
1727 DEBUG(std::cerr << "Replacing PHI: " << *I << "\n");
1728 Instruction *tmp = 0;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001729
Tanya Lattnera6457502004-10-14 06:04:28 +00001730 for(unsigned i = 0; i < I->getNumOperands(); ++i) {
1731 //Get Operand
1732 const MachineOperand &mOp = I->getOperand(i);
1733 assert(mOp.getType() == MachineOperand::MO_VirtualRegister && "Should be a Value*\n");
1734
1735 if(!tmp) {
1736 tmp = new TmpInstruction(mOp.getVRegValue());
1737 addToMCFI.push_back(tmp);
1738 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001739
Tanya Lattnera6457502004-10-14 06:04:28 +00001740 //Now for all our arguments we read, OR to the new TmpInstruction that we created
1741 if(mOp.isUse()) {
1742 DEBUG(std::cerr << "Use: " << mOp << "\n");
1743 //Place a copy at the end of its BB but before the branches
1744 assert(newValLocation.count(mOp.getVRegValue()) && "We must know where this value is located\n");
1745 //Reverse iterate to find the branches, we can safely assume no instructions have been
1746 //put in the nop positions
1747 for(MachineBasicBlock::iterator inst = --(newValLocation[mOp.getVRegValue()])->end(), endBB = (newValLocation[mOp.getVRegValue()])->begin(); inst != endBB; --inst) {
1748 MachineOpCode opc = inst->getOpcode();
1749 if(TMI->isBranch(opc) || TMI->isNop(opc))
1750 continue;
1751 else {
1752 BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
1753 break;
1754 }
1755
1756 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001757
Tanya Lattnera6457502004-10-14 06:04:28 +00001758 }
1759 else {
1760 //Remove the phi and replace it with an OR
1761 DEBUG(std::cerr << "Def: " << mOp << "\n");
1762 //newORs.push_back(std::make_pair(tmp, mOp.getVRegValue()));
1763 BuildMI(*kernelBB, I, V9::ORr, 3).addReg(tmp).addImm(0).addRegDef(mOp.getVRegValue());
1764 worklist.push_back(std::make_pair(kernelBB, I));
1765 }
1766
1767 }
1768
1769 }
1770
Tanya Lattnera6457502004-10-14 06:04:28 +00001771
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001772 }
1773
Tanya Lattner80f08552004-11-02 21:04:56 +00001774 //Add TmpInstructions to some MCFI
1775 if(addToMCFI.size() > 0) {
1776 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
1777 for(unsigned x = 0; x < addToMCFI.size(); ++x) {
1778 tempMvec.addTemp(addToMCFI[x]);
1779 }
1780 addToMCFI.clear();
1781 }
1782
Tanya Lattnera6457502004-10-14 06:04:28 +00001783
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001784 //Remove phis from epilogue
1785 for(std::vector<MachineBasicBlock*>::iterator MB = epilogues.begin(), ME = epilogues.end(); MB != ME; ++MB) {
1786 for(MachineBasicBlock::iterator I = (*MB)->begin(), E = (*MB)->end(); I != E; ++I) {
Tanya Lattner80f08552004-11-02 21:04:56 +00001787
1788 DEBUG(std::cerr << "Looking at Instr: " << *I << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001789 //Get op code and check if its a phi
Brian Gaeke418379e2004-08-18 20:04:24 +00001790 if(I->getOpcode() == V9::PHI) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001791 Instruction *tmp = 0;
Tanya Lattnera6457502004-10-14 06:04:28 +00001792
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001793 for(unsigned i = 0; i < I->getNumOperands(); ++i) {
1794 //Get Operand
1795 const MachineOperand &mOp = I->getOperand(i);
1796 assert(mOp.getType() == MachineOperand::MO_VirtualRegister && "Should be a Value*\n");
1797
1798 if(!tmp) {
1799 tmp = new TmpInstruction(mOp.getVRegValue());
Tanya Lattnera6457502004-10-14 06:04:28 +00001800 addToMCFI.push_back(tmp);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001801 }
1802
1803 //Now for all our arguments we read, OR to the new TmpInstruction that we created
1804 if(mOp.isUse()) {
1805 DEBUG(std::cerr << "Use: " << mOp << "\n");
1806 //Place a copy at the end of its BB but before the branches
1807 assert(newValLocation.count(mOp.getVRegValue()) && "We must know where this value is located\n");
1808 //Reverse iterate to find the branches, we can safely assume no instructions have been
1809 //put in the nop positions
1810 for(MachineBasicBlock::iterator inst = --(newValLocation[mOp.getVRegValue()])->end(), endBB = (newValLocation[mOp.getVRegValue()])->begin(); inst != endBB; --inst) {
1811 MachineOpCode opc = inst->getOpcode();
1812 if(TMI->isBranch(opc) || TMI->isNop(opc))
1813 continue;
1814 else {
1815 BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
1816 break;
1817 }
1818
1819 }
Tanya Lattnera6457502004-10-14 06:04:28 +00001820
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001821 }
1822 else {
1823 //Remove the phi and replace it with an OR
1824 DEBUG(std::cerr << "Def: " << mOp << "\n");
1825 BuildMI(**MB, I, V9::ORr, 3).addReg(tmp).addImm(0).addRegDef(mOp.getVRegValue());
1826 worklist.push_back(std::make_pair(*MB,I));
1827 }
1828
1829 }
1830 }
Tanya Lattnera6457502004-10-14 06:04:28 +00001831
Tanya Lattner80f08552004-11-02 21:04:56 +00001832
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001833 }
1834 }
1835
Tanya Lattner80f08552004-11-02 21:04:56 +00001836
1837 if(addToMCFI.size() > 0) {
1838 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
1839 for(unsigned x = 0; x < addToMCFI.size(); ++x) {
1840 tempMvec.addTemp(addToMCFI[x]);
1841 }
1842 addToMCFI.clear();
1843 }
1844
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001845 //Delete the phis
1846 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 +00001847
1848 DEBUG(std::cerr << "Deleting PHI " << *I->second << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001849 I->first->erase(I->second);
1850
1851 }
1852
Tanya Lattnera6457502004-10-14 06:04:28 +00001853
1854 assert((addToMCFI.size() == 0) && "We should have added all TmpInstructions to some MachineCodeForInstruction");
Tanya Lattner20890832004-05-28 20:14:12 +00001855}
1856
1857
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001858void ModuloSchedulingPass::reconstructLoop(MachineBasicBlock *BB) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00001859
Tanya Lattner420025b2004-10-10 22:44:35 +00001860 DEBUG(std::cerr << "Reconstructing Loop\n");
1861
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001862 //First find the value *'s that we need to "save"
1863 std::map<const Value*, std::pair<const MSchedGraphNode*, int> > valuesToSave;
Tanya Lattner4cffb582004-05-26 06:27:18 +00001864
Tanya Lattner420025b2004-10-10 22:44:35 +00001865 //Keep track of instructions we have already seen and their stage because
1866 //we don't want to "save" values if they are used in the kernel immediately
1867 std::map<const MachineInstr*, int> lastInstrs;
1868
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001869 //Loop over kernel and only look at instructions from a stage > 0
1870 //Look at its operands and save values *'s that are read
Tanya Lattner4cffb582004-05-26 06:27:18 +00001871 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00001872
Tanya Lattner420025b2004-10-10 22:44:35 +00001873 if(I->second !=0) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00001874 //For this instruction, get the Value*'s that it reads and put them into the set.
1875 //Assert if there is an operand of another type that we need to save
1876 const MachineInstr *inst = I->first->getInst();
Tanya Lattner420025b2004-10-10 22:44:35 +00001877 lastInstrs[inst] = I->second;
1878
Tanya Lattner4cffb582004-05-26 06:27:18 +00001879 for(unsigned i=0; i < inst->getNumOperands(); ++i) {
1880 //get machine operand
1881 const MachineOperand &mOp = inst->getOperand(i);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001882
Tanya Lattner4cffb582004-05-26 06:27:18 +00001883 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse()) {
1884 //find the value in the map
Tanya Lattner420025b2004-10-10 22:44:35 +00001885 if (const Value* srcI = mOp.getVRegValue()) {
1886
Tanya Lattnerced82222004-11-16 21:31:37 +00001887 if(isa<Constant>(srcI) || isa<Argument>(srcI) || isa<PHINode>(srcI))
Tanya Lattner80f08552004-11-02 21:04:56 +00001888 continue;
1889
Tanya Lattner420025b2004-10-10 22:44:35 +00001890 //Before we declare this Value* one that we should save
1891 //make sure its def is not of the same stage as this instruction
1892 //because it will be consumed before its used
1893 Instruction *defInst = (Instruction*) srcI;
1894
1895 //Should we save this value?
1896 bool save = true;
1897
Tanya Lattnerced82222004-11-16 21:31:37 +00001898 //Continue if not in the def map, loop invariant code does not need to be saved
1899 if(!defMap.count(srcI))
1900 continue;
1901
Tanya Lattner80f08552004-11-02 21:04:56 +00001902 MachineInstr *defInstr = defMap[srcI];
1903
Tanya Lattnerced82222004-11-16 21:31:37 +00001904
Tanya Lattner80f08552004-11-02 21:04:56 +00001905 if(lastInstrs.count(defInstr)) {
Tanya Lattnerced82222004-11-16 21:31:37 +00001906 if(lastInstrs[defInstr] == I->second) {
Tanya Lattner80f08552004-11-02 21:04:56 +00001907 save = false;
Tanya Lattnerced82222004-11-16 21:31:37 +00001908
1909 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001910 }
Tanya Lattner80f08552004-11-02 21:04:56 +00001911
Tanya Lattner420025b2004-10-10 22:44:35 +00001912 if(save)
1913 valuesToSave[srcI] = std::make_pair(I->first, i);
1914 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001915 }
1916
1917 if(mOp.getType() != MachineOperand::MO_VirtualRegister && mOp.isUse()) {
1918 assert("Our assumption is wrong. We have another type of register that needs to be saved\n");
1919 }
1920 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001921 }
1922 }
1923
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001924 //The new loop will consist of one or more prologues, the kernel, and one or more epilogues.
1925
1926 //Map to keep track of old to new values
Tanya Lattner420025b2004-10-10 22:44:35 +00001927 std::map<Value*, std::map<int, Value*> > newValues;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001928
Tanya Lattner420025b2004-10-10 22:44:35 +00001929 //Map to keep track of old to new values in kernel
1930 std::map<Value*, std::map<int, Value*> > kernelPHIs;
1931
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001932 //Another map to keep track of what machine basic blocks these new value*s are in since
1933 //they have no llvm instruction equivalent
1934 std::map<Value*, MachineBasicBlock*> newValLocation;
1935
1936 std::vector<MachineBasicBlock*> prologues;
1937 std::vector<BasicBlock*> llvm_prologues;
1938
1939
1940 //Write prologue
1941 writePrologues(prologues, BB, llvm_prologues, valuesToSave, newValues, newValLocation);
Tanya Lattner420025b2004-10-10 22:44:35 +00001942
1943 //Print out epilogues and prologue
1944 DEBUG(for(std::vector<MachineBasicBlock*>::iterator I = prologues.begin(), E = prologues.end();
1945 I != E; ++I) {
1946 std::cerr << "PROLOGUE\n";
1947 (*I)->print(std::cerr);
1948 });
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001949
1950 BasicBlock *llvmKernelBB = new BasicBlock("Kernel", (Function*) (BB->getBasicBlock()->getParent()));
1951 MachineBasicBlock *machineKernelBB = new MachineBasicBlock(llvmKernelBB);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001952 (((MachineBasicBlock*)BB)->getParent())->getBasicBlockList().push_back(machineKernelBB);
Tanya Lattner420025b2004-10-10 22:44:35 +00001953 writeKernel(llvmKernelBB, machineKernelBB, valuesToSave, newValues, newValLocation, kernelPHIs);
1954
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001955
1956 std::vector<MachineBasicBlock*> epilogues;
1957 std::vector<BasicBlock*> llvm_epilogues;
1958
1959 //Write epilogues
Tanya Lattner420025b2004-10-10 22:44:35 +00001960 writeEpilogues(epilogues, BB, llvm_epilogues, valuesToSave, newValues, newValLocation, kernelPHIs);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001961
1962
Tanya Lattner58fe2f02004-11-29 04:39:47 +00001963 //Fix our branches
1964 fixBranches(prologues, llvm_prologues, machineKernelBB, llvmKernelBB, epilogues, llvm_epilogues, BB);
1965
1966 //Remove phis
1967 removePHIs(BB, prologues, epilogues, machineKernelBB, newValLocation);
1968
1969 //Print out epilogues and prologue
1970 DEBUG(for(std::vector<MachineBasicBlock*>::iterator I = prologues.begin(), E = prologues.end();
1971 I != E; ++I) {
1972 std::cerr << "PROLOGUE\n";
1973 (*I)->print(std::cerr);
1974 });
1975
1976 DEBUG(std::cerr << "KERNEL\n");
1977 DEBUG(machineKernelBB->print(std::cerr));
1978
1979 DEBUG(for(std::vector<MachineBasicBlock*>::iterator I = epilogues.begin(), E = epilogues.end();
1980 I != E; ++I) {
1981 std::cerr << "EPILOGUE\n";
1982 (*I)->print(std::cerr);
1983 });
1984
1985
1986 DEBUG(std::cerr << "New Machine Function" << "\n");
1987 DEBUG(std::cerr << BB->getParent() << "\n");
1988
1989
1990}
1991
1992void 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) {
1993
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001994 const TargetInstrInfo *TMI = target.getInstrInfo();
1995
Tanya Lattner58fe2f02004-11-29 04:39:47 +00001996 //Fix prologue branches
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001997 for(unsigned I = 0; I < prologues.size(); ++I) {
1998
Tanya Lattner58fe2f02004-11-29 04:39:47 +00001999 //Find terminator since getFirstTerminator does not work!
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002000 for(MachineBasicBlock::reverse_iterator mInst = prologues[I]->rbegin(), mInstEnd = prologues[I]->rend(); mInst != mInstEnd; ++mInst) {
2001 MachineOpCode OC = mInst->getOpcode();
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002002 //If its a branch update its branchto
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002003 if(TMI->isBranch(OC)) {
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002004 for(unsigned opNum = 0; opNum < mInst->getNumOperands(); ++opNum) {
2005 MachineOperand &mOp = mInst->getOperand(opNum);
2006 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2007 //Check if we are branching to the kernel, if not branch to epilogue
2008 if(mOp.getVRegValue() == BB->getBasicBlock()) {
2009 if(I == prologues.size()-1)
2010 mOp.setValueReg(llvmKernelBB);
2011 else
2012 mOp.setValueReg(llvm_prologues[I+1]);
2013 }
2014 else {
2015 mOp.setValueReg(llvm_epilogues[(llvm_epilogues.size()-1-I)]);
2016 }
2017 }
2018 }
2019
2020 DEBUG(std::cerr << "New Prologue Branch: " << *mInst << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002021 }
2022 }
2023
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002024
2025 //Update llvm basic block with our new branch instr
2026 DEBUG(std::cerr << BB->getBasicBlock()->getTerminator() << "\n");
2027 const BranchInst *branchVal = dyn_cast<BranchInst>(BB->getBasicBlock()->getTerminator());
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002028
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002029 if(I == prologues.size()-1) {
2030 TerminatorInst *newBranch = new BranchInst(llvmKernelBB,
2031 llvm_epilogues[(llvm_epilogues.size()-1-I)],
Tanya Lattnera6457502004-10-14 06:04:28 +00002032 branchVal->getCondition(),
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002033 llvm_prologues[I]);
2034 }
2035 else
2036 TerminatorInst *newBranch = new BranchInst(llvm_prologues[I+1],
2037 llvm_epilogues[(llvm_epilogues.size()-1-I)],
Tanya Lattnera6457502004-10-14 06:04:28 +00002038 branchVal->getCondition(),
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002039 llvm_prologues[I]);
2040
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002041 }
2042
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002043 Value *origBranchExit = 0;
Tanya Lattnera6457502004-10-14 06:04:28 +00002044
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002045 //Fix up kernel machine branches
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002046 for(MachineBasicBlock::reverse_iterator mInst = machineKernelBB->rbegin(), mInstEnd = machineKernelBB->rend(); mInst != mInstEnd; ++mInst) {
2047 MachineOpCode OC = mInst->getOpcode();
2048 if(TMI->isBranch(OC)) {
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002049 for(unsigned opNum = 0; opNum < mInst->getNumOperands(); ++opNum) {
2050 MachineOperand &mOp = mInst->getOperand(opNum);
2051
2052 if(mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2053 if(mOp.getVRegValue() == BB->getBasicBlock())
2054 mOp.setValueReg(llvmKernelBB);
2055 else
2056 if(llvm_epilogues.size() > 0) {
2057 assert(origBranchExit == 0 && "There should only be one branch out of the loop");
2058
2059 origBranchExit = mOp.getVRegValue();
2060 mOp.setValueReg(llvm_epilogues[0]);
2061 }
2062 }
Tanya Lattnera6457502004-10-14 06:04:28 +00002063 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002064 }
2065 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002066
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002067 //Update kernelLLVM branches
2068 const BranchInst *branchVal = dyn_cast<BranchInst>(BB->getBasicBlock()->getTerminator());
Tanya Lattnera6457502004-10-14 06:04:28 +00002069
Tanya Lattner260652a2004-10-30 00:39:07 +00002070 assert(llvm_epilogues.size() != 0 && "We must have epilogues!");
2071
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002072 TerminatorInst *newBranch = new BranchInst(llvmKernelBB,
2073 llvm_epilogues[0],
Tanya Lattnera6457502004-10-14 06:04:28 +00002074 branchVal->getCondition(),
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002075 llvmKernelBB);
2076
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002077
2078 //Lastly add unconditional branches for the epilogues
2079 for(unsigned I = 0; I < epilogues.size(); ++I) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00002080
Tanya Lattnera6457502004-10-14 06:04:28 +00002081 //Now since we don't have fall throughs, add a unconditional branch to the next prologue
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002082 if(I != epilogues.size()-1) {
Tanya Lattner420025b2004-10-10 22:44:35 +00002083 BuildMI(epilogues[I], V9::BA, 1).addPCDisp(llvm_epilogues[I+1]);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002084 //Add unconditional branch to end of epilogue
2085 TerminatorInst *newBranch = new BranchInst(llvm_epilogues[I+1],
2086 llvm_epilogues[I]);
2087
Tanya Lattner4cffb582004-05-26 06:27:18 +00002088 }
Tanya Lattnera6457502004-10-14 06:04:28 +00002089 else {
Tanya Lattner58fe2f02004-11-29 04:39:47 +00002090 BuildMI(epilogues[I], V9::BA, 1).addPCDisp(origBranchExit);
Tanya Lattnera6457502004-10-14 06:04:28 +00002091
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002092
Tanya Lattnera6457502004-10-14 06:04:28 +00002093 //Update last epilogue exit branch
2094 BranchInst *branchVal = (BranchInst*) dyn_cast<BranchInst>(BB->getBasicBlock()->getTerminator());
2095 //Find where we are supposed to branch to
2096 BasicBlock *nextBlock = 0;
2097 for(unsigned j=0; j <branchVal->getNumSuccessors(); ++j) {
2098 if(branchVal->getSuccessor(j) != BB->getBasicBlock())
2099 nextBlock = branchVal->getSuccessor(j);
2100 }
2101
2102 assert((nextBlock != 0) && "Next block should not be null!");
2103 TerminatorInst *newBranch = new BranchInst(nextBlock, llvm_epilogues[I]);
2104 }
2105 //Add one more nop!
2106 BuildMI(epilogues[I], V9::NOP, 0);
2107
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002108 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00002109
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002110 //FIX UP Machine BB entry!!
2111 //We are looking at the predecesor of our loop basic block and we want to change its ba instruction
2112
Tanya Lattner4cffb582004-05-26 06:27:18 +00002113
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002114 //Find all llvm basic blocks that branch to the loop entry and change to our first prologue.
2115 const BasicBlock *llvmBB = BB->getBasicBlock();
2116
Tanya Lattner260652a2004-10-30 00:39:07 +00002117 std::vector<const BasicBlock*>Preds (pred_begin(llvmBB), pred_end(llvmBB));
2118
2119 //for(pred_const_iterator P = pred_begin(llvmBB), PE = pred_end(llvmBB); P != PE; ++PE) {
2120 for(std::vector<const BasicBlock*>::iterator P = Preds.begin(), PE = Preds.end(); P != PE; ++P) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002121 if(*P == llvmBB)
2122 continue;
2123 else {
2124 DEBUG(std::cerr << "Found our entry BB\n");
2125 //Get the Terminator instruction for this basic block and print it out
2126 DEBUG(std::cerr << *((*P)->getTerminator()) << "\n");
2127 //Update the terminator
2128 TerminatorInst *term = ((BasicBlock*)*P)->getTerminator();
2129 for(unsigned i=0; i < term->getNumSuccessors(); ++i) {
2130 if(term->getSuccessor(i) == llvmBB) {
2131 DEBUG(std::cerr << "Replacing successor bb\n");
2132 if(llvm_prologues.size() > 0) {
2133 term->setSuccessor(i, llvm_prologues[0]);
2134 //Also update its corresponding machine instruction
2135 MachineCodeForInstruction & tempMvec =
2136 MachineCodeForInstruction::get(term);
2137 for (unsigned j = 0; j < tempMvec.size(); j++) {
2138 MachineInstr *temp = tempMvec[j];
2139 MachineOpCode opc = temp->getOpcode();
2140 if(TMI->isBranch(opc)) {
2141 DEBUG(std::cerr << *temp << "\n");
2142 //Update branch
2143 for(unsigned opNum = 0; opNum < temp->getNumOperands(); ++opNum) {
2144 MachineOperand &mOp = temp->getOperand(opNum);
2145 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2146 mOp.setValueReg(llvm_prologues[0]);
2147 }
2148 }
2149 }
2150 }
2151 }
2152 else {
2153 term->setSuccessor(i, llvmKernelBB);
2154 //Also update its corresponding machine instruction
2155 MachineCodeForInstruction & tempMvec =
2156 MachineCodeForInstruction::get(term);
2157 for (unsigned j = 0; j < tempMvec.size(); j++) {
2158 MachineInstr *temp = tempMvec[j];
2159 MachineOpCode opc = temp->getOpcode();
2160 if(TMI->isBranch(opc)) {
2161 DEBUG(std::cerr << *temp << "\n");
2162 //Update branch
2163 for(unsigned opNum = 0; opNum < temp->getNumOperands(); ++opNum) {
2164 MachineOperand &mOp = temp->getOperand(opNum);
2165 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2166 mOp.setValueReg(llvmKernelBB);
2167 }
2168 }
2169 }
2170 }
2171 }
2172 }
2173 }
2174 break;
2175 }
2176 }
2177
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002178
Tanya Lattner420025b2004-10-10 22:44:35 +00002179 //BB->getParent()->getBasicBlockList().erase(BB);
Tanya Lattner4cffb582004-05-26 06:27:18 +00002180
2181}
2182