blob: 01598c3f91d7e6658f7dc201d9b0ad07e2bc1c04 [file] [log] [blame]
Tanya Lattnerced82222004-11-16 21:31:37 +00001
Tanya Lattnerd14b8372004-03-01 02:50:01 +00002//===-- ModuloScheduling.cpp - ModuloScheduling ----------------*- C++ -*-===//
3//
John Criswellb576c942003-10-20 19:43:21 +00004// The LLVM Compiler Infrastructure
5//
6// This file was developed by the LLVM research group and is distributed under
7// the University of Illinois Open Source License. See LICENSE.TXT for details.
Tanya Lattnerd14b8372004-03-01 02:50:01 +00008//
John Criswellb576c942003-10-20 19:43:21 +00009//===----------------------------------------------------------------------===//
Tanya Lattnerd14b8372004-03-01 02:50:01 +000010//
Tanya Lattner0a88d2d2004-07-30 23:36:10 +000011// This ModuloScheduling pass is based on the Swing Modulo Scheduling
12// algorithm.
Misha Brukman82fd8d82004-08-02 13:59:10 +000013//
Guochun Shif1c154f2003-03-27 17:57:44 +000014//===----------------------------------------------------------------------===//
15
Tanya Lattnerd14b8372004-03-01 02:50:01 +000016#define DEBUG_TYPE "ModuloSched"
17
18#include "ModuloScheduling.h"
Tanya Lattner0a88d2d2004-07-30 23:36:10 +000019#include "llvm/Instructions.h"
20#include "llvm/Function.h"
Tanya Lattnerd14b8372004-03-01 02:50:01 +000021#include "llvm/CodeGen/MachineFunction.h"
22#include "llvm/CodeGen/Passes.h"
23#include "llvm/Support/CFG.h"
24#include "llvm/Target/TargetSchedInfo.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000025#include "llvm/Support/Debug.h"
26#include "llvm/Support/GraphWriter.h"
27#include "llvm/ADT/StringExtras.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 {
65
Tanya Lattnerd14b8372004-03-01 02:50:01 +000066 template<>
67 struct DOTGraphTraits<MSchedGraph*> : public DefaultDOTGraphTraits {
68 static std::string getGraphName(MSchedGraph *F) {
69 return "Dependence Graph";
70 }
Guochun Shi8f1d4ab2003-06-08 23:16:07 +000071
Tanya Lattnerd14b8372004-03-01 02:50:01 +000072 static std::string getNodeLabel(MSchedGraphNode *Node, MSchedGraph *Graph) {
73 if (Node->getInst()) {
74 std::stringstream ss;
75 ss << *(Node->getInst());
76 return ss.str(); //((MachineInstr*)Node->getInst());
77 }
78 else
79 return "No Inst";
80 }
81 static std::string getEdgeSourceLabel(MSchedGraphNode *Node,
82 MSchedGraphNode::succ_iterator I) {
83 //Label each edge with the type of dependence
84 std::string edgelabel = "";
85 switch (I.getEdge().getDepOrderType()) {
86
87 case MSchedGraphEdge::TrueDep:
88 edgelabel = "True";
89 break;
90
91 case MSchedGraphEdge::AntiDep:
92 edgelabel = "Anti";
93 break;
94
95 case MSchedGraphEdge::OutputDep:
96 edgelabel = "Output";
97 break;
98
99 default:
100 edgelabel = "Unknown";
101 break;
102 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000103
104 //FIXME
105 int iteDiff = I.getEdge().getIteDiff();
106 std::string intStr = "(IteDiff: ";
107 intStr += itostr(iteDiff);
108
109 intStr += ")";
110 edgelabel += intStr;
111
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000112 return edgelabel;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000113 }
Guochun Shif1c154f2003-03-27 17:57:44 +0000114 };
Guochun Shif1c154f2003-03-27 17:57:44 +0000115}
Tanya Lattner4f839cc2003-08-28 17:12:14 +0000116
Misha Brukmanaa41c3c2003-10-10 17:41:32 +0000117/// ModuloScheduling::runOnFunction - main transformation entry point
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000118/// The Swing Modulo Schedule algorithm has three basic steps:
119/// 1) Computation and Analysis of the dependence graph
120/// 2) Ordering of the nodes
121/// 3) Scheduling
122///
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000123bool ModuloSchedulingPass::runOnFunction(Function &F) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000124
Tanya Lattner4f839cc2003-08-28 17:12:14 +0000125 bool Changed = false;
Tanya Lattnerced82222004-11-16 21:31:37 +0000126 int numMS = 0;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000127
Tanya Lattner420025b2004-10-10 22:44:35 +0000128 DEBUG(std::cerr << "Creating ModuloSchedGraph for each valid BasicBlock in " + F.getName() + "\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000129
130 //Get MachineFunction
131 MachineFunction &MF = MachineFunction::get(&F);
Tanya Lattner260652a2004-10-30 00:39:07 +0000132
133
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000134 //Worklist
135 std::vector<MachineBasicBlock*> Worklist;
136
137 //Iterate over BasicBlocks and put them into our worklist if they are valid
138 for (MachineFunction::iterator BI = MF.begin(); BI != MF.end(); ++BI)
139 if(MachineBBisValid(BI))
140 Worklist.push_back(&*BI);
141
Tanya Lattner80f08552004-11-02 21:04:56 +0000142 defaultInst = 0;
143
Tanya Lattner420025b2004-10-10 22:44:35 +0000144 DEBUG(if(Worklist.size() == 0) std::cerr << "No single basic block loops in function to ModuloSchedule\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000145
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000146 //Iterate over the worklist and perform scheduling
147 for(std::vector<MachineBasicBlock*>::iterator BI = Worklist.begin(),
148 BE = Worklist.end(); BI != BE; ++BI) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000149
Tanya Lattnerced82222004-11-16 21:31:37 +0000150 CreateDefMap(*BI);
151
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000152 MSchedGraph *MSG = new MSchedGraph(*BI, target);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000153
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000154 //Write Graph out to file
155 DEBUG(WriteGraphToFile(std::cerr, F.getName(), MSG));
156
157 //Print out BB for debugging
Tanya Lattner420025b2004-10-10 22:44:35 +0000158 DEBUG(std::cerr << "ModuloScheduling BB: \n"; (*BI)->print(std::cerr));
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000159
160 //Calculate Resource II
161 int ResMII = calculateResMII(*BI);
162
163 //Calculate Recurrence II
164 int RecMII = calculateRecMII(MSG, ResMII);
165
166 //Our starting initiation interval is the maximum of RecMII and ResMII
167 II = std::max(RecMII, ResMII);
168
169 //Print out II, RecMII, and ResMII
Tanya Lattner260652a2004-10-30 00:39:07 +0000170 DEBUG(std::cerr << "II starts out as " << II << " ( RecMII=" << RecMII << " and ResMII=" << ResMII << ")\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000171
Tanya Lattner260652a2004-10-30 00:39:07 +0000172 //Dump node properties if in debug mode
173 DEBUG(for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(),
174 E = nodeToAttributesMap.end(); I !=E; ++I) {
175 std::cerr << "Node: " << *(I->first) << " ASAP: " << I->second.ASAP << " ALAP: "
176 << I->second.ALAP << " MOB: " << I->second.MOB << " Depth: " << I->second.depth
177 << " Height: " << I->second.height << "\n";
178 });
179
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000180 //Calculate Node Properties
181 calculateNodeAttributes(MSG, ResMII);
182
183 //Dump node properties if in debug mode
184 DEBUG(for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(),
185 E = nodeToAttributesMap.end(); I !=E; ++I) {
186 std::cerr << "Node: " << *(I->first) << " ASAP: " << I->second.ASAP << " ALAP: "
187 << I->second.ALAP << " MOB: " << I->second.MOB << " Depth: " << I->second.depth
188 << " Height: " << I->second.height << "\n";
189 });
190
191 //Put nodes in order to schedule them
192 computePartialOrder();
193
194 //Dump out partial order
Tanya Lattner260652a2004-10-30 00:39:07 +0000195 DEBUG(for(std::vector<std::set<MSchedGraphNode*> >::iterator I = partialOrder.begin(),
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000196 E = partialOrder.end(); I !=E; ++I) {
197 std::cerr << "Start set in PO\n";
Tanya Lattner260652a2004-10-30 00:39:07 +0000198 for(std::set<MSchedGraphNode*>::iterator J = I->begin(), JE = I->end(); J != JE; ++J)
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000199 std::cerr << "PO:" << **J << "\n";
200 });
201
202 //Place nodes in final order
203 orderNodes();
204
205 //Dump out order of nodes
206 DEBUG(for(std::vector<MSchedGraphNode*>::iterator I = FinalNodeOrder.begin(), E = FinalNodeOrder.end(); I != E; ++I) {
207 std::cerr << "FO:" << **I << "\n";
208 });
209
210 //Finally schedule nodes
211 computeSchedule();
212
213 //Print out final schedule
214 DEBUG(schedule.print(std::cerr));
215
Tanya Lattner260652a2004-10-30 00:39:07 +0000216 //Final scheduling step is to reconstruct the loop only if we actual have
217 //stage > 0
Tanya Lattnerced82222004-11-16 21:31:37 +0000218 if(schedule.getMaxStage() != 0) {
Tanya Lattner260652a2004-10-30 00:39:07 +0000219 reconstructLoop(*BI);
Tanya Lattnerced82222004-11-16 21:31:37 +0000220 numMS++;
221 Changed = true;
222 }
Tanya Lattner260652a2004-10-30 00:39:07 +0000223 else
224 DEBUG(std::cerr << "Max stage is 0, so no change in loop\n");
225
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000226 //Clear out our maps for the next basic block that is processed
227 nodeToAttributesMap.clear();
228 partialOrder.clear();
229 recurrenceList.clear();
230 FinalNodeOrder.clear();
231 schedule.clear();
Tanya Lattnerced82222004-11-16 21:31:37 +0000232 defMap.clear();
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000233 //Clean up. Nuke old MachineBB and llvmBB
234 //BasicBlock *llvmBB = (BasicBlock*) (*BI)->getBasicBlock();
235 //Function *parent = (Function*) llvmBB->getParent();
236 //Should't std::find work??
237 //parent->getBasicBlockList().erase(std::find(parent->getBasicBlockList().begin(), parent->getBasicBlockList().end(), *llvmBB));
238 //parent->getBasicBlockList().erase(llvmBB);
239
240 //delete(llvmBB);
241 //delete(*BI);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000242 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000243
244
Tanya Lattnerced82222004-11-16 21:31:37 +0000245 DEBUG(std::cerr << "Number of Loop Candidates: " << Worklist.size() << "\n Number ModuloScheduled: " << numMS << "\n");
246
Tanya Lattner4f839cc2003-08-28 17:12:14 +0000247 return Changed;
248}
Brian Gaeked0fde302003-11-11 22:41:34 +0000249
Tanya Lattnerced82222004-11-16 21:31:37 +0000250void ModuloSchedulingPass::CreateDefMap(MachineBasicBlock *BI) {
251 defaultInst = 0;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000252
Tanya Lattnerced82222004-11-16 21:31:37 +0000253 for(MachineBasicBlock::iterator I = BI->begin(), E = BI->end(); I != E; ++I) {
254 for(unsigned opNum = 0; opNum < I->getNumOperands(); ++opNum) {
255 const MachineOperand &mOp = I->getOperand(opNum);
256 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef()) {
257 defMap[mOp.getVRegValue()] = &*I;
258 }
259
260 //See if we can use this Value* as our defaultInst
261 if(!defaultInst && mOp.getType() == MachineOperand::MO_VirtualRegister) {
262 Value *V = mOp.getVRegValue();
263 if(!isa<TmpInstruction>(V) && !isa<Argument>(V) && !isa<Constant>(V) && !isa<PHINode>(V))
264 defaultInst = (Instruction*) V;
265 }
266 }
267 }
268 assert(defaultInst && "We must have a default instruction to use as our main point to add to machine code for instruction\n");
269
270}
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000271/// This function checks if a Machine Basic Block is valid for modulo
272/// scheduling. This means that it has no control flow (if/else or
273/// calls) in the block. Currently ModuloScheduling only works on
274/// single basic block loops.
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000275bool ModuloSchedulingPass::MachineBBisValid(const MachineBasicBlock *BI) {
276
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000277 bool isLoop = false;
278
279 //Check first if its a valid loop
280 for(succ_const_iterator I = succ_begin(BI->getBasicBlock()),
281 E = succ_end(BI->getBasicBlock()); I != E; ++I) {
282 if (*I == BI->getBasicBlock()) // has single block loop
283 isLoop = true;
284 }
285
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000286 if(!isLoop)
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000287 return false;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000288
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000289 //Get Target machine instruction info
290 const TargetInstrInfo *TMI = target.getInstrInfo();
291
292 //Check each instruction and look for calls
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000293 for(MachineBasicBlock::const_iterator I = BI->begin(), E = BI->end(); I != E; ++I) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000294 //Get opcode to check instruction type
295 MachineOpCode OC = I->getOpcode();
296 if(TMI->isCall(OC))
297 return false;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000298 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000299 return true;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000300}
301
302//ResMII is calculated by determining the usage count for each resource
303//and using the maximum.
304//FIXME: In future there should be a way to get alternative resources
305//for each instruction
306int ModuloSchedulingPass::calculateResMII(const MachineBasicBlock *BI) {
307
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000308 const TargetInstrInfo *mii = target.getInstrInfo();
309 const TargetSchedInfo *msi = target.getSchedInfo();
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000310
311 int ResMII = 0;
312
313 //Map to keep track of usage count of each resource
314 std::map<unsigned, unsigned> resourceUsageCount;
315
316 for(MachineBasicBlock::const_iterator I = BI->begin(), E = BI->end(); I != E; ++I) {
317
318 //Get resource usage for this instruction
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000319 InstrRUsage rUsage = msi->getInstrRUsage(I->getOpcode());
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000320 std::vector<std::vector<resourceId_t> > resources = rUsage.resourcesByCycle;
321
322 //Loop over resources in each cycle and increments their usage count
323 for(unsigned i=0; i < resources.size(); ++i)
324 for(unsigned j=0; j < resources[i].size(); ++j) {
325 if( resourceUsageCount.find(resources[i][j]) == resourceUsageCount.end()) {
326 resourceUsageCount[resources[i][j]] = 1;
327 }
328 else {
329 resourceUsageCount[resources[i][j]] = resourceUsageCount[resources[i][j]] + 1;
330 }
331 }
332 }
333
334 //Find maximum usage count
335
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000336 //Get max number of instructions that can be issued at once. (FIXME)
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000337 int issueSlots = msi->maxNumIssueTotal;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000338
339 for(std::map<unsigned,unsigned>::iterator RB = resourceUsageCount.begin(), RE = resourceUsageCount.end(); RB != RE; ++RB) {
Tanya Lattner4cffb582004-05-26 06:27:18 +0000340
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000341 //Get the total number of the resources in our cpu
Tanya Lattner4cffb582004-05-26 06:27:18 +0000342 int resourceNum = CPUResource::getCPUResource(RB->first)->maxNumUsers;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000343
344 //Get total usage count for this resources
345 unsigned usageCount = RB->second;
346
347 //Divide the usage count by either the max number we can issue or the number of
348 //resources (whichever is its upper bound)
349 double finalUsageCount;
Tanya Lattner4cffb582004-05-26 06:27:18 +0000350 if( resourceNum <= issueSlots)
351 finalUsageCount = ceil(1.0 * usageCount / resourceNum);
352 else
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000353 finalUsageCount = ceil(1.0 * usageCount / issueSlots);
354
355
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000356 //Only keep track of the max
357 ResMII = std::max( (int) finalUsageCount, ResMII);
358
359 }
360
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000361 return ResMII;
362
363}
364
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000365/// calculateRecMII - Calculates the value of the highest recurrence
366/// By value we mean the total latency
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000367int ModuloSchedulingPass::calculateRecMII(MSchedGraph *graph, int MII) {
368 std::vector<MSchedGraphNode*> vNodes;
369 //Loop over all nodes in the graph
370 for(MSchedGraph::iterator I = graph->begin(), E = graph->end(); I != E; ++I) {
371 findAllReccurrences(I->second, vNodes, MII);
372 vNodes.clear();
373 }
374
375 int RecMII = 0;
376
377 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 +0000378 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 +0000379 std::cerr << **N << "\n";
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000380 });
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000381 RecMII = std::max(RecMII, I->first);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000382 }
383
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000384 return MII;
385}
386
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000387/// calculateNodeAttributes - The following properties are calculated for
388/// each node in the dependence graph: ASAP, ALAP, Depth, Height, and
389/// MOB.
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000390void ModuloSchedulingPass::calculateNodeAttributes(MSchedGraph *graph, int MII) {
391
Tanya Lattner260652a2004-10-30 00:39:07 +0000392 assert(nodeToAttributesMap.empty() && "Node attribute map was not cleared");
393
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000394 //Loop over the nodes and add them to the map
395 for(MSchedGraph::iterator I = graph->begin(), E = graph->end(); I != E; ++I) {
Tanya Lattner260652a2004-10-30 00:39:07 +0000396
397 DEBUG(std::cerr << "Inserting node into attribute map: " << *I->second << "\n");
398
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000399 //Assert if its already in the map
Tanya Lattner260652a2004-10-30 00:39:07 +0000400 assert(nodeToAttributesMap.count(I->second) == 0 &&
401 "Node attributes are already in the map");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000402
403 //Put into the map with default attribute values
404 nodeToAttributesMap[I->second] = MSNodeAttributes();
405 }
406
407 //Create set to deal with reccurrences
408 std::set<MSchedGraphNode*> visitedNodes;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000409
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000410 //Now Loop over map and calculate the node attributes
411 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000412 calculateASAP(I->first, MII, (MSchedGraphNode*) 0);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000413 visitedNodes.clear();
414 }
415
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000416 int maxASAP = findMaxASAP();
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000417 //Calculate ALAP which depends on ASAP being totally calculated
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000418 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
419 calculateALAP(I->first, MII, maxASAP, (MSchedGraphNode*) 0);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000420 visitedNodes.clear();
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000421 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000422
423 //Calculate MOB which depends on ASAP being totally calculated, also do depth and height
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000424 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
425 (I->second).MOB = std::max(0,(I->second).ALAP - (I->second).ASAP);
426
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000427 DEBUG(std::cerr << "MOB: " << (I->second).MOB << " (" << *(I->first) << ")\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000428 calculateDepth(I->first, (MSchedGraphNode*) 0);
429 calculateHeight(I->first, (MSchedGraphNode*) 0);
430 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000431
432
433}
434
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000435/// ignoreEdge - Checks to see if this edge of a recurrence should be ignored or not
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000436bool ModuloSchedulingPass::ignoreEdge(MSchedGraphNode *srcNode, MSchedGraphNode *destNode) {
437 if(destNode == 0 || srcNode ==0)
438 return false;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000439
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000440 bool findEdge = edgesToIgnore.count(std::make_pair(srcNode, destNode->getInEdgeNum(srcNode)));
Tanya Lattner4cffb582004-05-26 06:27:18 +0000441
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000442 return findEdge;
443}
444
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000445
446/// calculateASAP - Calculates the
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000447int ModuloSchedulingPass::calculateASAP(MSchedGraphNode *node, int MII, MSchedGraphNode *destNode) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000448
449 DEBUG(std::cerr << "Calculating ASAP for " << *node << "\n");
450
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000451 //Get current node attributes
452 MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
453
454 if(attributes.ASAP != -1)
455 return attributes.ASAP;
456
457 int maxPredValue = 0;
458
459 //Iterate over all of the predecessors and find max
460 for(MSchedGraphNode::pred_iterator P = node->pred_begin(), E = node->pred_end(); P != E; ++P) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000461
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000462 //Only process if we are not ignoring the edge
463 if(!ignoreEdge(*P, node)) {
464 int predASAP = -1;
465 predASAP = calculateASAP(*P, MII, node);
466
467 assert(predASAP != -1 && "ASAP has not been calculated");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000468 int iteDiff = node->getInEdge(*P).getIteDiff();
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000469
470 int currentPredValue = predASAP + (*P)->getLatency() - (iteDiff * MII);
471 DEBUG(std::cerr << "pred ASAP: " << predASAP << ", iteDiff: " << iteDiff << ", PredLatency: " << (*P)->getLatency() << ", Current ASAP pred: " << currentPredValue << "\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000472 maxPredValue = std::max(maxPredValue, currentPredValue);
473 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000474 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000475
476 attributes.ASAP = maxPredValue;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000477
478 DEBUG(std::cerr << "ASAP: " << attributes.ASAP << " (" << *node << ")\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000479
480 return maxPredValue;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000481}
482
483
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000484int ModuloSchedulingPass::calculateALAP(MSchedGraphNode *node, int MII,
485 int maxASAP, MSchedGraphNode *srcNode) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000486
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000487 DEBUG(std::cerr << "Calculating ALAP for " << *node << "\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000488
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000489 MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
490
491 if(attributes.ALAP != -1)
492 return attributes.ALAP;
493
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000494 if(node->hasSuccessors()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000495
496 //Trying to deal with the issue where the node has successors, but
497 //we are ignoring all of the edges to them. So this is my hack for
498 //now.. there is probably a more elegant way of doing this (FIXME)
499 bool processedOneEdge = false;
500
501 //FIXME, set to something high to start
502 int minSuccValue = 9999999;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000503
504 //Iterate over all of the predecessors and fine max
505 for(MSchedGraphNode::succ_iterator P = node->succ_begin(),
506 E = node->succ_end(); P != E; ++P) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000507
508 //Only process if we are not ignoring the edge
509 if(!ignoreEdge(node, *P)) {
510 processedOneEdge = true;
511 int succALAP = -1;
512 succALAP = calculateALAP(*P, MII, maxASAP, node);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000513
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000514 assert(succALAP != -1 && "Successors ALAP should have been caclulated");
515
516 int iteDiff = P.getEdge().getIteDiff();
517
518 int currentSuccValue = succALAP - node->getLatency() + iteDiff * MII;
519
520 DEBUG(std::cerr << "succ ALAP: " << succALAP << ", iteDiff: " << iteDiff << ", SuccLatency: " << (*P)->getLatency() << ", Current ALAP succ: " << currentSuccValue << "\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000521
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000522 minSuccValue = std::min(minSuccValue, currentSuccValue);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000523 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000524 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000525
526 if(processedOneEdge)
527 attributes.ALAP = minSuccValue;
528
529 else
530 attributes.ALAP = maxASAP;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000531 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000532 else
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000533 attributes.ALAP = maxASAP;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000534
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000535 DEBUG(std::cerr << "ALAP: " << attributes.ALAP << " (" << *node << ")\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000536
537 if(attributes.ALAP < 0)
538 attributes.ALAP = 0;
539
540 return attributes.ALAP;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000541}
542
543int ModuloSchedulingPass::findMaxASAP() {
544 int maxASAP = 0;
545
546 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(),
547 E = nodeToAttributesMap.end(); I != E; ++I)
548 maxASAP = std::max(maxASAP, I->second.ASAP);
549 return maxASAP;
550}
551
552
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000553int ModuloSchedulingPass::calculateHeight(MSchedGraphNode *node,MSchedGraphNode *srcNode) {
554
555 MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000556
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000557 if(attributes.height != -1)
558 return attributes.height;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000559
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000560 int maxHeight = 0;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000561
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000562 //Iterate over all of the predecessors and find max
563 for(MSchedGraphNode::succ_iterator P = node->succ_begin(),
564 E = node->succ_end(); P != E; ++P) {
565
566
567 if(!ignoreEdge(node, *P)) {
568 int succHeight = calculateHeight(*P, node);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000569
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000570 assert(succHeight != -1 && "Successors Height should have been caclulated");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000571
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000572 int currentHeight = succHeight + node->getLatency();
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000573 maxHeight = std::max(maxHeight, currentHeight);
574 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000575 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000576 attributes.height = maxHeight;
577 DEBUG(std::cerr << "Height: " << attributes.height << " (" << *node << ")\n");
578 return maxHeight;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000579}
580
581
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000582int ModuloSchedulingPass::calculateDepth(MSchedGraphNode *node,
583 MSchedGraphNode *destNode) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000584
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000585 MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000586
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000587 if(attributes.depth != -1)
588 return attributes.depth;
589
590 int maxDepth = 0;
591
592 //Iterate over all of the predecessors and fine max
593 for(MSchedGraphNode::pred_iterator P = node->pred_begin(), E = node->pred_end(); P != E; ++P) {
594
595 if(!ignoreEdge(*P, node)) {
596 int predDepth = -1;
597 predDepth = calculateDepth(*P, node);
598
599 assert(predDepth != -1 && "Predecessors ASAP should have been caclulated");
600
601 int currentDepth = predDepth + (*P)->getLatency();
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000602 maxDepth = std::max(maxDepth, currentDepth);
603 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000604 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000605 attributes.depth = maxDepth;
606
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000607 DEBUG(std::cerr << "Depth: " << attributes.depth << " (" << *node << "*)\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000608 return maxDepth;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000609}
610
611
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000612
613void ModuloSchedulingPass::addReccurrence(std::vector<MSchedGraphNode*> &recurrence, int II, MSchedGraphNode *srcBENode, MSchedGraphNode *destBENode) {
614 //Check to make sure that this recurrence is unique
615 bool same = false;
616
617
618 //Loop over all recurrences already in our list
619 for(std::set<std::pair<int, std::vector<MSchedGraphNode*> > >::iterator R = recurrenceList.begin(), RE = recurrenceList.end(); R != RE; ++R) {
620
621 bool all_same = true;
622 //First compare size
623 if(R->second.size() == recurrence.size()) {
624
625 for(std::vector<MSchedGraphNode*>::const_iterator node = R->second.begin(), end = R->second.end(); node != end; ++node) {
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000626 if(std::find(recurrence.begin(), recurrence.end(), *node) == recurrence.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000627 all_same = all_same && false;
628 break;
629 }
630 else
631 all_same = all_same && true;
632 }
633 if(all_same) {
634 same = true;
635 break;
636 }
637 }
638 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000639
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000640 if(!same) {
Tanya Lattner4cffb582004-05-26 06:27:18 +0000641 srcBENode = recurrence.back();
642 destBENode = recurrence.front();
643
644 //FIXME
645 if(destBENode->getInEdge(srcBENode).getIteDiff() == 0) {
646 //DEBUG(std::cerr << "NOT A BACKEDGE\n");
647 //find actual backedge HACK HACK
648 for(unsigned i=0; i< recurrence.size()-1; ++i) {
649 if(recurrence[i+1]->getInEdge(recurrence[i]).getIteDiff() == 1) {
650 srcBENode = recurrence[i];
651 destBENode = recurrence[i+1];
652 break;
653 }
654
655 }
656
657 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000658 DEBUG(std::cerr << "Back Edge to Remove: " << *srcBENode << " to " << *destBENode << "\n");
659 edgesToIgnore.insert(std::make_pair(srcBENode, destBENode->getInEdgeNum(srcBENode)));
660 recurrenceList.insert(std::make_pair(II, recurrence));
661 }
662
663}
664
665void ModuloSchedulingPass::findAllReccurrences(MSchedGraphNode *node,
666 std::vector<MSchedGraphNode*> &visitedNodes,
667 int II) {
668
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000669 if(std::find(visitedNodes.begin(), visitedNodes.end(), node) != visitedNodes.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000670 std::vector<MSchedGraphNode*> recurrence;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000671 bool first = true;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000672 int delay = 0;
673 int distance = 0;
674 int RecMII = II; //Starting value
675 MSchedGraphNode *last = node;
Chris Lattner46c2b3a2004-08-04 03:51:55 +0000676 MSchedGraphNode *srcBackEdge = 0;
677 MSchedGraphNode *destBackEdge = 0;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000678
679
680
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000681 for(std::vector<MSchedGraphNode*>::iterator I = visitedNodes.begin(), E = visitedNodes.end();
682 I !=E; ++I) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000683
684 if(*I == node)
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000685 first = false;
686 if(first)
687 continue;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000688
689 delay = delay + (*I)->getLatency();
690
691 if(*I != node) {
692 int diff = (*I)->getInEdge(last).getIteDiff();
693 distance += diff;
694 if(diff > 0) {
695 srcBackEdge = last;
696 destBackEdge = *I;
697 }
698 }
699
700 recurrence.push_back(*I);
701 last = *I;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000702 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000703
704
705
706 //Get final distance calc
707 distance += node->getInEdge(last).getIteDiff();
708
709
710 //Adjust II until we get close to the inequality delay - II*distance <= 0
711
712 int value = delay-(RecMII * distance);
713 int lastII = II;
714 while(value <= 0) {
715
716 lastII = RecMII;
717 RecMII--;
718 value = delay-(RecMII * distance);
719 }
720
721
722 DEBUG(std::cerr << "Final II for this recurrence: " << lastII << "\n");
723 addReccurrence(recurrence, lastII, srcBackEdge, destBackEdge);
724 assert(distance != 0 && "Recurrence distance should not be zero");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000725 return;
726 }
727
728 for(MSchedGraphNode::succ_iterator I = node->succ_begin(), E = node->succ_end(); I != E; ++I) {
729 visitedNodes.push_back(node);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000730 findAllReccurrences(*I, visitedNodes, II);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000731 visitedNodes.pop_back();
732 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000733}
734
735
736
737
738
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000739void ModuloSchedulingPass::computePartialOrder() {
740
741
742 //Loop over all recurrences and add to our partial order
743 //be sure to remove nodes that are already in the partial order in
744 //a different recurrence and don't add empty recurrences.
745 for(std::set<std::pair<int, std::vector<MSchedGraphNode*> > >::reverse_iterator I = recurrenceList.rbegin(), E=recurrenceList.rend(); I !=E; ++I) {
746
747 //Add nodes that connect this recurrence to the previous recurrence
748
749 //If this is the first recurrence in the partial order, add all predecessors
750 for(std::vector<MSchedGraphNode*>::const_iterator N = I->second.begin(), NE = I->second.end(); N != NE; ++N) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000751
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000752 }
753
754
Tanya Lattner260652a2004-10-30 00:39:07 +0000755 std::set<MSchedGraphNode*> new_recurrence;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000756 //Loop through recurrence and remove any nodes already in the partial order
757 for(std::vector<MSchedGraphNode*>::const_iterator N = I->second.begin(), NE = I->second.end(); N != NE; ++N) {
758 bool found = false;
Tanya Lattner260652a2004-10-30 00:39:07 +0000759 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(), PE = partialOrder.end(); PO != PE; ++PO) {
760 if(PO->count(*N))
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000761 found = true;
762 }
763 if(!found) {
Tanya Lattner260652a2004-10-30 00:39:07 +0000764 new_recurrence.insert(*N);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000765
766 if(partialOrder.size() == 0)
767 //For each predecessors, add it to this recurrence ONLY if it is not already in it
768 for(MSchedGraphNode::pred_iterator P = (*N)->pred_begin(),
769 PE = (*N)->pred_end(); P != PE; ++P) {
770
771 //Check if we are supposed to ignore this edge or not
772 if(!ignoreEdge(*P, *N))
773 //Check if already in this recurrence
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000774 if(std::find(I->second.begin(), I->second.end(), *P) == I->second.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000775 //Also need to check if in partial order
776 bool predFound = false;
Tanya Lattner260652a2004-10-30 00:39:07 +0000777 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(), PEND = partialOrder.end(); PO != PEND; ++PO) {
778 if(PO->count(*P))
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000779 predFound = true;
780 }
781
782 if(!predFound)
Tanya Lattner260652a2004-10-30 00:39:07 +0000783 if(!new_recurrence.count(*P))
784 new_recurrence.insert(*P);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000785
786 }
787 }
788 }
789 }
790
791
792 if(new_recurrence.size() > 0)
793 partialOrder.push_back(new_recurrence);
794 }
795
796 //Add any nodes that are not already in the partial order
Tanya Lattner260652a2004-10-30 00:39:07 +0000797 //Add them in a set, one set per connected component
798 std::set<MSchedGraphNode*> lastNodes;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000799 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
800 bool found = false;
801 //Check if its already in our partial order, if not add it to the final vector
Tanya Lattner260652a2004-10-30 00:39:07 +0000802 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(), PE = partialOrder.end(); PO != PE; ++PO) {
803 if(PO->count(I->first))
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000804 found = true;
805 }
806 if(!found)
Tanya Lattner260652a2004-10-30 00:39:07 +0000807 lastNodes.insert(I->first);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000808 }
809
Tanya Lattner260652a2004-10-30 00:39:07 +0000810 //Break up remaining nodes that are not in the partial order
811 //into their connected compoenents
812 while(lastNodes.size() > 0) {
813 std::set<MSchedGraphNode*> ccSet;
814 connectedComponentSet(*(lastNodes.begin()),ccSet, lastNodes);
815 if(ccSet.size() > 0)
816 partialOrder.push_back(ccSet);
817 }
818 //if(lastNodes.size() > 0)
819 //partialOrder.push_back(lastNodes);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000820
821}
822
823
Tanya Lattner260652a2004-10-30 00:39:07 +0000824void ModuloSchedulingPass::connectedComponentSet(MSchedGraphNode *node, std::set<MSchedGraphNode*> &ccSet, std::set<MSchedGraphNode*> &lastNodes) {
825
826 //Add to final set
827 if( !ccSet.count(node) && lastNodes.count(node)) {
828 lastNodes.erase(node);
829 ccSet.insert(node);
830 }
831 else
832 return;
833
834 //Loop over successors and recurse if we have not seen this node before
835 for(MSchedGraphNode::succ_iterator node_succ = node->succ_begin(), end=node->succ_end(); node_succ != end; ++node_succ) {
836 connectedComponentSet(*node_succ, ccSet, lastNodes);
837 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000838
Tanya Lattner260652a2004-10-30 00:39:07 +0000839}
840
841void ModuloSchedulingPass::predIntersect(std::set<MSchedGraphNode*> &CurrentSet, std::set<MSchedGraphNode*> &IntersectResult) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000842
843 for(unsigned j=0; j < FinalNodeOrder.size(); ++j) {
844 for(MSchedGraphNode::pred_iterator P = FinalNodeOrder[j]->pred_begin(),
845 E = FinalNodeOrder[j]->pred_end(); P != E; ++P) {
846
847 //Check if we are supposed to ignore this edge or not
848 if(ignoreEdge(*P,FinalNodeOrder[j]))
849 continue;
850
Tanya Lattner260652a2004-10-30 00:39:07 +0000851 if(CurrentSet.count(*P))
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000852 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), *P) == FinalNodeOrder.end())
Tanya Lattner260652a2004-10-30 00:39:07 +0000853 IntersectResult.insert(*P);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000854 }
855 }
856}
857
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000858
Tanya Lattner260652a2004-10-30 00:39:07 +0000859
860
861
862void ModuloSchedulingPass::succIntersect(std::set<MSchedGraphNode*> &CurrentSet, std::set<MSchedGraphNode*> &IntersectResult) {
863
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000864 for(unsigned j=0; j < FinalNodeOrder.size(); ++j) {
865 for(MSchedGraphNode::succ_iterator P = FinalNodeOrder[j]->succ_begin(),
866 E = FinalNodeOrder[j]->succ_end(); P != E; ++P) {
867
868 //Check if we are supposed to ignore this edge or not
869 if(ignoreEdge(FinalNodeOrder[j],*P))
870 continue;
871
Tanya Lattner260652a2004-10-30 00:39:07 +0000872 if(CurrentSet.count(*P))
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000873 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), *P) == FinalNodeOrder.end())
Tanya Lattner260652a2004-10-30 00:39:07 +0000874 IntersectResult.insert(*P);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000875 }
876 }
877}
878
Tanya Lattner260652a2004-10-30 00:39:07 +0000879void dumpIntersection(std::set<MSchedGraphNode*> &IntersectCurrent) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000880 std::cerr << "Intersection (";
Tanya Lattner260652a2004-10-30 00:39:07 +0000881 for(std::set<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(), E = IntersectCurrent.end(); I != E; ++I)
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000882 std::cerr << **I << ", ";
883 std::cerr << ")\n";
884}
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000885
886
887
888void ModuloSchedulingPass::orderNodes() {
889
890 int BOTTOM_UP = 0;
891 int TOP_DOWN = 1;
892
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000893 //Set default order
894 int order = BOTTOM_UP;
895
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000896
897 //Loop over all the sets and place them in the final node order
Tanya Lattner260652a2004-10-30 00:39:07 +0000898 for(std::vector<std::set<MSchedGraphNode*> >::iterator CurrentSet = partialOrder.begin(), E= partialOrder.end(); CurrentSet != E; ++CurrentSet) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000899
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000900 DEBUG(std::cerr << "Processing set in S\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +0000901 DEBUG(dumpIntersection(*CurrentSet));
902
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000903 //Result of intersection
Tanya Lattner260652a2004-10-30 00:39:07 +0000904 std::set<MSchedGraphNode*> IntersectCurrent;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000905
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000906 predIntersect(*CurrentSet, IntersectCurrent);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000907
908 //If the intersection of predecessor and current set is not empty
909 //sort nodes bottom up
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000910 if(IntersectCurrent.size() != 0) {
911 DEBUG(std::cerr << "Final Node Order Predecessors and Current Set interesection is NOT empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000912 order = BOTTOM_UP;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000913 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000914 //If empty, use successors
915 else {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000916 DEBUG(std::cerr << "Final Node Order Predecessors and Current Set interesection is empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000917
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000918 succIntersect(*CurrentSet, IntersectCurrent);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000919
920 //sort top-down
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000921 if(IntersectCurrent.size() != 0) {
922 DEBUG(std::cerr << "Final Node Order Successors and Current Set interesection is NOT empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000923 order = TOP_DOWN;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000924 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000925 else {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000926 DEBUG(std::cerr << "Final Node Order Successors and Current Set interesection is empty\n");
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000927 //Find node with max ASAP in current Set
928 MSchedGraphNode *node;
929 int maxASAP = 0;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000930 DEBUG(std::cerr << "Using current set of size " << CurrentSet->size() << "to find max ASAP\n");
Tanya Lattner260652a2004-10-30 00:39:07 +0000931 for(std::set<MSchedGraphNode*>::iterator J = CurrentSet->begin(), JE = CurrentSet->end(); J != JE; ++J) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000932 //Get node attributes
Tanya Lattner260652a2004-10-30 00:39:07 +0000933 MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*J)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000934 //assert(nodeAttr != nodeToAttributesMap.end() && "Node not in attributes map!");
Tanya Lattner260652a2004-10-30 00:39:07 +0000935
936 if(maxASAP <= nodeAttr.ASAP) {
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000937 maxASAP = nodeAttr.ASAP;
Tanya Lattner260652a2004-10-30 00:39:07 +0000938 node = *J;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000939 }
940 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000941 assert(node != 0 && "In node ordering node should not be null");
Tanya Lattner260652a2004-10-30 00:39:07 +0000942 IntersectCurrent.insert(node);
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000943 order = BOTTOM_UP;
944 }
945 }
946
947 //Repeat until all nodes are put into the final order from current set
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000948 while(IntersectCurrent.size() > 0) {
949
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000950 if(order == TOP_DOWN) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000951 DEBUG(std::cerr << "Order is TOP DOWN\n");
952
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000953 while(IntersectCurrent.size() > 0) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000954 DEBUG(std::cerr << "Intersection is not empty, so find heighest height\n");
955
956 int MOB = 0;
957 int height = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +0000958 MSchedGraphNode *highestHeightNode = *(IntersectCurrent.begin());
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000959
960 //Find node in intersection with highest heigh and lowest MOB
Tanya Lattner260652a2004-10-30 00:39:07 +0000961 for(std::set<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(),
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000962 E = IntersectCurrent.end(); I != E; ++I) {
963
964 //Get current nodes properties
965 MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*I)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000966
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000967 if(height < nodeAttr.height) {
968 highestHeightNode = *I;
969 height = nodeAttr.height;
970 MOB = nodeAttr.MOB;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000971 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000972 else if(height == nodeAttr.height) {
973 if(MOB > nodeAttr.height) {
974 highestHeightNode = *I;
975 height = nodeAttr.height;
976 MOB = nodeAttr.MOB;
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000977 }
978 }
979 }
980
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000981 //Append our node with greatest height to the NodeOrder
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000982 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), highestHeightNode) == FinalNodeOrder.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000983 DEBUG(std::cerr << "Adding node to Final Order: " << *highestHeightNode << "\n");
984 FinalNodeOrder.push_back(highestHeightNode);
985 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000986
987 //Remove V from IntersectOrder
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000988 IntersectCurrent.erase(std::find(IntersectCurrent.begin(),
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000989 IntersectCurrent.end(), highestHeightNode));
990
Tanya Lattnerd14b8372004-03-01 02:50:01 +0000991
992 //Intersect V's successors with CurrentSet
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000993 for(MSchedGraphNode::succ_iterator P = highestHeightNode->succ_begin(),
994 E = highestHeightNode->succ_end(); P != E; ++P) {
995 //if(lower_bound(CurrentSet->begin(),
996 // CurrentSet->end(), *P) != CurrentSet->end()) {
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +0000997 if(std::find(CurrentSet->begin(), CurrentSet->end(), *P) != CurrentSet->end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +0000998 if(ignoreEdge(highestHeightNode, *P))
999 continue;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001000 //If not already in Intersect, add
Tanya Lattner260652a2004-10-30 00:39:07 +00001001 if(!IntersectCurrent.count(*P))
1002 IntersectCurrent.insert(*P);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001003 }
1004 }
1005 } //End while loop over Intersect Size
1006
1007 //Change direction
1008 order = BOTTOM_UP;
1009
1010 //Reset Intersect to reflect changes in OrderNodes
1011 IntersectCurrent.clear();
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001012 predIntersect(*CurrentSet, IntersectCurrent);
1013
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001014 } //End If TOP_DOWN
1015
1016 //Begin if BOTTOM_UP
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001017 else {
1018 DEBUG(std::cerr << "Order is BOTTOM UP\n");
1019 while(IntersectCurrent.size() > 0) {
1020 DEBUG(std::cerr << "Intersection of size " << IntersectCurrent.size() << ", finding highest depth\n");
1021
1022 //dump intersection
1023 DEBUG(dumpIntersection(IntersectCurrent));
1024 //Get node with highest depth, if a tie, use one with lowest
1025 //MOB
1026 int MOB = 0;
1027 int depth = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +00001028 MSchedGraphNode *highestDepthNode = *(IntersectCurrent.begin());
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001029
Tanya Lattner260652a2004-10-30 00:39:07 +00001030 for(std::set<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(),
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001031 E = IntersectCurrent.end(); I != E; ++I) {
1032 //Find node attribute in graph
1033 MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*I)->second;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001034
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001035 if(depth < nodeAttr.depth) {
1036 highestDepthNode = *I;
1037 depth = nodeAttr.depth;
1038 MOB = nodeAttr.MOB;
1039 }
1040 else if(depth == nodeAttr.depth) {
1041 if(MOB > nodeAttr.MOB) {
1042 highestDepthNode = *I;
1043 depth = nodeAttr.depth;
1044 MOB = nodeAttr.MOB;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001045 }
1046 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001047 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001048
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001049
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001050
1051 //Append highest depth node to the NodeOrder
Alkis Evlogimenosc72c6172004-09-28 14:42:44 +00001052 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), highestDepthNode) == FinalNodeOrder.end()) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001053 DEBUG(std::cerr << "Adding node to Final Order: " << *highestDepthNode << "\n");
1054 FinalNodeOrder.push_back(highestDepthNode);
1055 }
1056 //Remove heightestDepthNode from IntersectOrder
Tanya Lattner260652a2004-10-30 00:39:07 +00001057 IntersectCurrent.erase(highestDepthNode);
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001058
1059
1060 //Intersect heightDepthNode's pred with CurrentSet
1061 for(MSchedGraphNode::pred_iterator P = highestDepthNode->pred_begin(),
1062 E = highestDepthNode->pred_end(); P != E; ++P) {
Tanya Lattner260652a2004-10-30 00:39:07 +00001063 if(CurrentSet->count(*P)) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001064 if(ignoreEdge(*P, highestDepthNode))
1065 continue;
1066
1067 //If not already in Intersect, add
Tanya Lattner260652a2004-10-30 00:39:07 +00001068 if(!IntersectCurrent.count(*P))
1069 IntersectCurrent.insert(*P);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001070 }
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001071 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001072
1073 } //End while loop over Intersect Size
1074
1075 //Change order
1076 order = TOP_DOWN;
1077
1078 //Reset IntersectCurrent to reflect changes in OrderNodes
1079 IntersectCurrent.clear();
1080 succIntersect(*CurrentSet, IntersectCurrent);
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001081 } //End if BOTTOM_DOWN
1082
Tanya Lattner420025b2004-10-10 22:44:35 +00001083 DEBUG(std::cerr << "Current Intersection Size: " << IntersectCurrent.size() << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001084 }
1085 //End Wrapping while loop
Tanya Lattner420025b2004-10-10 22:44:35 +00001086 DEBUG(std::cerr << "Ending Size of Current Set: " << CurrentSet->size() << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001087 }//End for over all sets of nodes
Tanya Lattner420025b2004-10-10 22:44:35 +00001088
1089 //FIXME: As the algorithm stands it will NEVER add an instruction such as ba (with no
1090 //data dependencies) to the final order. We add this manually. It will always be
1091 //in the last set of S since its not part of a recurrence
1092 //Loop over all the sets and place them in the final node order
Tanya Lattner260652a2004-10-30 00:39:07 +00001093 std::vector<std::set<MSchedGraphNode*> > ::reverse_iterator LastSet = partialOrder.rbegin();
1094 for(std::set<MSchedGraphNode*>::iterator CurrentNode = LastSet->begin(), LastNode = LastSet->end();
Tanya Lattner420025b2004-10-10 22:44:35 +00001095 CurrentNode != LastNode; ++CurrentNode) {
1096 if((*CurrentNode)->getInst()->getOpcode() == V9::BA)
1097 FinalNodeOrder.push_back(*CurrentNode);
1098 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001099 //Return final Order
1100 //return FinalNodeOrder;
1101}
1102
1103void ModuloSchedulingPass::computeSchedule() {
1104
1105 bool success = false;
1106
Tanya Lattner260652a2004-10-30 00:39:07 +00001107 //FIXME: Should be set to max II of the original loop
1108 //Cap II in order to prevent infinite loop
1109 int capII = 30;
1110
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001111 while(!success) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001112
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001113 //Loop over the final node order and process each node
1114 for(std::vector<MSchedGraphNode*>::iterator I = FinalNodeOrder.begin(),
1115 E = FinalNodeOrder.end(); I != E; ++I) {
1116
1117 //CalculateEarly and Late start
1118 int EarlyStart = -1;
1119 int LateStart = 99999; //Set to something higher then we would ever expect (FIXME)
1120 bool hasSucc = false;
1121 bool hasPred = false;
Tanya Lattner4cffb582004-05-26 06:27:18 +00001122
1123 if(!(*I)->isBranch()) {
1124 //Loop over nodes in the schedule and determine if they are predecessors
1125 //or successors of the node we are trying to schedule
1126 for(MSSchedule::schedule_iterator nodesByCycle = schedule.begin(), nodesByCycleEnd = schedule.end();
1127 nodesByCycle != nodesByCycleEnd; ++nodesByCycle) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001128
Tanya Lattner4cffb582004-05-26 06:27:18 +00001129 //For this cycle, get the vector of nodes schedule and loop over it
1130 for(std::vector<MSchedGraphNode*>::iterator schedNode = nodesByCycle->second.begin(), SNE = nodesByCycle->second.end(); schedNode != SNE; ++schedNode) {
1131
1132 if((*I)->isPredecessor(*schedNode)) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001133 if(!ignoreEdge(*schedNode, *I)) {
1134 int diff = (*I)->getInEdge(*schedNode).getIteDiff();
Tanya Lattner4cffb582004-05-26 06:27:18 +00001135 int ES_Temp = nodesByCycle->first + (*schedNode)->getLatency() - diff * II;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001136 DEBUG(std::cerr << "Diff: " << diff << " Cycle: " << nodesByCycle->first << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001137 DEBUG(std::cerr << "Temp EarlyStart: " << ES_Temp << " Prev EarlyStart: " << EarlyStart << "\n");
1138 EarlyStart = std::max(EarlyStart, ES_Temp);
1139 hasPred = true;
1140 }
1141 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001142 if((*I)->isSuccessor(*schedNode)) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001143 if(!ignoreEdge(*I,*schedNode)) {
1144 int diff = (*schedNode)->getInEdge(*I).getIteDiff();
Tanya Lattner4cffb582004-05-26 06:27:18 +00001145 int LS_Temp = nodesByCycle->first - (*I)->getLatency() + diff * II;
1146 DEBUG(std::cerr << "Diff: " << diff << " Cycle: " << nodesByCycle->first << "\n");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001147 DEBUG(std::cerr << "Temp LateStart: " << LS_Temp << " Prev LateStart: " << LateStart << "\n");
1148 LateStart = std::min(LateStart, LS_Temp);
1149 hasSucc = true;
1150 }
1151 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001152 }
1153 }
1154 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001155 else {
1156 //WARNING: HACK! FIXME!!!!
Tanya Lattner420025b2004-10-10 22:44:35 +00001157 if((*I)->getInst()->getOpcode() == V9::BA) {
1158 EarlyStart = II-1;
1159 LateStart = II-1;
1160 }
1161 else {
1162 EarlyStart = II-1;
1163 LateStart = II-1;
1164 assert( (EarlyStart >= 0) && (LateStart >=0) && "EarlyStart and LateStart must be greater then 0");
1165 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001166 hasPred = 1;
1167 hasSucc = 1;
1168 }
1169
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001170
1171 DEBUG(std::cerr << "Has Successors: " << hasSucc << ", Has Pred: " << hasPred << "\n");
1172 DEBUG(std::cerr << "EarlyStart: " << EarlyStart << ", LateStart: " << LateStart << "\n");
1173
1174 //Check if the node has no pred or successors and set Early Start to its ASAP
1175 if(!hasSucc && !hasPred)
1176 EarlyStart = nodeToAttributesMap.find(*I)->second.ASAP;
1177
1178 //Now, try to schedule this node depending upon its pred and successor in the schedule
1179 //already
1180 if(!hasSucc && hasPred)
1181 success = scheduleNode(*I, EarlyStart, (EarlyStart + II -1));
1182 else if(!hasPred && hasSucc)
1183 success = scheduleNode(*I, LateStart, (LateStart - II +1));
1184 else if(hasPred && hasSucc)
1185 success = scheduleNode(*I, EarlyStart, std::min(LateStart, (EarlyStart + II -1)));
1186 else
1187 success = scheduleNode(*I, EarlyStart, EarlyStart + II - 1);
1188
1189 if(!success) {
1190 ++II;
1191 schedule.clear();
1192 break;
1193 }
1194
1195 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001196
Tanya Lattner260652a2004-10-30 00:39:07 +00001197 if(success) {
1198 DEBUG(std::cerr << "Constructing Schedule Kernel\n");
1199 success = schedule.constructKernel(II);
1200 DEBUG(std::cerr << "Done Constructing Schedule Kernel\n");
1201 if(!success) {
1202 ++II;
1203 schedule.clear();
1204 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001205 }
Tanya Lattner260652a2004-10-30 00:39:07 +00001206
1207 assert(II < capII && "The II should not exceed the original loop number of cycles");
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001208 }
1209}
1210
1211
1212bool ModuloSchedulingPass::scheduleNode(MSchedGraphNode *node,
1213 int start, int end) {
1214 bool success = false;
1215
1216 DEBUG(std::cerr << *node << " (Start Cycle: " << start << ", End Cycle: " << end << ")\n");
1217
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001218 //Make sure start and end are not negative
Tanya Lattner260652a2004-10-30 00:39:07 +00001219 if(start < 0) {
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001220 start = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +00001221
1222 }
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001223 if(end < 0)
1224 end = 0;
1225
1226 bool forward = true;
1227 if(start > end)
1228 forward = false;
1229
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001230 bool increaseSC = true;
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001231 int cycle = start ;
1232
1233
1234 while(increaseSC) {
1235
1236 increaseSC = false;
1237
Tanya Lattner4cffb582004-05-26 06:27:18 +00001238 increaseSC = schedule.insert(node, cycle);
1239
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001240 if(!increaseSC)
1241 return true;
1242
1243 //Increment cycle to try again
1244 if(forward) {
1245 ++cycle;
1246 DEBUG(std::cerr << "Increase cycle: " << cycle << "\n");
1247 if(cycle > end)
1248 return false;
1249 }
1250 else {
1251 --cycle;
1252 DEBUG(std::cerr << "Decrease cycle: " << cycle << "\n");
1253 if(cycle < end)
1254 return false;
1255 }
1256 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001257
Tanya Lattner73e3e2e2004-05-08 16:12:10 +00001258 return success;
Tanya Lattnerd14b8372004-03-01 02:50:01 +00001259}
Tanya Lattner4cffb582004-05-26 06:27:18 +00001260
Tanya Lattner420025b2004-10-10 22:44:35 +00001261void 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 +00001262
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001263 //Keep a map to easily know whats in the kernel
Tanya Lattner4cffb582004-05-26 06:27:18 +00001264 std::map<int, std::set<const MachineInstr*> > inKernel;
1265 int maxStageCount = 0;
1266
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001267 MSchedGraphNode *branch = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +00001268 MSchedGraphNode *BAbranch = 0;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001269
Tanya Lattner4cffb582004-05-26 06:27:18 +00001270 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
1271 maxStageCount = std::max(maxStageCount, I->second);
1272
1273 //Ignore the branch, we will handle this separately
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001274 if(I->first->isBranch()) {
Tanya Lattnera6457502004-10-14 06:04:28 +00001275 if (I->first->getInst()->getOpcode() != V9::BA)
Tanya Lattner420025b2004-10-10 22:44:35 +00001276 branch = I->first;
Tanya Lattner260652a2004-10-30 00:39:07 +00001277 else
1278 BAbranch = I->first;
1279
Tanya Lattner4cffb582004-05-26 06:27:18 +00001280 continue;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001281 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001282
1283 //Put int the map so we know what instructions in each stage are in the kernel
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001284 DEBUG(std::cerr << "Inserting instruction " << *(I->first->getInst()) << " into map at stage " << I->second << "\n");
1285 inKernel[I->second].insert(I->first->getInst());
Tanya Lattner4cffb582004-05-26 06:27:18 +00001286 }
1287
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001288 //Get target information to look at machine operands
1289 const TargetInstrInfo *mii = target.getInstrInfo();
1290
1291 //Now write the prologues
1292 for(int i = 0; i < maxStageCount; ++i) {
1293 BasicBlock *llvmBB = new BasicBlock("PROLOGUE", (Function*) (origBB->getBasicBlock()->getParent()));
Tanya Lattner4cffb582004-05-26 06:27:18 +00001294 MachineBasicBlock *machineBB = new MachineBasicBlock(llvmBB);
1295
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001296 DEBUG(std::cerr << "i=" << i << "\n");
1297 for(int j = 0; j <= i; ++j) {
1298 for(MachineBasicBlock::const_iterator MI = origBB->begin(), ME = origBB->end(); ME != MI; ++MI) {
1299 if(inKernel[j].count(&*MI)) {
Tanya Lattner420025b2004-10-10 22:44:35 +00001300 MachineInstr *instClone = MI->clone();
1301 machineBB->push_back(instClone);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001302
Tanya Lattner420025b2004-10-10 22:44:35 +00001303 DEBUG(std::cerr << "Cloning: " << *MI << "\n");
1304
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001305 Instruction *tmp;
1306
1307 //After cloning, we may need to save the value that this instruction defines
1308 for(unsigned opNum=0; opNum < MI->getNumOperands(); ++opNum) {
1309 //get machine operand
Tanya Lattner420025b2004-10-10 22:44:35 +00001310 const MachineOperand &mOp = instClone->getOperand(opNum);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001311 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef()) {
1312
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001313 //Check if this is a value we should save
1314 if(valuesToSave.count(mOp.getVRegValue())) {
1315 //Save copy in tmpInstruction
1316 tmp = new TmpInstruction(mOp.getVRegValue());
1317
Tanya Lattner80f08552004-11-02 21:04:56 +00001318 //Add TmpInstruction to safe LLVM Instruction MCFI
1319 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001320 tempMvec.addTemp((Value*) tmp);
1321
Tanya Lattner420025b2004-10-10 22:44:35 +00001322 DEBUG(std::cerr << "Value: " << *(mOp.getVRegValue()) << " New Value: " << *tmp << " Stage: " << i << "\n");
1323
1324 newValues[mOp.getVRegValue()][i]= tmp;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001325 newValLocation[tmp] = machineBB;
1326
Tanya Lattner420025b2004-10-10 22:44:35 +00001327 DEBUG(std::cerr << "Machine Instr Operands: " << *(mOp.getVRegValue()) << ", 0, " << *tmp << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001328
1329 //Create machine instruction and put int machineBB
1330 MachineInstr *saveValue = BuildMI(machineBB, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
1331
1332 DEBUG(std::cerr << "Created new machine instr: " << *saveValue << "\n");
1333 }
1334 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001335
1336 //We may also need to update the value that we use if its from an earlier prologue
1337 if(j != 0) {
1338 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse()) {
1339 if(newValues.count(mOp.getVRegValue()))
1340 if(newValues[mOp.getVRegValue()].count(j-1)) {
1341 DEBUG(std::cerr << "Replaced this value: " << mOp.getVRegValue() << " With:" << (newValues[mOp.getVRegValue()][i-1]) << "\n");
1342 //Update the operand with the right value
1343 instClone->getOperand(opNum).setValueReg(newValues[mOp.getVRegValue()][i-1]);
1344 }
1345 }
1346 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001347 }
1348 }
Tanya Lattner20890832004-05-28 20:14:12 +00001349 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001350 }
1351
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001352
1353 //Stick in branch at the end
1354 machineBB->push_back(branch->getInst()->clone());
Tanya Lattner420025b2004-10-10 22:44:35 +00001355
Tanya Lattner260652a2004-10-30 00:39:07 +00001356 //Add nop
1357 BuildMI(machineBB, V9::NOP, 0);
1358
1359 //Stick in branch at the end
1360 machineBB->push_back(BAbranch->getInst()->clone());
1361
1362 //Add nop
1363 BuildMI(machineBB, V9::NOP, 0);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001364
1365 (((MachineBasicBlock*)origBB)->getParent())->getBasicBlockList().push_back(machineBB);
Tanya Lattner4cffb582004-05-26 06:27:18 +00001366 prologues.push_back(machineBB);
1367 llvm_prologues.push_back(llvmBB);
1368 }
1369}
1370
Tanya Lattner420025b2004-10-10 22:44:35 +00001371void 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 +00001372
Tanya Lattner20890832004-05-28 20:14:12 +00001373 std::map<int, std::set<const MachineInstr*> > inKernel;
Tanya Lattner420025b2004-10-10 22:44:35 +00001374
Tanya Lattner20890832004-05-28 20:14:12 +00001375 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
Tanya Lattner20890832004-05-28 20:14:12 +00001376
1377 //Ignore the branch, we will handle this separately
1378 if(I->first->isBranch())
1379 continue;
1380
1381 //Put int the map so we know what instructions in each stage are in the kernel
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001382 inKernel[I->second].insert(I->first->getInst());
Tanya Lattner20890832004-05-28 20:14:12 +00001383 }
1384
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001385 std::map<Value*, Value*> valPHIs;
1386
Tanya Lattner420025b2004-10-10 22:44:35 +00001387 //some debug stuff, will remove later
1388 DEBUG(for(std::map<Value*, std::map<int, Value*> >::iterator V = newValues.begin(), E = newValues.end(); V !=E; ++V) {
1389 std::cerr << "Old Value: " << *(V->first) << "\n";
1390 for(std::map<int, Value*>::iterator I = V->second.begin(), IE = V->second.end(); I != IE; ++I)
1391 std::cerr << "Stage: " << I->first << " Value: " << *(I->second) << "\n";
1392 });
1393
1394 //some debug stuff, will remove later
1395 DEBUG(for(std::map<Value*, std::map<int, Value*> >::iterator V = kernelPHIs.begin(), E = kernelPHIs.end(); V !=E; ++V) {
1396 std::cerr << "Old Value: " << *(V->first) << "\n";
1397 for(std::map<int, Value*>::iterator I = V->second.begin(), IE = V->second.end(); I != IE; ++I)
1398 std::cerr << "Stage: " << I->first << " Value: " << *(I->second) << "\n";
1399 });
1400
Tanya Lattner20890832004-05-28 20:14:12 +00001401 //Now write the epilogues
Tanya Lattner420025b2004-10-10 22:44:35 +00001402 for(int i = schedule.getMaxStage()-1; i >= 0; --i) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001403 BasicBlock *llvmBB = new BasicBlock("EPILOGUE", (Function*) (origBB->getBasicBlock()->getParent()));
Tanya Lattner20890832004-05-28 20:14:12 +00001404 MachineBasicBlock *machineBB = new MachineBasicBlock(llvmBB);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001405
Tanya Lattner420025b2004-10-10 22:44:35 +00001406 DEBUG(std::cerr << " Epilogue #: " << i << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001407
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001408
Tanya Lattnera6457502004-10-14 06:04:28 +00001409 std::map<Value*, int> inEpilogue;
Tanya Lattner420025b2004-10-10 22:44:35 +00001410
1411 for(MachineBasicBlock::const_iterator MI = origBB->begin(), ME = origBB->end(); ME != MI; ++MI) {
1412 for(int j=schedule.getMaxStage(); j > i; --j) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001413 if(inKernel[j].count(&*MI)) {
1414 DEBUG(std::cerr << "Cloning instruction " << *MI << "\n");
1415 MachineInstr *clone = MI->clone();
1416
1417 //Update operands that need to use the result from the phi
Tanya Lattner420025b2004-10-10 22:44:35 +00001418 for(unsigned opNum=0; opNum < clone->getNumOperands(); ++opNum) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001419 //get machine operand
Tanya Lattner420025b2004-10-10 22:44:35 +00001420 const MachineOperand &mOp = clone->getOperand(opNum);
Tanya Lattner420025b2004-10-10 22:44:35 +00001421
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001422 if((mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse())) {
Tanya Lattner420025b2004-10-10 22:44:35 +00001423
1424 DEBUG(std::cerr << "Writing PHI for " << *(mOp.getVRegValue()) << "\n");
Tanya Lattnera6457502004-10-14 06:04:28 +00001425
1426 //If this is the last instructions for the max iterations ago, don't update operands
1427 if(inEpilogue.count(mOp.getVRegValue()))
1428 if(inEpilogue[mOp.getVRegValue()] == i)
1429 continue;
Tanya Lattner420025b2004-10-10 22:44:35 +00001430
1431 //Quickly write appropriate phis for this operand
1432 if(newValues.count(mOp.getVRegValue())) {
1433 if(newValues[mOp.getVRegValue()].count(i)) {
1434 Instruction *tmp = new TmpInstruction(newValues[mOp.getVRegValue()][i]);
Tanya Lattnera6457502004-10-14 06:04:28 +00001435
1436 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00001437 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001438 tempMvec.addTemp((Value*) tmp);
1439
Tanya Lattner420025b2004-10-10 22:44:35 +00001440 MachineInstr *saveValue = BuildMI(machineBB, V9::PHI, 3).addReg(newValues[mOp.getVRegValue()][i]).addReg(kernelPHIs[mOp.getVRegValue()][i]).addRegDef(tmp);
1441 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
1442 valPHIs[mOp.getVRegValue()] = tmp;
1443 }
1444 }
1445
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001446 if(valPHIs.count(mOp.getVRegValue())) {
1447 //Update the operand in the cloned instruction
Tanya Lattner420025b2004-10-10 22:44:35 +00001448 clone->getOperand(opNum).setValueReg(valPHIs[mOp.getVRegValue()]);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001449 }
1450 }
Tanya Lattnera6457502004-10-14 06:04:28 +00001451 else if((mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef())) {
1452 inEpilogue[mOp.getVRegValue()] = i;
1453 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001454 }
1455 machineBB->push_back(clone);
1456 }
1457 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001458 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001459
Tanya Lattner20890832004-05-28 20:14:12 +00001460 (((MachineBasicBlock*)origBB)->getParent())->getBasicBlockList().push_back(machineBB);
1461 epilogues.push_back(machineBB);
1462 llvm_epilogues.push_back(llvmBB);
Tanya Lattner420025b2004-10-10 22:44:35 +00001463
1464 DEBUG(std::cerr << "EPILOGUE #" << i << "\n");
1465 DEBUG(machineBB->print(std::cerr));
Tanya Lattner20890832004-05-28 20:14:12 +00001466 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001467}
1468
Tanya Lattner420025b2004-10-10 22:44:35 +00001469void 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 +00001470
1471 //Keep track of operands that are read and saved from a previous iteration. The new clone
1472 //instruction will use the result of the phi instead.
1473 std::map<Value*, Value*> finalPHIValue;
1474 std::map<Value*, Value*> kernelValue;
1475
1476 //Create TmpInstructions for the final phis
1477 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
1478
Tanya Lattner420025b2004-10-10 22:44:35 +00001479 DEBUG(std::cerr << "Stage: " << I->second << " Inst: " << *(I->first->getInst()) << "\n";);
1480
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001481 //Clone instruction
1482 const MachineInstr *inst = I->first->getInst();
1483 MachineInstr *instClone = inst->clone();
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001484
Tanya Lattner420025b2004-10-10 22:44:35 +00001485 //Insert into machine basic block
1486 machineBB->push_back(instClone);
1487
Tanya Lattnerced82222004-11-16 21:31:37 +00001488 DEBUG(std::cerr << "Cloned Inst: " << *instClone << "\n");
1489
Tanya Lattnera6457502004-10-14 06:04:28 +00001490 if(I->first->isBranch()) {
1491 //Add kernel noop
1492 BuildMI(machineBB, V9::NOP, 0);
1493 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001494
1495 //Loop over Machine Operands
1496 for(unsigned i=0; i < inst->getNumOperands(); ++i) {
1497 //get machine operand
1498 const MachineOperand &mOp = inst->getOperand(i);
1499
1500 if(I->second != 0) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001501 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse()) {
Tanya Lattner420025b2004-10-10 22:44:35 +00001502
1503 //Check to see where this operand is defined if this instruction is from max stage
1504 if(I->second == schedule.getMaxStage()) {
1505 DEBUG(std::cerr << "VREG: " << *(mOp.getVRegValue()) << "\n");
1506 }
1507
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001508 //If its in the value saved, we need to create a temp instruction and use that instead
1509 if(valuesToSave.count(mOp.getVRegValue())) {
Tanya Lattnerced82222004-11-16 21:31:37 +00001510
1511 //Check if we already have a final PHI value for this
1512 if(!finalPHIValue.count(mOp.getVRegValue())) {
1513 TmpInstruction *tmp = new TmpInstruction(mOp.getVRegValue());
1514
1515 //Get machine code for this instruction
1516 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
1517 tempMvec.addTemp((Value*) tmp);
1518
1519 //Update the operand in the cloned instruction
1520 instClone->getOperand(i).setValueReg(tmp);
1521
1522 //save this as our final phi
1523 finalPHIValue[mOp.getVRegValue()] = tmp;
1524 newValLocation[tmp] = machineBB;
1525 }
1526 else {
1527 //Use the previous final phi value
1528 instClone->getOperand(i).setValueReg(finalPHIValue[mOp.getVRegValue()]);
1529 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001530 }
1531 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001532 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001533 if(I->second != schedule.getMaxStage()) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001534 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef()) {
1535 if(valuesToSave.count(mOp.getVRegValue())) {
1536
1537 TmpInstruction *tmp = new TmpInstruction(mOp.getVRegValue());
1538
Tanya Lattnera6457502004-10-14 06:04:28 +00001539 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00001540 MachineCodeForInstruction & tempVec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001541 tempVec.addTemp((Value*) tmp);
1542
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001543 //Create new machine instr and put in MBB
1544 MachineInstr *saveValue = BuildMI(machineBB, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
1545
1546 //Save for future cleanup
1547 kernelValue[mOp.getVRegValue()] = tmp;
1548 newValLocation[tmp] = machineBB;
Tanya Lattner420025b2004-10-10 22:44:35 +00001549 kernelPHIs[mOp.getVRegValue()][schedule.getMaxStage()-1] = tmp;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001550 }
1551 }
1552 }
1553 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001554
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001555 }
1556
Tanya Lattner420025b2004-10-10 22:44:35 +00001557 DEBUG(std::cerr << "KERNEL before PHIs\n");
1558 DEBUG(machineBB->print(std::cerr));
1559
1560
1561 //Loop over each value we need to generate phis for
1562 for(std::map<Value*, std::map<int, Value*> >::iterator V = newValues.begin(),
1563 E = newValues.end(); V != E; ++V) {
1564
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001565
1566 DEBUG(std::cerr << "Writing phi for" << *(V->first));
Tanya Lattner420025b2004-10-10 22:44:35 +00001567 DEBUG(std::cerr << "\nMap of Value* for this phi\n");
1568 DEBUG(for(std::map<int, Value*>::iterator I = V->second.begin(),
1569 IE = V->second.end(); I != IE; ++I) {
1570 std::cerr << "Stage: " << I->first;
1571 std::cerr << " Value: " << *(I->second) << "\n";
1572 });
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001573
Tanya Lattner420025b2004-10-10 22:44:35 +00001574 //If we only have one current iteration live, its safe to set lastPhi = to kernel value
1575 if(V->second.size() == 1) {
1576 assert(kernelValue[V->first] != 0 && "Kernel value* must exist to create phi");
1577 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(),V9::PHI, 3).addReg(V->second.begin()->second).addReg(kernelValue[V->first]).addRegDef(finalPHIValue[V->first]);
1578 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
1579 kernelPHIs[V->first][schedule.getMaxStage()-1] = kernelValue[V->first];
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001580 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001581 else {
1582
1583 //Keep track of last phi created.
1584 Instruction *lastPhi = 0;
1585
1586 unsigned count = 1;
1587 //Loop over the the map backwards to generate phis
1588 for(std::map<int, Value*>::reverse_iterator I = V->second.rbegin(), IE = V->second.rend();
1589 I != IE; ++I) {
1590
1591 if(count < (V->second).size()) {
1592 if(lastPhi == 0) {
1593 lastPhi = new TmpInstruction(I->second);
Tanya Lattnera6457502004-10-14 06:04:28 +00001594
1595 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00001596 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001597 tempMvec.addTemp((Value*) lastPhi);
1598
Tanya Lattner420025b2004-10-10 22:44:35 +00001599 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(), V9::PHI, 3).addReg(kernelValue[V->first]).addReg(I->second).addRegDef(lastPhi);
1600 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
1601 newValLocation[lastPhi] = machineBB;
1602 }
1603 else {
1604 Instruction *tmp = new TmpInstruction(I->second);
Tanya Lattnera6457502004-10-14 06:04:28 +00001605
1606 //Get machine code for this instruction
Tanya Lattner80f08552004-11-02 21:04:56 +00001607 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnera6457502004-10-14 06:04:28 +00001608 tempMvec.addTemp((Value*) tmp);
1609
1610
Tanya Lattner420025b2004-10-10 22:44:35 +00001611 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(), V9::PHI, 3).addReg(lastPhi).addReg(I->second).addRegDef(tmp);
1612 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
1613 lastPhi = tmp;
1614 kernelPHIs[V->first][I->first] = lastPhi;
1615 newValLocation[lastPhi] = machineBB;
1616 }
1617 }
1618 //Final phi value
1619 else {
1620 //The resulting value must be the Value* we created earlier
1621 assert(lastPhi != 0 && "Last phi is NULL!\n");
1622 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(), V9::PHI, 3).addReg(lastPhi).addReg(I->second).addRegDef(finalPHIValue[V->first]);
1623 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
1624 kernelPHIs[V->first][I->first] = finalPHIValue[V->first];
1625 }
1626
1627 ++count;
1628 }
1629
1630 }
1631 }
1632
1633 DEBUG(std::cerr << "KERNEL after PHIs\n");
1634 DEBUG(machineBB->print(std::cerr));
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001635}
1636
Tanya Lattner420025b2004-10-10 22:44:35 +00001637
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001638void ModuloSchedulingPass::removePHIs(const MachineBasicBlock *origBB, std::vector<MachineBasicBlock *> &prologues, std::vector<MachineBasicBlock *> &epilogues, MachineBasicBlock *kernelBB, std::map<Value*, MachineBasicBlock*> &newValLocation) {
1639
1640 //Worklist to delete things
1641 std::vector<std::pair<MachineBasicBlock*, MachineBasicBlock::iterator> > worklist;
Tanya Lattnera6457502004-10-14 06:04:28 +00001642
1643 //Worklist of TmpInstructions that need to be added to a MCFI
1644 std::vector<Instruction*> addToMCFI;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001645
Tanya Lattnera6457502004-10-14 06:04:28 +00001646 //Worklist to add OR instructions to end of kernel so not to invalidate the iterator
1647 //std::vector<std::pair<Instruction*, Value*> > newORs;
1648
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001649 const TargetInstrInfo *TMI = target.getInstrInfo();
1650
1651 //Start with the kernel and for each phi insert a copy for the phi def and for each arg
1652 for(MachineBasicBlock::iterator I = kernelBB->begin(), E = kernelBB->end(); I != E; ++I) {
Tanya Lattnera6457502004-10-14 06:04:28 +00001653
Tanya Lattner80f08552004-11-02 21:04:56 +00001654 DEBUG(std::cerr << "Looking at Instr: " << *I << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001655 //Get op code and check if its a phi
Tanya Lattnera6457502004-10-14 06:04:28 +00001656 if(I->getOpcode() == V9::PHI) {
1657
1658 DEBUG(std::cerr << "Replacing PHI: " << *I << "\n");
1659 Instruction *tmp = 0;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001660
Tanya Lattnera6457502004-10-14 06:04:28 +00001661 for(unsigned i = 0; i < I->getNumOperands(); ++i) {
1662 //Get Operand
1663 const MachineOperand &mOp = I->getOperand(i);
1664 assert(mOp.getType() == MachineOperand::MO_VirtualRegister && "Should be a Value*\n");
1665
1666 if(!tmp) {
1667 tmp = new TmpInstruction(mOp.getVRegValue());
1668 addToMCFI.push_back(tmp);
1669 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001670
Tanya Lattnera6457502004-10-14 06:04:28 +00001671 //Now for all our arguments we read, OR to the new TmpInstruction that we created
1672 if(mOp.isUse()) {
1673 DEBUG(std::cerr << "Use: " << mOp << "\n");
1674 //Place a copy at the end of its BB but before the branches
1675 assert(newValLocation.count(mOp.getVRegValue()) && "We must know where this value is located\n");
1676 //Reverse iterate to find the branches, we can safely assume no instructions have been
1677 //put in the nop positions
1678 for(MachineBasicBlock::iterator inst = --(newValLocation[mOp.getVRegValue()])->end(), endBB = (newValLocation[mOp.getVRegValue()])->begin(); inst != endBB; --inst) {
1679 MachineOpCode opc = inst->getOpcode();
1680 if(TMI->isBranch(opc) || TMI->isNop(opc))
1681 continue;
1682 else {
1683 BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
1684 break;
1685 }
1686
1687 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001688
Tanya Lattnera6457502004-10-14 06:04:28 +00001689 }
1690 else {
1691 //Remove the phi and replace it with an OR
1692 DEBUG(std::cerr << "Def: " << mOp << "\n");
1693 //newORs.push_back(std::make_pair(tmp, mOp.getVRegValue()));
1694 BuildMI(*kernelBB, I, V9::ORr, 3).addReg(tmp).addImm(0).addRegDef(mOp.getVRegValue());
1695 worklist.push_back(std::make_pair(kernelBB, I));
1696 }
1697
1698 }
1699
1700 }
1701
Tanya Lattnera6457502004-10-14 06:04:28 +00001702
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001703 }
1704
Tanya Lattner80f08552004-11-02 21:04:56 +00001705 //Add TmpInstructions to some MCFI
1706 if(addToMCFI.size() > 0) {
1707 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
1708 for(unsigned x = 0; x < addToMCFI.size(); ++x) {
1709 tempMvec.addTemp(addToMCFI[x]);
1710 }
1711 addToMCFI.clear();
1712 }
1713
Tanya Lattnera6457502004-10-14 06:04:28 +00001714
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001715 //Remove phis from epilogue
1716 for(std::vector<MachineBasicBlock*>::iterator MB = epilogues.begin(), ME = epilogues.end(); MB != ME; ++MB) {
1717 for(MachineBasicBlock::iterator I = (*MB)->begin(), E = (*MB)->end(); I != E; ++I) {
Tanya Lattner80f08552004-11-02 21:04:56 +00001718
1719 DEBUG(std::cerr << "Looking at Instr: " << *I << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001720 //Get op code and check if its a phi
Brian Gaeke418379e2004-08-18 20:04:24 +00001721 if(I->getOpcode() == V9::PHI) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001722 Instruction *tmp = 0;
Tanya Lattnera6457502004-10-14 06:04:28 +00001723
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001724 for(unsigned i = 0; i < I->getNumOperands(); ++i) {
1725 //Get Operand
1726 const MachineOperand &mOp = I->getOperand(i);
1727 assert(mOp.getType() == MachineOperand::MO_VirtualRegister && "Should be a Value*\n");
1728
1729 if(!tmp) {
1730 tmp = new TmpInstruction(mOp.getVRegValue());
Tanya Lattnera6457502004-10-14 06:04:28 +00001731 addToMCFI.push_back(tmp);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001732 }
1733
1734 //Now for all our arguments we read, OR to the new TmpInstruction that we created
1735 if(mOp.isUse()) {
1736 DEBUG(std::cerr << "Use: " << mOp << "\n");
1737 //Place a copy at the end of its BB but before the branches
1738 assert(newValLocation.count(mOp.getVRegValue()) && "We must know where this value is located\n");
1739 //Reverse iterate to find the branches, we can safely assume no instructions have been
1740 //put in the nop positions
1741 for(MachineBasicBlock::iterator inst = --(newValLocation[mOp.getVRegValue()])->end(), endBB = (newValLocation[mOp.getVRegValue()])->begin(); inst != endBB; --inst) {
1742 MachineOpCode opc = inst->getOpcode();
1743 if(TMI->isBranch(opc) || TMI->isNop(opc))
1744 continue;
1745 else {
1746 BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
1747 break;
1748 }
1749
1750 }
Tanya Lattnera6457502004-10-14 06:04:28 +00001751
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001752 }
1753 else {
1754 //Remove the phi and replace it with an OR
1755 DEBUG(std::cerr << "Def: " << mOp << "\n");
1756 BuildMI(**MB, I, V9::ORr, 3).addReg(tmp).addImm(0).addRegDef(mOp.getVRegValue());
1757 worklist.push_back(std::make_pair(*MB,I));
1758 }
1759
1760 }
1761 }
Tanya Lattnera6457502004-10-14 06:04:28 +00001762
Tanya Lattner80f08552004-11-02 21:04:56 +00001763
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001764 }
1765 }
1766
Tanya Lattner80f08552004-11-02 21:04:56 +00001767
1768 if(addToMCFI.size() > 0) {
1769 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
1770 for(unsigned x = 0; x < addToMCFI.size(); ++x) {
1771 tempMvec.addTemp(addToMCFI[x]);
1772 }
1773 addToMCFI.clear();
1774 }
1775
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001776 //Delete the phis
1777 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 +00001778
1779 DEBUG(std::cerr << "Deleting PHI " << *I->second << "\n");
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001780 I->first->erase(I->second);
1781
1782 }
1783
Tanya Lattnera6457502004-10-14 06:04:28 +00001784
1785 assert((addToMCFI.size() == 0) && "We should have added all TmpInstructions to some MachineCodeForInstruction");
Tanya Lattner20890832004-05-28 20:14:12 +00001786}
1787
1788
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001789void ModuloSchedulingPass::reconstructLoop(MachineBasicBlock *BB) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00001790
Tanya Lattner420025b2004-10-10 22:44:35 +00001791 DEBUG(std::cerr << "Reconstructing Loop\n");
1792
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001793 //First find the value *'s that we need to "save"
1794 std::map<const Value*, std::pair<const MSchedGraphNode*, int> > valuesToSave;
Tanya Lattner4cffb582004-05-26 06:27:18 +00001795
Tanya Lattner420025b2004-10-10 22:44:35 +00001796 //Keep track of instructions we have already seen and their stage because
1797 //we don't want to "save" values if they are used in the kernel immediately
1798 std::map<const MachineInstr*, int> lastInstrs;
1799
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001800 //Loop over kernel and only look at instructions from a stage > 0
1801 //Look at its operands and save values *'s that are read
Tanya Lattner4cffb582004-05-26 06:27:18 +00001802 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00001803
Tanya Lattner420025b2004-10-10 22:44:35 +00001804 if(I->second !=0) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00001805 //For this instruction, get the Value*'s that it reads and put them into the set.
1806 //Assert if there is an operand of another type that we need to save
1807 const MachineInstr *inst = I->first->getInst();
Tanya Lattner420025b2004-10-10 22:44:35 +00001808 lastInstrs[inst] = I->second;
1809
Tanya Lattner4cffb582004-05-26 06:27:18 +00001810 for(unsigned i=0; i < inst->getNumOperands(); ++i) {
1811 //get machine operand
1812 const MachineOperand &mOp = inst->getOperand(i);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001813
Tanya Lattner4cffb582004-05-26 06:27:18 +00001814 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse()) {
1815 //find the value in the map
Tanya Lattner420025b2004-10-10 22:44:35 +00001816 if (const Value* srcI = mOp.getVRegValue()) {
1817
Tanya Lattnerced82222004-11-16 21:31:37 +00001818 if(isa<Constant>(srcI) || isa<Argument>(srcI) || isa<PHINode>(srcI))
Tanya Lattner80f08552004-11-02 21:04:56 +00001819 continue;
1820
Tanya Lattner420025b2004-10-10 22:44:35 +00001821 //Before we declare this Value* one that we should save
1822 //make sure its def is not of the same stage as this instruction
1823 //because it will be consumed before its used
1824 Instruction *defInst = (Instruction*) srcI;
1825
1826 //Should we save this value?
1827 bool save = true;
1828
Tanya Lattnerced82222004-11-16 21:31:37 +00001829 //Continue if not in the def map, loop invariant code does not need to be saved
1830 if(!defMap.count(srcI))
1831 continue;
1832
Tanya Lattner80f08552004-11-02 21:04:56 +00001833 MachineInstr *defInstr = defMap[srcI];
1834
Tanya Lattnerced82222004-11-16 21:31:37 +00001835
Tanya Lattner80f08552004-11-02 21:04:56 +00001836 if(lastInstrs.count(defInstr)) {
Tanya Lattnerced82222004-11-16 21:31:37 +00001837 if(lastInstrs[defInstr] == I->second) {
Tanya Lattner80f08552004-11-02 21:04:56 +00001838 save = false;
Tanya Lattnerced82222004-11-16 21:31:37 +00001839
1840 }
Tanya Lattner420025b2004-10-10 22:44:35 +00001841 }
Tanya Lattner80f08552004-11-02 21:04:56 +00001842
Tanya Lattner420025b2004-10-10 22:44:35 +00001843 if(save)
1844 valuesToSave[srcI] = std::make_pair(I->first, i);
1845 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001846 }
1847
1848 if(mOp.getType() != MachineOperand::MO_VirtualRegister && mOp.isUse()) {
1849 assert("Our assumption is wrong. We have another type of register that needs to be saved\n");
1850 }
1851 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00001852 }
1853 }
1854
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001855 //The new loop will consist of one or more prologues, the kernel, and one or more epilogues.
1856
1857 //Map to keep track of old to new values
Tanya Lattner420025b2004-10-10 22:44:35 +00001858 std::map<Value*, std::map<int, Value*> > newValues;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001859
Tanya Lattner420025b2004-10-10 22:44:35 +00001860 //Map to keep track of old to new values in kernel
1861 std::map<Value*, std::map<int, Value*> > kernelPHIs;
1862
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001863 //Another map to keep track of what machine basic blocks these new value*s are in since
1864 //they have no llvm instruction equivalent
1865 std::map<Value*, MachineBasicBlock*> newValLocation;
1866
1867 std::vector<MachineBasicBlock*> prologues;
1868 std::vector<BasicBlock*> llvm_prologues;
1869
1870
1871 //Write prologue
1872 writePrologues(prologues, BB, llvm_prologues, valuesToSave, newValues, newValLocation);
Tanya Lattner420025b2004-10-10 22:44:35 +00001873
1874 //Print out epilogues and prologue
1875 DEBUG(for(std::vector<MachineBasicBlock*>::iterator I = prologues.begin(), E = prologues.end();
1876 I != E; ++I) {
1877 std::cerr << "PROLOGUE\n";
1878 (*I)->print(std::cerr);
1879 });
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001880
1881 BasicBlock *llvmKernelBB = new BasicBlock("Kernel", (Function*) (BB->getBasicBlock()->getParent()));
1882 MachineBasicBlock *machineKernelBB = new MachineBasicBlock(llvmKernelBB);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001883 (((MachineBasicBlock*)BB)->getParent())->getBasicBlockList().push_back(machineKernelBB);
Tanya Lattner420025b2004-10-10 22:44:35 +00001884 writeKernel(llvmKernelBB, machineKernelBB, valuesToSave, newValues, newValLocation, kernelPHIs);
1885
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001886
1887 std::vector<MachineBasicBlock*> epilogues;
1888 std::vector<BasicBlock*> llvm_epilogues;
1889
1890 //Write epilogues
Tanya Lattner420025b2004-10-10 22:44:35 +00001891 writeEpilogues(epilogues, BB, llvm_epilogues, valuesToSave, newValues, newValLocation, kernelPHIs);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001892
1893
1894 const TargetInstrInfo *TMI = target.getInstrInfo();
1895
1896 //Fix up machineBB and llvmBB branches
1897 for(unsigned I = 0; I < prologues.size(); ++I) {
1898
1899 MachineInstr *branch = 0;
Tanya Lattner260652a2004-10-30 00:39:07 +00001900 MachineInstr *branch2 = 0;
1901
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001902 //Find terminator since getFirstTerminator does not work!
1903 for(MachineBasicBlock::reverse_iterator mInst = prologues[I]->rbegin(), mInstEnd = prologues[I]->rend(); mInst != mInstEnd; ++mInst) {
1904 MachineOpCode OC = mInst->getOpcode();
1905 if(TMI->isBranch(OC)) {
Tanya Lattner260652a2004-10-30 00:39:07 +00001906 if(mInst->getOpcode() == V9::BA)
1907 branch2 = &*mInst;
1908 else
1909 branch = &*mInst;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001910 DEBUG(std::cerr << *mInst << "\n");
Tanya Lattner260652a2004-10-30 00:39:07 +00001911 if(branch !=0 && branch2 !=0)
1912 break;
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001913 }
1914 }
1915
Tanya Lattner260652a2004-10-30 00:39:07 +00001916 //Update branch1
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001917 for(unsigned opNum = 0; opNum < branch->getNumOperands(); ++opNum) {
1918 MachineOperand &mOp = branch->getOperand(opNum);
1919 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
Tanya Lattner260652a2004-10-30 00:39:07 +00001920 //Check if we are branching to the kernel, if not branch to epilogue
1921 if(mOp.getVRegValue() == BB->getBasicBlock()) {
1922 if(I == prologues.size()-1)
1923 mOp.setValueReg(llvmKernelBB);
1924 else
1925 mOp.setValueReg(llvm_prologues[I+1]);
1926 }
1927 else
1928 mOp.setValueReg(llvm_epilogues[(llvm_epilogues.size()-1-I)]);
1929 }
1930 }
1931
1932 //Update branch1
1933 for(unsigned opNum = 0; opNum < branch2->getNumOperands(); ++opNum) {
1934 MachineOperand &mOp = branch2->getOperand(opNum);
1935 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
1936 //Check if we are branching to the kernel, if not branch to epilogue
1937 if(mOp.getVRegValue() == BB->getBasicBlock()) {
1938 if(I == prologues.size()-1)
1939 mOp.setValueReg(llvmKernelBB);
1940 else
1941 mOp.setValueReg(llvm_prologues[I+1]);
1942 }
1943 else
1944 mOp.setValueReg(llvm_epilogues[(llvm_epilogues.size()-1-I)]);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001945 }
1946 }
1947
1948 //Update llvm basic block with our new branch instr
1949 DEBUG(std::cerr << BB->getBasicBlock()->getTerminator() << "\n");
1950 const BranchInst *branchVal = dyn_cast<BranchInst>(BB->getBasicBlock()->getTerminator());
Tanya Lattnera6457502004-10-14 06:04:28 +00001951 //TmpInstruction *tmp = new TmpInstruction(branchVal->getCondition());
1952
1953 //Add TmpInstruction to original branches MCFI
1954 //MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(branchVal);
1955 //tempMvec.addTemp((Value*) tmp);
1956
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001957 if(I == prologues.size()-1) {
1958 TerminatorInst *newBranch = new BranchInst(llvmKernelBB,
1959 llvm_epilogues[(llvm_epilogues.size()-1-I)],
Tanya Lattnera6457502004-10-14 06:04:28 +00001960 branchVal->getCondition(),
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001961 llvm_prologues[I]);
1962 }
1963 else
1964 TerminatorInst *newBranch = new BranchInst(llvm_prologues[I+1],
1965 llvm_epilogues[(llvm_epilogues.size()-1-I)],
Tanya Lattnera6457502004-10-14 06:04:28 +00001966 branchVal->getCondition(),
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001967 llvm_prologues[I]);
1968
1969 assert(branch != 0 && "There must be a terminator for this machine basic block!\n");
1970
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001971 }
1972
1973 //Fix up kernel machine branches
1974 MachineInstr *branch = 0;
Tanya Lattnera6457502004-10-14 06:04:28 +00001975 MachineInstr *BAbranch = 0;
1976
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001977 for(MachineBasicBlock::reverse_iterator mInst = machineKernelBB->rbegin(), mInstEnd = machineKernelBB->rend(); mInst != mInstEnd; ++mInst) {
1978 MachineOpCode OC = mInst->getOpcode();
1979 if(TMI->isBranch(OC)) {
Tanya Lattnera6457502004-10-14 06:04:28 +00001980 if(mInst->getOpcode() == V9::BA) {
1981 BAbranch = &*mInst;
1982 }
1983 else {
1984 branch = &*mInst;
1985 break;
1986 }
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00001987 }
1988 }
1989
1990 assert(branch != 0 && "There must be a terminator for the kernel machine basic block!\n");
1991
1992 //Update kernel self loop branch
1993 for(unsigned opNum = 0; opNum < branch->getNumOperands(); ++opNum) {
1994 MachineOperand &mOp = branch->getOperand(opNum);
1995
1996 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
1997 mOp.setValueReg(llvmKernelBB);
1998 }
1999 }
2000
Tanya Lattnera6457502004-10-14 06:04:28 +00002001 Value *origBAVal = 0;
2002
2003 //Update kernel BA branch
2004 for(unsigned opNum = 0; opNum < BAbranch->getNumOperands(); ++opNum) {
2005 MachineOperand &mOp = BAbranch->getOperand(opNum);
2006 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2007 origBAVal = mOp.getVRegValue();
2008 if(llvm_epilogues.size() > 0)
2009 mOp.setValueReg(llvm_epilogues[0]);
2010
2011 }
2012 }
2013
2014 assert((origBAVal != 0) && "Could not find original branch always value");
2015
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002016 //Update kernelLLVM branches
2017 const BranchInst *branchVal = dyn_cast<BranchInst>(BB->getBasicBlock()->getTerminator());
Tanya Lattnera6457502004-10-14 06:04:28 +00002018 //TmpInstruction *tmp = new TmpInstruction(branchVal->getCondition());
2019
2020 //Add TmpInstruction to original branches MCFI
2021 //MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(branchVal);
2022 //tempMvec.addTemp((Value*) tmp);
2023
Tanya Lattner260652a2004-10-30 00:39:07 +00002024 assert(llvm_epilogues.size() != 0 && "We must have epilogues!");
2025
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002026 TerminatorInst *newBranch = new BranchInst(llvmKernelBB,
2027 llvm_epilogues[0],
Tanya Lattnera6457502004-10-14 06:04:28 +00002028 branchVal->getCondition(),
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002029 llvmKernelBB);
2030
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002031
2032 //Lastly add unconditional branches for the epilogues
2033 for(unsigned I = 0; I < epilogues.size(); ++I) {
Tanya Lattner4cffb582004-05-26 06:27:18 +00002034
Tanya Lattnera6457502004-10-14 06:04:28 +00002035 //Now since we don't have fall throughs, add a unconditional branch to the next prologue
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002036 if(I != epilogues.size()-1) {
Tanya Lattner420025b2004-10-10 22:44:35 +00002037 BuildMI(epilogues[I], V9::BA, 1).addPCDisp(llvm_epilogues[I+1]);
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002038 //Add unconditional branch to end of epilogue
2039 TerminatorInst *newBranch = new BranchInst(llvm_epilogues[I+1],
2040 llvm_epilogues[I]);
2041
Tanya Lattner4cffb582004-05-26 06:27:18 +00002042 }
Tanya Lattnera6457502004-10-14 06:04:28 +00002043 else {
2044 BuildMI(epilogues[I], V9::BA, 1).addPCDisp(origBAVal);
2045
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002046
Tanya Lattnera6457502004-10-14 06:04:28 +00002047 //Update last epilogue exit branch
2048 BranchInst *branchVal = (BranchInst*) dyn_cast<BranchInst>(BB->getBasicBlock()->getTerminator());
2049 //Find where we are supposed to branch to
2050 BasicBlock *nextBlock = 0;
2051 for(unsigned j=0; j <branchVal->getNumSuccessors(); ++j) {
2052 if(branchVal->getSuccessor(j) != BB->getBasicBlock())
2053 nextBlock = branchVal->getSuccessor(j);
2054 }
2055
2056 assert((nextBlock != 0) && "Next block should not be null!");
2057 TerminatorInst *newBranch = new BranchInst(nextBlock, llvm_epilogues[I]);
2058 }
2059 //Add one more nop!
2060 BuildMI(epilogues[I], V9::NOP, 0);
2061
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002062 }
Tanya Lattner4cffb582004-05-26 06:27:18 +00002063
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002064 //FIX UP Machine BB entry!!
2065 //We are looking at the predecesor of our loop basic block and we want to change its ba instruction
2066
Tanya Lattner4cffb582004-05-26 06:27:18 +00002067
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002068 //Find all llvm basic blocks that branch to the loop entry and change to our first prologue.
2069 const BasicBlock *llvmBB = BB->getBasicBlock();
2070
Tanya Lattner260652a2004-10-30 00:39:07 +00002071 std::vector<const BasicBlock*>Preds (pred_begin(llvmBB), pred_end(llvmBB));
2072
2073 //for(pred_const_iterator P = pred_begin(llvmBB), PE = pred_end(llvmBB); P != PE; ++PE) {
2074 for(std::vector<const BasicBlock*>::iterator P = Preds.begin(), PE = Preds.end(); P != PE; ++P) {
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002075 if(*P == llvmBB)
2076 continue;
2077 else {
2078 DEBUG(std::cerr << "Found our entry BB\n");
2079 //Get the Terminator instruction for this basic block and print it out
2080 DEBUG(std::cerr << *((*P)->getTerminator()) << "\n");
2081 //Update the terminator
2082 TerminatorInst *term = ((BasicBlock*)*P)->getTerminator();
2083 for(unsigned i=0; i < term->getNumSuccessors(); ++i) {
2084 if(term->getSuccessor(i) == llvmBB) {
2085 DEBUG(std::cerr << "Replacing successor bb\n");
2086 if(llvm_prologues.size() > 0) {
2087 term->setSuccessor(i, llvm_prologues[0]);
2088 //Also update its corresponding machine instruction
2089 MachineCodeForInstruction & tempMvec =
2090 MachineCodeForInstruction::get(term);
2091 for (unsigned j = 0; j < tempMvec.size(); j++) {
2092 MachineInstr *temp = tempMvec[j];
2093 MachineOpCode opc = temp->getOpcode();
2094 if(TMI->isBranch(opc)) {
2095 DEBUG(std::cerr << *temp << "\n");
2096 //Update branch
2097 for(unsigned opNum = 0; opNum < temp->getNumOperands(); ++opNum) {
2098 MachineOperand &mOp = temp->getOperand(opNum);
2099 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2100 mOp.setValueReg(llvm_prologues[0]);
2101 }
2102 }
2103 }
2104 }
2105 }
2106 else {
2107 term->setSuccessor(i, llvmKernelBB);
2108 //Also update its corresponding machine instruction
2109 MachineCodeForInstruction & tempMvec =
2110 MachineCodeForInstruction::get(term);
2111 for (unsigned j = 0; j < tempMvec.size(); j++) {
2112 MachineInstr *temp = tempMvec[j];
2113 MachineOpCode opc = temp->getOpcode();
2114 if(TMI->isBranch(opc)) {
2115 DEBUG(std::cerr << *temp << "\n");
2116 //Update branch
2117 for(unsigned opNum = 0; opNum < temp->getNumOperands(); ++opNum) {
2118 MachineOperand &mOp = temp->getOperand(opNum);
2119 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2120 mOp.setValueReg(llvmKernelBB);
2121 }
2122 }
2123 }
2124 }
2125 }
2126 }
2127 }
2128 break;
2129 }
2130 }
2131
2132 removePHIs(BB, prologues, epilogues, machineKernelBB, newValLocation);
Tanya Lattner4cffb582004-05-26 06:27:18 +00002133
2134
Tanya Lattner0a88d2d2004-07-30 23:36:10 +00002135
2136 //Print out epilogues and prologue
2137 DEBUG(for(std::vector<MachineBasicBlock*>::iterator I = prologues.begin(), E = prologues.end();
2138 I != E; ++I) {
2139 std::cerr << "PROLOGUE\n";
2140 (*I)->print(std::cerr);
2141 });
2142
2143 DEBUG(std::cerr << "KERNEL\n");
2144 DEBUG(machineKernelBB->print(std::cerr));
2145
2146 DEBUG(for(std::vector<MachineBasicBlock*>::iterator I = epilogues.begin(), E = epilogues.end();
2147 I != E; ++I) {
2148 std::cerr << "EPILOGUE\n";
2149 (*I)->print(std::cerr);
2150 });
2151
2152
2153 DEBUG(std::cerr << "New Machine Function" << "\n");
2154 DEBUG(std::cerr << BB->getParent() << "\n");
2155
Tanya Lattner420025b2004-10-10 22:44:35 +00002156 //BB->getParent()->getBasicBlockList().erase(BB);
Tanya Lattner4cffb582004-05-26 06:27:18 +00002157
2158}
2159