blob: 4e57c65aae1098ace8342d95029017362317af34 [file] [log] [blame]
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001//===-- ModuloScheduling.cpp - ModuloScheduling ----------------*- C++ -*-===//
2//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Misha Brukmanb4402432005-04-21 23:30:14 +00009//
10// This ModuloScheduling pass is based on the Swing Modulo Scheduling
11// algorithm.
12//
Guochun Shi45d8f322003-03-27 17:57:44 +000013//===----------------------------------------------------------------------===//
14
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +000015#define DEBUG_TYPE "ModuloSched"
16
17#include "ModuloScheduling.h"
Tanya Lattner13417b52005-03-23 01:47:20 +000018#include "llvm/Constants.h"
Tanya Lattner081fbd12004-07-30 23:36:10 +000019#include "llvm/Instructions.h"
20#include "llvm/Function.h"
Tanya Lattnerdd10fbe2004-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 Spencer7c16caa2004-09-01 22:55:40 +000025#include "llvm/Support/Debug.h"
26#include "llvm/Support/GraphWriter.h"
Tanya Lattner56807c62005-02-10 17:02:58 +000027#include "llvm/ADT/SCCIterator.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000028#include "llvm/ADT/StringExtras.h"
Tanya Lattnerab9cf272004-11-22 20:41:24 +000029#include "llvm/ADT/Statistic.h"
Tanya Lattner56807c62005-02-10 17:02:58 +000030#include "llvm/Support/Timer.h"
Misha Brukman84817852004-08-02 13:59:10 +000031#include <cmath>
Alkis Evlogimenos20f1b0b2004-09-28 14:42:44 +000032#include <algorithm>
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +000033#include <fstream>
34#include <sstream>
Misha Brukman84817852004-08-02 13:59:10 +000035#include <utility>
36#include <vector>
Misha Brukman9da1134b2004-10-10 23:34:50 +000037#include "../MachineCodeForInstruction.h"
38#include "../SparcV9TmpInstr.h"
39#include "../SparcV9Internals.h"
40#include "../SparcV9RegisterInfo.h"
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +000041using namespace llvm;
42
43/// Create ModuloSchedulingPass
44///
45FunctionPass *llvm::createModuloSchedulingPass(TargetMachine & targ) {
46 DEBUG(std::cerr << "Created ModuloSchedulingPass\n");
Misha Brukmanb4402432005-04-21 23:30:14 +000047 return new ModuloSchedulingPass(targ);
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +000048}
49
Tanya Lattner081fbd12004-07-30 23:36:10 +000050
51//Graph Traits for printing out the dependence graph
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +000052template<typename GraphType>
53static void WriteGraphToFile(std::ostream &O, const std::string &GraphName,
54 const GraphType &GT) {
55 std::string Filename = GraphName + ".dot";
56 O << "Writing '" << Filename << "'...";
57 std::ofstream F(Filename.c_str());
Misha Brukmanb4402432005-04-21 23:30:14 +000058
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +000059 if (F.good())
60 WriteGraph(F, GT);
61 else
62 O << " error opening file for writing!";
63 O << "\n";
64};
Guochun Shi45d8f322003-03-27 17:57:44 +000065
Tanya Lattner56807c62005-02-10 17:02:58 +000066
67#if 1
68#define TIME_REGION(VARNAME, DESC) \
69 NamedRegionTimer VARNAME(DESC)
70#else
71#define TIME_REGION(VARNAME, DESC)
72#endif
73
74
Tanya Lattner081fbd12004-07-30 23:36:10 +000075//Graph Traits for printing out the dependence graph
Brian Gaeke960707c2003-11-11 22:41:34 +000076namespace llvm {
Tanya Lattner42ed1482005-04-22 06:32:48 +000077
78 //Loop statistics
Tanya Lattnerab9cf272004-11-22 20:41:24 +000079 Statistic<> ValidLoops("modulosched-validLoops", "Number of candidate loops modulo-scheduled");
Tanya Lattner42ed1482005-04-22 06:32:48 +000080 Statistic<> JumboBB("modulosched-jumboBB", "Basic Blocks with more then 100 instructions");
81 Statistic<> LoopsWithCalls("modulosched-loopCalls", "Loops with calls");
82 Statistic<> LoopsWithCondMov("modulosched-loopCondMov", "Loops with conditional moves");
83 Statistic<> InvalidLoops("modulosched-invalidLoops", "Loops with unknown trip counts or loop invariant trip counts");
Tanya Lattner56807c62005-02-10 17:02:58 +000084 Statistic<> SingleBBLoops("modulosched-singeBBLoops", "Number of single basic block loops");
Tanya Lattner42ed1482005-04-22 06:32:48 +000085
86 //Scheduling Statistics
87 Statistic<> MSLoops("modulosched-schedLoops", "Number of loops successfully modulo-scheduled");
Tanya Lattnerc28fd0d2005-02-16 04:00:59 +000088 Statistic<> NoSched("modulosched-noSched", "No schedule");
89 Statistic<> SameStage("modulosched-sameStage", "Max stage is 0");
Tanya Lattner42ed1482005-04-22 06:32:48 +000090 Statistic<> ResourceConstraint("modulosched-resourceConstraint", "Loops constrained by resources");
91 Statistic<> RecurrenceConstraint("modulosched-recurrenceConstraint", "Loops constrained by recurrences");
92 Statistic<> FinalIISum("modulosched-finalIISum", "Sum of all final II");
93 Statistic<> IISum("modulosched-IISum", "Sum of all theoretical II");
Brian Gaeke960707c2003-11-11 22:41:34 +000094
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +000095 template<>
96 struct DOTGraphTraits<MSchedGraph*> : public DefaultDOTGraphTraits {
97 static std::string getGraphName(MSchedGraph *F) {
98 return "Dependence Graph";
99 }
Misha Brukmanb4402432005-04-21 23:30:14 +0000100
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000101 static std::string getNodeLabel(MSchedGraphNode *Node, MSchedGraph *Graph) {
102 if (Node->getInst()) {
103 std::stringstream ss;
104 ss << *(Node->getInst());
105 return ss.str(); //((MachineInstr*)Node->getInst());
106 }
107 else
108 return "No Inst";
109 }
110 static std::string getEdgeSourceLabel(MSchedGraphNode *Node,
111 MSchedGraphNode::succ_iterator I) {
112 //Label each edge with the type of dependence
113 std::string edgelabel = "";
114 switch (I.getEdge().getDepOrderType()) {
115
Misha Brukmanb4402432005-04-21 23:30:14 +0000116 case MSchedGraphEdge::TrueDep:
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000117 edgelabel = "True";
118 break;
Misha Brukmanb4402432005-04-21 23:30:14 +0000119
120 case MSchedGraphEdge::AntiDep:
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000121 edgelabel = "Anti";
122 break;
123
Misha Brukmanb4402432005-04-21 23:30:14 +0000124 case MSchedGraphEdge::OutputDep:
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000125 edgelabel = "Output";
126 break;
127
128 default:
129 edgelabel = "Unknown";
130 break;
131 }
Tanya Lattnera6820d62004-05-08 16:12:10 +0000132
133 //FIXME
134 int iteDiff = I.getEdge().getIteDiff();
135 std::string intStr = "(IteDiff: ";
136 intStr += itostr(iteDiff);
137
138 intStr += ")";
139 edgelabel += intStr;
140
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000141 return edgelabel;
Tanya Lattnera6820d62004-05-08 16:12:10 +0000142 }
Guochun Shi45d8f322003-03-27 17:57:44 +0000143 };
Guochun Shi45d8f322003-03-27 17:57:44 +0000144}
Tanya Lattner7efb18f2003-08-28 17:12:14 +0000145
Tanya Lattner13417b52005-03-23 01:47:20 +0000146
147#include <unistd.h>
148
Misha Brukman80f283b2003-10-10 17:41:32 +0000149/// ModuloScheduling::runOnFunction - main transformation entry point
Tanya Lattner081fbd12004-07-30 23:36:10 +0000150/// The Swing Modulo Schedule algorithm has three basic steps:
151/// 1) Computation and Analysis of the dependence graph
152/// 2) Ordering of the nodes
153/// 3) Scheduling
Misha Brukmanb4402432005-04-21 23:30:14 +0000154///
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000155bool ModuloSchedulingPass::runOnFunction(Function &F) {
Tanya Lattner42ed1482005-04-22 06:32:48 +0000156 alarm(100);
Tanya Lattner13417b52005-03-23 01:47:20 +0000157
Tanya Lattner7efb18f2003-08-28 17:12:14 +0000158 bool Changed = false;
Tanya Lattner7beb51c2004-11-16 21:31:37 +0000159 int numMS = 0;
Misha Brukmanb4402432005-04-21 23:30:14 +0000160
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +0000161 DEBUG(std::cerr << "Creating ModuloSchedGraph for each valid BasicBlock in " + F.getName() + "\n");
Misha Brukmanb4402432005-04-21 23:30:14 +0000162
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000163 //Get MachineFunction
164 MachineFunction &MF = MachineFunction::get(&F);
Misha Brukmanb4402432005-04-21 23:30:14 +0000165
Tanya Lattner91964492005-03-29 20:35:10 +0000166 DependenceAnalyzer &DA = getAnalysis<DependenceAnalyzer>();
Misha Brukmanb4402432005-04-21 23:30:14 +0000167
Tanya Lattner13417b52005-03-23 01:47:20 +0000168
Tanya Lattner081fbd12004-07-30 23:36:10 +0000169 //Worklist
170 std::vector<MachineBasicBlock*> Worklist;
Misha Brukmanb4402432005-04-21 23:30:14 +0000171
Tanya Lattner081fbd12004-07-30 23:36:10 +0000172 //Iterate over BasicBlocks and put them into our worklist if they are valid
173 for (MachineFunction::iterator BI = MF.begin(); BI != MF.end(); ++BI)
Tanya Lattner42ed1482005-04-22 06:32:48 +0000174 if(MachineBBisValid(BI)) {
175 if(BI->size() < 100) {
176 Worklist.push_back(&*BI);
177 ++ValidLoops;
178 }
179 else
180 ++JumboBB;
181 std::cerr << "BB Size: " << BI->size() << "\n";
Tanya Lattnerab9cf272004-11-22 20:41:24 +0000182 }
Misha Brukmanb4402432005-04-21 23:30:14 +0000183
Tanya Lattner444be612004-11-02 21:04:56 +0000184 defaultInst = 0;
185
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +0000186 DEBUG(if(Worklist.size() == 0) std::cerr << "No single basic block loops in function to ModuloSchedule\n");
Tanya Lattnera6820d62004-05-08 16:12:10 +0000187
Tanya Lattner081fbd12004-07-30 23:36:10 +0000188 //Iterate over the worklist and perform scheduling
Misha Brukmanb4402432005-04-21 23:30:14 +0000189 for(std::vector<MachineBasicBlock*>::iterator BI = Worklist.begin(),
Tanya Lattner081fbd12004-07-30 23:36:10 +0000190 BE = Worklist.end(); BI != BE; ++BI) {
Tanya Lattner56807c62005-02-10 17:02:58 +0000191
192 //Print out BB for debugging
Tanya Lattner42ed1482005-04-22 06:32:48 +0000193 DEBUG(std::cerr << "BB Size: " << (*BI)->size() << "\n");
Tanya Lattner56807c62005-02-10 17:02:58 +0000194 DEBUG(std::cerr << "ModuloScheduling BB: \n"; (*BI)->print(std::cerr));
195
Tanya Lattner13417b52005-03-23 01:47:20 +0000196 //Print out LLVM BB
197 DEBUG(std::cerr << "ModuloScheduling LLVMBB: \n"; (*BI)->getBasicBlock()->print(std::cerr));
198
Tanya Lattner56807c62005-02-10 17:02:58 +0000199 //Catch the odd case where we only have TmpInstructions and no real Value*s
200 if(!CreateDefMap(*BI)) {
201 //Clear out our maps for the next basic block that is processed
202 nodeToAttributesMap.clear();
203 partialOrder.clear();
204 recurrenceList.clear();
205 FinalNodeOrder.clear();
206 schedule.clear();
207 defMap.clear();
208 continue;
209 }
Tanya Lattner7beb51c2004-11-16 21:31:37 +0000210
Tanya Lattner8d64e9a2005-04-05 16:36:44 +0000211 MSchedGraph *MSG = new MSchedGraph(*BI, target, indVarInstrs[*BI], DA, machineTollvm[*BI]);
Misha Brukmanb4402432005-04-21 23:30:14 +0000212
Tanya Lattner081fbd12004-07-30 23:36:10 +0000213 //Write Graph out to file
214 DEBUG(WriteGraphToFile(std::cerr, F.getName(), MSG));
Tanya Lattner42ed1482005-04-22 06:32:48 +0000215 DEBUG(MSG->print(std::cerr));
Misha Brukmanb4402432005-04-21 23:30:14 +0000216
Tanya Lattner081fbd12004-07-30 23:36:10 +0000217 //Calculate Resource II
218 int ResMII = calculateResMII(*BI);
Misha Brukmanb4402432005-04-21 23:30:14 +0000219
Tanya Lattner081fbd12004-07-30 23:36:10 +0000220 //Calculate Recurrence II
221 int RecMII = calculateRecMII(MSG, ResMII);
Tanya Lattner56807c62005-02-10 17:02:58 +0000222
223 DEBUG(std::cerr << "Number of reccurrences found: " << recurrenceList.size() << "\n");
Misha Brukmanb4402432005-04-21 23:30:14 +0000224
Tanya Lattner081fbd12004-07-30 23:36:10 +0000225 //Our starting initiation interval is the maximum of RecMII and ResMII
Tanya Lattner42ed1482005-04-22 06:32:48 +0000226 if(RecMII < ResMII)
227 ++RecurrenceConstraint;
228 else
229 ++ResourceConstraint;
230
Tanya Lattner56807c62005-02-10 17:02:58 +0000231 II = std::max(RecMII, ResMII);
Tanya Lattner42ed1482005-04-22 06:32:48 +0000232 int mII = II;
233 IISum += mII;
Misha Brukmanb4402432005-04-21 23:30:14 +0000234
Tanya Lattner081fbd12004-07-30 23:36:10 +0000235 //Print out II, RecMII, and ResMII
Tanya Lattnerddebd1e2004-10-30 00:39:07 +0000236 DEBUG(std::cerr << "II starts out as " << II << " ( RecMII=" << RecMII << " and ResMII=" << ResMII << ")\n");
Misha Brukmanb4402432005-04-21 23:30:14 +0000237
Tanya Lattnerddebd1e2004-10-30 00:39:07 +0000238 //Dump node properties if in debug mode
Misha Brukmanb4402432005-04-21 23:30:14 +0000239 DEBUG(for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(),
Tanya Lattnerddebd1e2004-10-30 00:39:07 +0000240 E = nodeToAttributesMap.end(); I !=E; ++I) {
Misha Brukmanb4402432005-04-21 23:30:14 +0000241 std::cerr << "Node: " << *(I->first) << " ASAP: " << I->second.ASAP << " ALAP: "
242 << I->second.ALAP << " MOB: " << I->second.MOB << " Depth: " << I->second.depth
Tanya Lattner56807c62005-02-10 17:02:58 +0000243 << " Height: " << I->second.height << "\n";
244 });
Tanya Lattnerddebd1e2004-10-30 00:39:07 +0000245
Tanya Lattner081fbd12004-07-30 23:36:10 +0000246 //Calculate Node Properties
247 calculateNodeAttributes(MSG, ResMII);
Misha Brukmanb4402432005-04-21 23:30:14 +0000248
Tanya Lattner081fbd12004-07-30 23:36:10 +0000249 //Dump node properties if in debug mode
Misha Brukmanb4402432005-04-21 23:30:14 +0000250 DEBUG(for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(),
Tanya Lattner081fbd12004-07-30 23:36:10 +0000251 E = nodeToAttributesMap.end(); I !=E; ++I) {
Misha Brukmanb4402432005-04-21 23:30:14 +0000252 std::cerr << "Node: " << *(I->first) << " ASAP: " << I->second.ASAP << " ALAP: "
253 << I->second.ALAP << " MOB: " << I->second.MOB << " Depth: " << I->second.depth
Tanya Lattner56807c62005-02-10 17:02:58 +0000254 << " Height: " << I->second.height << "\n";
255 });
Misha Brukmanb4402432005-04-21 23:30:14 +0000256
Tanya Lattner081fbd12004-07-30 23:36:10 +0000257 //Put nodes in order to schedule them
258 computePartialOrder();
Misha Brukmanb4402432005-04-21 23:30:14 +0000259
Tanya Lattner081fbd12004-07-30 23:36:10 +0000260 //Dump out partial order
Misha Brukmanb4402432005-04-21 23:30:14 +0000261 DEBUG(for(std::vector<std::set<MSchedGraphNode*> >::iterator I = partialOrder.begin(),
Tanya Lattner081fbd12004-07-30 23:36:10 +0000262 E = partialOrder.end(); I !=E; ++I) {
Tanya Lattner56807c62005-02-10 17:02:58 +0000263 std::cerr << "Start set in PO\n";
264 for(std::set<MSchedGraphNode*>::iterator J = I->begin(), JE = I->end(); J != JE; ++J)
265 std::cerr << "PO:" << **J << "\n";
266 });
Misha Brukmanb4402432005-04-21 23:30:14 +0000267
Tanya Lattner081fbd12004-07-30 23:36:10 +0000268 //Place nodes in final order
269 orderNodes();
Misha Brukmanb4402432005-04-21 23:30:14 +0000270
Tanya Lattner081fbd12004-07-30 23:36:10 +0000271 //Dump out order of nodes
272 DEBUG(for(std::vector<MSchedGraphNode*>::iterator I = FinalNodeOrder.begin(), E = FinalNodeOrder.end(); I != E; ++I) {
Tanya Lattner56807c62005-02-10 17:02:58 +0000273 std::cerr << "FO:" << **I << "\n";
274 });
Misha Brukmanb4402432005-04-21 23:30:14 +0000275
Tanya Lattner081fbd12004-07-30 23:36:10 +0000276 //Finally schedule nodes
Tanya Lattner42ed1482005-04-22 06:32:48 +0000277 bool haveSched = computeSchedule(*BI, MSG);
Misha Brukmanb4402432005-04-21 23:30:14 +0000278
Tanya Lattner081fbd12004-07-30 23:36:10 +0000279 //Print out final schedule
280 DEBUG(schedule.print(std::cerr));
Misha Brukmanb4402432005-04-21 23:30:14 +0000281
Tanya Lattnerddebd1e2004-10-30 00:39:07 +0000282 //Final scheduling step is to reconstruct the loop only if we actual have
283 //stage > 0
Tanya Lattner8d64e9a2005-04-05 16:36:44 +0000284 if(haveSched) {
Tanya Lattnerddebd1e2004-10-30 00:39:07 +0000285 reconstructLoop(*BI);
Tanya Lattnerab9cf272004-11-22 20:41:24 +0000286 ++MSLoops;
Tanya Lattner7beb51c2004-11-16 21:31:37 +0000287 Changed = true;
Tanya Lattner8d64e9a2005-04-05 16:36:44 +0000288
289 if(schedule.getMaxStage() == 0)
Tanya Lattnerc28fd0d2005-02-16 04:00:59 +0000290 ++SameStage;
Tanya Lattnerc28fd0d2005-02-16 04:00:59 +0000291 }
Tanya Lattner8d64e9a2005-04-05 16:36:44 +0000292 else
293 ++NoSched;
Misha Brukmanb4402432005-04-21 23:30:14 +0000294
Tanya Lattner081fbd12004-07-30 23:36:10 +0000295 //Clear out our maps for the next basic block that is processed
296 nodeToAttributesMap.clear();
297 partialOrder.clear();
298 recurrenceList.clear();
299 FinalNodeOrder.clear();
300 schedule.clear();
Tanya Lattner7beb51c2004-11-16 21:31:37 +0000301 defMap.clear();
Tanya Lattner081fbd12004-07-30 23:36:10 +0000302 //Clean up. Nuke old MachineBB and llvmBB
303 //BasicBlock *llvmBB = (BasicBlock*) (*BI)->getBasicBlock();
304 //Function *parent = (Function*) llvmBB->getParent();
305 //Should't std::find work??
306 //parent->getBasicBlockList().erase(std::find(parent->getBasicBlockList().begin(), parent->getBasicBlockList().end(), *llvmBB));
307 //parent->getBasicBlockList().erase(llvmBB);
Misha Brukmanb4402432005-04-21 23:30:14 +0000308
Tanya Lattner081fbd12004-07-30 23:36:10 +0000309 //delete(llvmBB);
310 //delete(*BI);
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000311 }
Tanya Lattner13417b52005-03-23 01:47:20 +0000312
Misha Brukmanb4402432005-04-21 23:30:14 +0000313 alarm(0);
Tanya Lattner7efb18f2003-08-28 17:12:14 +0000314 return Changed;
315}
Brian Gaeke960707c2003-11-11 22:41:34 +0000316
Tanya Lattner56807c62005-02-10 17:02:58 +0000317bool ModuloSchedulingPass::CreateDefMap(MachineBasicBlock *BI) {
Tanya Lattner7beb51c2004-11-16 21:31:37 +0000318 defaultInst = 0;
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000319
Tanya Lattner7beb51c2004-11-16 21:31:37 +0000320 for(MachineBasicBlock::iterator I = BI->begin(), E = BI->end(); I != E; ++I) {
321 for(unsigned opNum = 0; opNum < I->getNumOperands(); ++opNum) {
322 const MachineOperand &mOp = I->getOperand(opNum);
323 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef()) {
Tanya Lattnerab9cf272004-11-22 20:41:24 +0000324 //assert if this is the second def we have seen
Misha Brukmanb4402432005-04-21 23:30:14 +0000325 //DEBUG(std::cerr << "Putting " << *(mOp.getVRegValue()) << " into map\n");
Tanya Lattnerab9cf272004-11-22 20:41:24 +0000326 assert(!defMap.count(mOp.getVRegValue()) && "Def already in the map");
327
Tanya Lattner7beb51c2004-11-16 21:31:37 +0000328 defMap[mOp.getVRegValue()] = &*I;
329 }
Misha Brukmanb4402432005-04-21 23:30:14 +0000330
Tanya Lattner7beb51c2004-11-16 21:31:37 +0000331 //See if we can use this Value* as our defaultInst
332 if(!defaultInst && mOp.getType() == MachineOperand::MO_VirtualRegister) {
333 Value *V = mOp.getVRegValue();
334 if(!isa<TmpInstruction>(V) && !isa<Argument>(V) && !isa<Constant>(V) && !isa<PHINode>(V))
335 defaultInst = (Instruction*) V;
336 }
337 }
338 }
Misha Brukmanb4402432005-04-21 23:30:14 +0000339
Tanya Lattner56807c62005-02-10 17:02:58 +0000340 if(!defaultInst)
341 return false;
Misha Brukmanb4402432005-04-21 23:30:14 +0000342
Tanya Lattner56807c62005-02-10 17:02:58 +0000343 return true;
Misha Brukmanb4402432005-04-21 23:30:14 +0000344
Tanya Lattner7beb51c2004-11-16 21:31:37 +0000345}
Tanya Lattner081fbd12004-07-30 23:36:10 +0000346/// This function checks if a Machine Basic Block is valid for modulo
347/// scheduling. This means that it has no control flow (if/else or
348/// calls) in the block. Currently ModuloScheduling only works on
349/// single basic block loops.
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000350bool ModuloSchedulingPass::MachineBBisValid(const MachineBasicBlock *BI) {
351
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000352 bool isLoop = false;
Misha Brukmanb4402432005-04-21 23:30:14 +0000353
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000354 //Check first if its a valid loop
Misha Brukmanb4402432005-04-21 23:30:14 +0000355 for(succ_const_iterator I = succ_begin(BI->getBasicBlock()),
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000356 E = succ_end(BI->getBasicBlock()); I != E; ++I) {
357 if (*I == BI->getBasicBlock()) // has single block loop
358 isLoop = true;
359 }
Misha Brukmanb4402432005-04-21 23:30:14 +0000360
Tanya Lattner081fbd12004-07-30 23:36:10 +0000361 if(!isLoop)
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000362 return false;
Tanya Lattner201e9722004-12-02 07:22:15 +0000363
364 //Check that we have a conditional branch (avoiding MS infinite loops)
365 if(BranchInst *b = dyn_cast<BranchInst>(((BasicBlock*) BI->getBasicBlock())->getTerminator()))
366 if(b->isUnconditional())
367 return false;
368
Tanya Lattnerab9cf272004-11-22 20:41:24 +0000369 //Check size of our basic block.. make sure we have more then just the terminator in it
370 if(BI->getBasicBlock()->size() == 1)
371 return false;
372
Tanya Lattner56807c62005-02-10 17:02:58 +0000373 //Increase number of single basic block loops for stats
374 ++SingleBBLoops;
375
Tanya Lattner081fbd12004-07-30 23:36:10 +0000376 //Get Target machine instruction info
377 const TargetInstrInfo *TMI = target.getInstrInfo();
Misha Brukmanb4402432005-04-21 23:30:14 +0000378
Tanya Lattner13417b52005-03-23 01:47:20 +0000379 //Check each instruction and look for calls, keep map to get index later
380 std::map<const MachineInstr*, unsigned> indexMap;
381
382 unsigned count = 0;
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000383 for(MachineBasicBlock::const_iterator I = BI->begin(), E = BI->end(); I != E; ++I) {
Tanya Lattner081fbd12004-07-30 23:36:10 +0000384 //Get opcode to check instruction type
385 MachineOpCode OC = I->getOpcode();
Misha Brukmanb4402432005-04-21 23:30:14 +0000386
Tanya Lattner91964492005-03-29 20:35:10 +0000387 //Look for calls
Tanya Lattner42ed1482005-04-22 06:32:48 +0000388 if(TMI->isCall(OC)) {
389 ++LoopsWithCalls;
Tanya Lattner081fbd12004-07-30 23:36:10 +0000390 return false;
Tanya Lattner42ed1482005-04-22 06:32:48 +0000391 }
392
Tanya Lattner56807c62005-02-10 17:02:58 +0000393 //Look for conditional move
Misha Brukmanb4402432005-04-21 23:30:14 +0000394 if(OC == V9::MOVRZr || OC == V9::MOVRZi || OC == V9::MOVRLEZr || OC == V9::MOVRLEZi
Tanya Lattner56807c62005-02-10 17:02:58 +0000395 || OC == V9::MOVRLZr || OC == V9::MOVRLZi || OC == V9::MOVRNZr || OC == V9::MOVRNZi
Misha Brukmanb4402432005-04-21 23:30:14 +0000396 || OC == V9::MOVRGZr || OC == V9::MOVRGZi || OC == V9::MOVRGEZr
Tanya Lattner56807c62005-02-10 17:02:58 +0000397 || OC == V9::MOVRGEZi || OC == V9::MOVLEr || OC == V9::MOVLEi || OC == V9::MOVLEUr
398 || OC == V9::MOVLEUi || OC == V9::MOVFLEr || OC == V9::MOVFLEi
399 || OC == V9::MOVNEr || OC == V9::MOVNEi || OC == V9::MOVNEGr || OC == V9::MOVNEGi
Tanya Lattner42ed1482005-04-22 06:32:48 +0000400 || OC == V9::MOVFNEr || OC == V9::MOVFNEi) {
401 ++LoopsWithCondMov;
Tanya Lattner56807c62005-02-10 17:02:58 +0000402 return false;
Tanya Lattner42ed1482005-04-22 06:32:48 +0000403 }
Misha Brukmanb4402432005-04-21 23:30:14 +0000404
Tanya Lattner13417b52005-03-23 01:47:20 +0000405 indexMap[I] = count;
406
407 if(TMI->isNop(OC))
408 continue;
409
410 ++count;
Tanya Lattner081fbd12004-07-30 23:36:10 +0000411 }
Tanya Lattner13417b52005-03-23 01:47:20 +0000412
413 //Apply a simple pattern match to make sure this loop can be modulo scheduled
414 //This means only loops with a branch associated to the iteration count
415
416 //Get the branch
417 BranchInst *b = dyn_cast<BranchInst>(((BasicBlock*) BI->getBasicBlock())->getTerminator());
418
419 //Get the condition for the branch (we already checked if it was conditional)
420 Value *cond = b->getCondition();
421
422 DEBUG(std::cerr << "Condition: " << *cond << "\n");
423
424 //List of instructions associated with induction variable
425 std::set<Instruction*> indVar;
426 std::vector<Instruction*> stack;
427
428 BasicBlock *BB = (BasicBlock*) BI->getBasicBlock();
429
430 //Add branch
431 indVar.insert(b);
432
433 if(Instruction *I = dyn_cast<Instruction>(cond))
434 if(I->getParent() == BB) {
Tanya Lattner42ed1482005-04-22 06:32:48 +0000435 if (!assocIndVar(I, indVar, stack, BB)) {
436 ++InvalidLoops;
Tanya Lattner13417b52005-03-23 01:47:20 +0000437 return false;
Tanya Lattner42ed1482005-04-22 06:32:48 +0000438 }
Tanya Lattner13417b52005-03-23 01:47:20 +0000439 }
Tanya Lattner42ed1482005-04-22 06:32:48 +0000440 else {
441 ++InvalidLoops;
Tanya Lattner13417b52005-03-23 01:47:20 +0000442 return false;
Tanya Lattner42ed1482005-04-22 06:32:48 +0000443 }
444 else {
445 ++InvalidLoops;
Tanya Lattner13417b52005-03-23 01:47:20 +0000446 return false;
Tanya Lattner42ed1482005-04-22 06:32:48 +0000447 }
Tanya Lattner13417b52005-03-23 01:47:20 +0000448 //The indVar set must be >= 3 instructions for this loop to match (FIX ME!)
449 if(indVar.size() < 3 )
450 return false;
451
452 //Dump out instructions associate with indvar for debug reasons
453 DEBUG(for(std::set<Instruction*>::iterator N = indVar.begin(), NE = indVar.end(); N != NE; ++N) {
454 std::cerr << **N << "\n";
455 });
456
Tanya Lattner91964492005-03-29 20:35:10 +0000457 //Create map of machine instr to llvm instr
458 std::map<MachineInstr*, Instruction*> mllvm;
459 for(BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
460 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(I);
461 for (unsigned j = 0; j < tempMvec.size(); j++) {
462 mllvm[tempMvec[j]] = I;
463 }
464 }
465
Tanya Lattner13417b52005-03-23 01:47:20 +0000466 //Convert list of LLVM Instructions to list of Machine instructions
467 std::map<const MachineInstr*, unsigned> mIndVar;
468 for(std::set<Instruction*>::iterator N = indVar.begin(), NE = indVar.end(); N != NE; ++N) {
Misha Brukmanb4402432005-04-21 23:30:14 +0000469
Tanya Lattner8d64e9a2005-04-05 16:36:44 +0000470 //If we have a load, we can't handle this loop because there is no way to preserve dependences
471 //between loads and stores
472 if(isa<LoadInst>(*N))
473 return false;
474
Tanya Lattner13417b52005-03-23 01:47:20 +0000475 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(*N);
476 for (unsigned j = 0; j < tempMvec.size(); j++) {
477 MachineOpCode OC = (tempMvec[j])->getOpcode();
478 if(TMI->isNop(OC))
479 continue;
480 if(!indexMap.count(tempMvec[j]))
481 continue;
482 mIndVar[(MachineInstr*) tempMvec[j]] = indexMap[(MachineInstr*) tempMvec[j]];
483 DEBUG(std::cerr << *(tempMvec[j]) << " at index " << indexMap[(MachineInstr*) tempMvec[j]] << "\n");
484 }
485 }
486
Tanya Lattner8d64e9a2005-04-05 16:36:44 +0000487 //Must have some guts to the loop body (more then 1 instr, dont count nops in size)
488 if(mIndVar.size() >= (BI->size()-3))
Tanya Lattner13417b52005-03-23 01:47:20 +0000489 return false;
490
491 //Put into a map for future access
492 indVarInstrs[BI] = mIndVar;
Tanya Lattner91964492005-03-29 20:35:10 +0000493 machineTollvm[BI] = mllvm;
Tanya Lattner13417b52005-03-23 01:47:20 +0000494 return true;
495}
496
Misha Brukmanb4402432005-04-21 23:30:14 +0000497bool ModuloSchedulingPass::assocIndVar(Instruction *I, std::set<Instruction*> &indVar,
Tanya Lattner13417b52005-03-23 01:47:20 +0000498 std::vector<Instruction*> &stack, BasicBlock *BB) {
499
500 stack.push_back(I);
501
502 //If this is a phi node, check if its the canonical indvar
503 if(PHINode *PN = dyn_cast<PHINode>(I)) {
504 if (Instruction *Inc =
505 dyn_cast<Instruction>(PN->getIncomingValueForBlock(BB)))
506 if (Inc->getOpcode() == Instruction::Add && Inc->getOperand(0) == PN)
507 if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
508 if (CI->equalsInt(1)) {
509 //We have found the indvar, so add the stack, and inc instruction to the set
510 indVar.insert(stack.begin(), stack.end());
511 indVar.insert(Inc);
512 stack.pop_back();
513 return true;
514 }
515 return false;
516 }
517 else {
518 //Loop over each of the instructions operands, check if they are an instruction and in this BB
519 for(unsigned i = 0; i < I->getNumOperands(); ++i) {
520 if(Instruction *N = dyn_cast<Instruction>(I->getOperand(i))) {
521 if(N->getParent() == BB)
522 if(!assocIndVar(N, indVar, stack, BB))
523 return false;
524 }
525 }
526 }
527
528 stack.pop_back();
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000529 return true;
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000530}
531
532//ResMII is calculated by determining the usage count for each resource
533//and using the maximum.
534//FIXME: In future there should be a way to get alternative resources
535//for each instruction
536int ModuloSchedulingPass::calculateResMII(const MachineBasicBlock *BI) {
Misha Brukmanb4402432005-04-21 23:30:14 +0000537
Tanya Lattner56807c62005-02-10 17:02:58 +0000538 TIME_REGION(X, "calculateResMII");
539
Tanya Lattner081fbd12004-07-30 23:36:10 +0000540 const TargetInstrInfo *mii = target.getInstrInfo();
541 const TargetSchedInfo *msi = target.getSchedInfo();
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000542
543 int ResMII = 0;
Misha Brukmanb4402432005-04-21 23:30:14 +0000544
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000545 //Map to keep track of usage count of each resource
546 std::map<unsigned, unsigned> resourceUsageCount;
547
548 for(MachineBasicBlock::const_iterator I = BI->begin(), E = BI->end(); I != E; ++I) {
549
550 //Get resource usage for this instruction
Tanya Lattner081fbd12004-07-30 23:36:10 +0000551 InstrRUsage rUsage = msi->getInstrRUsage(I->getOpcode());
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000552 std::vector<std::vector<resourceId_t> > resources = rUsage.resourcesByCycle;
553
554 //Loop over resources in each cycle and increments their usage count
555 for(unsigned i=0; i < resources.size(); ++i)
556 for(unsigned j=0; j < resources[i].size(); ++j) {
Tanya Lattner42ed1482005-04-22 06:32:48 +0000557 if(!resourceUsageCount.count(resources[i][j])) {
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000558 resourceUsageCount[resources[i][j]] = 1;
559 }
560 else {
561 resourceUsageCount[resources[i][j]] = resourceUsageCount[resources[i][j]] + 1;
562 }
563 }
564 }
565
566 //Find maximum usage count
Misha Brukmanb4402432005-04-21 23:30:14 +0000567
Tanya Lattnera6820d62004-05-08 16:12:10 +0000568 //Get max number of instructions that can be issued at once. (FIXME)
Tanya Lattner081fbd12004-07-30 23:36:10 +0000569 int issueSlots = msi->maxNumIssueTotal;
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000570
571 for(std::map<unsigned,unsigned>::iterator RB = resourceUsageCount.begin(), RE = resourceUsageCount.end(); RB != RE; ++RB) {
Misha Brukmanb4402432005-04-21 23:30:14 +0000572
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000573 //Get the total number of the resources in our cpu
Tanya Lattnera066df62004-05-26 06:27:18 +0000574 int resourceNum = CPUResource::getCPUResource(RB->first)->maxNumUsers;
Misha Brukmanb4402432005-04-21 23:30:14 +0000575
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000576 //Get total usage count for this resources
577 unsigned usageCount = RB->second;
Misha Brukmanb4402432005-04-21 23:30:14 +0000578
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000579 //Divide the usage count by either the max number we can issue or the number of
580 //resources (whichever is its upper bound)
581 double finalUsageCount;
Tanya Lattnera066df62004-05-26 06:27:18 +0000582 if( resourceNum <= issueSlots)
583 finalUsageCount = ceil(1.0 * usageCount / resourceNum);
584 else
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000585 finalUsageCount = ceil(1.0 * usageCount / issueSlots);
Misha Brukmanb4402432005-04-21 23:30:14 +0000586
587
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000588 //Only keep track of the max
589 ResMII = std::max( (int) finalUsageCount, ResMII);
590
591 }
592
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000593 return ResMII;
594
595}
596
Tanya Lattner081fbd12004-07-30 23:36:10 +0000597/// calculateRecMII - Calculates the value of the highest recurrence
598/// By value we mean the total latency
Tanya Lattnera6820d62004-05-08 16:12:10 +0000599int ModuloSchedulingPass::calculateRecMII(MSchedGraph *graph, int MII) {
Tanya Lattner56807c62005-02-10 17:02:58 +0000600 /*std::vector<MSchedGraphNode*> vNodes;
Tanya Lattnera6820d62004-05-08 16:12:10 +0000601 //Loop over all nodes in the graph
602 for(MSchedGraph::iterator I = graph->begin(), E = graph->end(); I != E; ++I) {
603 findAllReccurrences(I->second, vNodes, MII);
604 vNodes.clear();
Tanya Lattner56807c62005-02-10 17:02:58 +0000605 }*/
Misha Brukmanb4402432005-04-21 23:30:14 +0000606
Tanya Lattner56807c62005-02-10 17:02:58 +0000607 TIME_REGION(X, "calculateRecMII");
Tanya Lattnera6820d62004-05-08 16:12:10 +0000608
Tanya Lattner56807c62005-02-10 17:02:58 +0000609 findAllCircuits(graph, MII);
Tanya Lattnera6820d62004-05-08 16:12:10 +0000610 int RecMII = 0;
Misha Brukmanb4402432005-04-21 23:30:14 +0000611
Tanya Lattner13417b52005-03-23 01:47:20 +0000612 for(std::set<std::pair<int, std::vector<MSchedGraphNode*> > >::iterator I = recurrenceList.begin(), E=recurrenceList.end(); I !=E; ++I) {
Tanya Lattnera6820d62004-05-08 16:12:10 +0000613 RecMII = std::max(RecMII, I->first);
Tanya Lattner081fbd12004-07-30 23:36:10 +0000614 }
Misha Brukmanb4402432005-04-21 23:30:14 +0000615
Tanya Lattnera6820d62004-05-08 16:12:10 +0000616 return MII;
617}
618
Tanya Lattner081fbd12004-07-30 23:36:10 +0000619/// calculateNodeAttributes - The following properties are calculated for
620/// each node in the dependence graph: ASAP, ALAP, Depth, Height, and
621/// MOB.
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000622void ModuloSchedulingPass::calculateNodeAttributes(MSchedGraph *graph, int MII) {
623
Tanya Lattner56807c62005-02-10 17:02:58 +0000624 TIME_REGION(X, "calculateNodeAttributes");
625
Tanya Lattnerddebd1e2004-10-30 00:39:07 +0000626 assert(nodeToAttributesMap.empty() && "Node attribute map was not cleared");
627
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000628 //Loop over the nodes and add them to the map
629 for(MSchedGraph::iterator I = graph->begin(), E = graph->end(); I != E; ++I) {
Tanya Lattnerddebd1e2004-10-30 00:39:07 +0000630
631 DEBUG(std::cerr << "Inserting node into attribute map: " << *I->second << "\n");
632
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000633 //Assert if its already in the map
Tanya Lattnerddebd1e2004-10-30 00:39:07 +0000634 assert(nodeToAttributesMap.count(I->second) == 0 &&
635 "Node attributes are already in the map");
Misha Brukmanb4402432005-04-21 23:30:14 +0000636
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000637 //Put into the map with default attribute values
638 nodeToAttributesMap[I->second] = MSNodeAttributes();
639 }
640
641 //Create set to deal with reccurrences
642 std::set<MSchedGraphNode*> visitedNodes;
Misha Brukmanb4402432005-04-21 23:30:14 +0000643
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000644 //Now Loop over map and calculate the node attributes
645 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
Tanya Lattnera6820d62004-05-08 16:12:10 +0000646 calculateASAP(I->first, MII, (MSchedGraphNode*) 0);
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000647 visitedNodes.clear();
648 }
Misha Brukmanb4402432005-04-21 23:30:14 +0000649
Tanya Lattnera6820d62004-05-08 16:12:10 +0000650 int maxASAP = findMaxASAP();
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000651 //Calculate ALAP which depends on ASAP being totally calculated
Tanya Lattnera6820d62004-05-08 16:12:10 +0000652 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
653 calculateALAP(I->first, MII, maxASAP, (MSchedGraphNode*) 0);
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000654 visitedNodes.clear();
Tanya Lattnera6820d62004-05-08 16:12:10 +0000655 }
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000656
657 //Calculate MOB which depends on ASAP being totally calculated, also do depth and height
Tanya Lattnera6820d62004-05-08 16:12:10 +0000658 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(), E = nodeToAttributesMap.end(); I != E; ++I) {
659 (I->second).MOB = std::max(0,(I->second).ALAP - (I->second).ASAP);
Misha Brukmanb4402432005-04-21 23:30:14 +0000660
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000661 DEBUG(std::cerr << "MOB: " << (I->second).MOB << " (" << *(I->first) << ")\n");
Tanya Lattnera6820d62004-05-08 16:12:10 +0000662 calculateDepth(I->first, (MSchedGraphNode*) 0);
663 calculateHeight(I->first, (MSchedGraphNode*) 0);
664 }
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000665
666
667}
668
Tanya Lattner081fbd12004-07-30 23:36:10 +0000669/// ignoreEdge - Checks to see if this edge of a recurrence should be ignored or not
Tanya Lattnera6820d62004-05-08 16:12:10 +0000670bool ModuloSchedulingPass::ignoreEdge(MSchedGraphNode *srcNode, MSchedGraphNode *destNode) {
671 if(destNode == 0 || srcNode ==0)
672 return false;
Misha Brukmanb4402432005-04-21 23:30:14 +0000673
Tanya Lattnera6820d62004-05-08 16:12:10 +0000674 bool findEdge = edgesToIgnore.count(std::make_pair(srcNode, destNode->getInEdgeNum(srcNode)));
Misha Brukmanb4402432005-04-21 23:30:14 +0000675
Tanya Lattner13417b52005-03-23 01:47:20 +0000676 DEBUG(std::cerr << "Ignoring edge? from: " << *srcNode << " to " << *destNode << "\n");
677
Tanya Lattnera6820d62004-05-08 16:12:10 +0000678 return findEdge;
679}
680
Tanya Lattner081fbd12004-07-30 23:36:10 +0000681
Misha Brukmanb4402432005-04-21 23:30:14 +0000682/// calculateASAP - Calculates the
Tanya Lattnera6820d62004-05-08 16:12:10 +0000683int ModuloSchedulingPass::calculateASAP(MSchedGraphNode *node, int MII, MSchedGraphNode *destNode) {
Misha Brukmanb4402432005-04-21 23:30:14 +0000684
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000685 DEBUG(std::cerr << "Calculating ASAP for " << *node << "\n");
686
Tanya Lattnera6820d62004-05-08 16:12:10 +0000687 //Get current node attributes
688 MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
689
690 if(attributes.ASAP != -1)
691 return attributes.ASAP;
Misha Brukmanb4402432005-04-21 23:30:14 +0000692
Tanya Lattnera6820d62004-05-08 16:12:10 +0000693 int maxPredValue = 0;
Misha Brukmanb4402432005-04-21 23:30:14 +0000694
Tanya Lattnera6820d62004-05-08 16:12:10 +0000695 //Iterate over all of the predecessors and find max
696 for(MSchedGraphNode::pred_iterator P = node->pred_begin(), E = node->pred_end(); P != E; ++P) {
Misha Brukmanb4402432005-04-21 23:30:14 +0000697
Tanya Lattnera6820d62004-05-08 16:12:10 +0000698 //Only process if we are not ignoring the edge
699 if(!ignoreEdge(*P, node)) {
700 int predASAP = -1;
701 predASAP = calculateASAP(*P, MII, node);
Misha Brukmanb4402432005-04-21 23:30:14 +0000702
Tanya Lattnera6820d62004-05-08 16:12:10 +0000703 assert(predASAP != -1 && "ASAP has not been calculated");
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000704 int iteDiff = node->getInEdge(*P).getIteDiff();
Misha Brukmanb4402432005-04-21 23:30:14 +0000705
Tanya Lattnera6820d62004-05-08 16:12:10 +0000706 int currentPredValue = predASAP + (*P)->getLatency() - (iteDiff * MII);
707 DEBUG(std::cerr << "pred ASAP: " << predASAP << ", iteDiff: " << iteDiff << ", PredLatency: " << (*P)->getLatency() << ", Current ASAP pred: " << currentPredValue << "\n");
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000708 maxPredValue = std::max(maxPredValue, currentPredValue);
709 }
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000710 }
Misha Brukmanb4402432005-04-21 23:30:14 +0000711
Tanya Lattnera6820d62004-05-08 16:12:10 +0000712 attributes.ASAP = maxPredValue;
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000713
714 DEBUG(std::cerr << "ASAP: " << attributes.ASAP << " (" << *node << ")\n");
Misha Brukmanb4402432005-04-21 23:30:14 +0000715
Tanya Lattnera6820d62004-05-08 16:12:10 +0000716 return maxPredValue;
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000717}
718
719
Misha Brukmanb4402432005-04-21 23:30:14 +0000720int ModuloSchedulingPass::calculateALAP(MSchedGraphNode *node, int MII,
Tanya Lattnera6820d62004-05-08 16:12:10 +0000721 int maxASAP, MSchedGraphNode *srcNode) {
Misha Brukmanb4402432005-04-21 23:30:14 +0000722
Tanya Lattnera6820d62004-05-08 16:12:10 +0000723 DEBUG(std::cerr << "Calculating ALAP for " << *node << "\n");
Misha Brukmanb4402432005-04-21 23:30:14 +0000724
Tanya Lattnera6820d62004-05-08 16:12:10 +0000725 MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
Misha Brukmanb4402432005-04-21 23:30:14 +0000726
Tanya Lattnera6820d62004-05-08 16:12:10 +0000727 if(attributes.ALAP != -1)
728 return attributes.ALAP;
Misha Brukmanb4402432005-04-21 23:30:14 +0000729
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000730 if(node->hasSuccessors()) {
Misha Brukmanb4402432005-04-21 23:30:14 +0000731
Tanya Lattnera6820d62004-05-08 16:12:10 +0000732 //Trying to deal with the issue where the node has successors, but
733 //we are ignoring all of the edges to them. So this is my hack for
734 //now.. there is probably a more elegant way of doing this (FIXME)
735 bool processedOneEdge = false;
736
737 //FIXME, set to something high to start
738 int minSuccValue = 9999999;
Misha Brukmanb4402432005-04-21 23:30:14 +0000739
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000740 //Iterate over all of the predecessors and fine max
Misha Brukmanb4402432005-04-21 23:30:14 +0000741 for(MSchedGraphNode::succ_iterator P = node->succ_begin(),
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000742 E = node->succ_end(); P != E; ++P) {
Misha Brukmanb4402432005-04-21 23:30:14 +0000743
Tanya Lattnera6820d62004-05-08 16:12:10 +0000744 //Only process if we are not ignoring the edge
745 if(!ignoreEdge(node, *P)) {
746 processedOneEdge = true;
747 int succALAP = -1;
748 succALAP = calculateALAP(*P, MII, maxASAP, node);
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000749
Tanya Lattnera6820d62004-05-08 16:12:10 +0000750 assert(succALAP != -1 && "Successors ALAP should have been caclulated");
751
752 int iteDiff = P.getEdge().getIteDiff();
753
754 int currentSuccValue = succALAP - node->getLatency() + iteDiff * MII;
755
756 DEBUG(std::cerr << "succ ALAP: " << succALAP << ", iteDiff: " << iteDiff << ", SuccLatency: " << (*P)->getLatency() << ", Current ALAP succ: " << currentSuccValue << "\n");
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000757
Tanya Lattnera6820d62004-05-08 16:12:10 +0000758 minSuccValue = std::min(minSuccValue, currentSuccValue);
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000759 }
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000760 }
Misha Brukmanb4402432005-04-21 23:30:14 +0000761
Tanya Lattnera6820d62004-05-08 16:12:10 +0000762 if(processedOneEdge)
763 attributes.ALAP = minSuccValue;
Misha Brukmanb4402432005-04-21 23:30:14 +0000764
Tanya Lattnera6820d62004-05-08 16:12:10 +0000765 else
766 attributes.ALAP = maxASAP;
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000767 }
Tanya Lattnera6820d62004-05-08 16:12:10 +0000768 else
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000769 attributes.ALAP = maxASAP;
Tanya Lattnera6820d62004-05-08 16:12:10 +0000770
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000771 DEBUG(std::cerr << "ALAP: " << attributes.ALAP << " (" << *node << ")\n");
Tanya Lattnera6820d62004-05-08 16:12:10 +0000772
773 if(attributes.ALAP < 0)
774 attributes.ALAP = 0;
775
776 return attributes.ALAP;
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000777}
778
779int ModuloSchedulingPass::findMaxASAP() {
780 int maxASAP = 0;
781
782 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(),
783 E = nodeToAttributesMap.end(); I != E; ++I)
784 maxASAP = std::max(maxASAP, I->second.ASAP);
785 return maxASAP;
786}
787
788
Tanya Lattnera6820d62004-05-08 16:12:10 +0000789int ModuloSchedulingPass::calculateHeight(MSchedGraphNode *node,MSchedGraphNode *srcNode) {
Misha Brukmanb4402432005-04-21 23:30:14 +0000790
Tanya Lattnera6820d62004-05-08 16:12:10 +0000791 MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000792
Tanya Lattnera6820d62004-05-08 16:12:10 +0000793 if(attributes.height != -1)
794 return attributes.height;
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000795
Tanya Lattnera6820d62004-05-08 16:12:10 +0000796 int maxHeight = 0;
Misha Brukmanb4402432005-04-21 23:30:14 +0000797
Tanya Lattnera6820d62004-05-08 16:12:10 +0000798 //Iterate over all of the predecessors and find max
Misha Brukmanb4402432005-04-21 23:30:14 +0000799 for(MSchedGraphNode::succ_iterator P = node->succ_begin(),
Tanya Lattnera6820d62004-05-08 16:12:10 +0000800 E = node->succ_end(); P != E; ++P) {
Misha Brukmanb4402432005-04-21 23:30:14 +0000801
802
Tanya Lattnera6820d62004-05-08 16:12:10 +0000803 if(!ignoreEdge(node, *P)) {
804 int succHeight = calculateHeight(*P, node);
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000805
Tanya Lattnera6820d62004-05-08 16:12:10 +0000806 assert(succHeight != -1 && "Successors Height should have been caclulated");
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000807
Tanya Lattnera6820d62004-05-08 16:12:10 +0000808 int currentHeight = succHeight + node->getLatency();
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000809 maxHeight = std::max(maxHeight, currentHeight);
810 }
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000811 }
Tanya Lattnera6820d62004-05-08 16:12:10 +0000812 attributes.height = maxHeight;
813 DEBUG(std::cerr << "Height: " << attributes.height << " (" << *node << ")\n");
814 return maxHeight;
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000815}
816
817
Misha Brukmanb4402432005-04-21 23:30:14 +0000818int ModuloSchedulingPass::calculateDepth(MSchedGraphNode *node,
Tanya Lattnera6820d62004-05-08 16:12:10 +0000819 MSchedGraphNode *destNode) {
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000820
Tanya Lattnera6820d62004-05-08 16:12:10 +0000821 MSNodeAttributes &attributes = nodeToAttributesMap.find(node)->second;
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000822
Tanya Lattnera6820d62004-05-08 16:12:10 +0000823 if(attributes.depth != -1)
824 return attributes.depth;
825
826 int maxDepth = 0;
Misha Brukmanb4402432005-04-21 23:30:14 +0000827
Tanya Lattnera6820d62004-05-08 16:12:10 +0000828 //Iterate over all of the predecessors and fine max
829 for(MSchedGraphNode::pred_iterator P = node->pred_begin(), E = node->pred_end(); P != E; ++P) {
830
831 if(!ignoreEdge(*P, node)) {
832 int predDepth = -1;
833 predDepth = calculateDepth(*P, node);
Misha Brukmanb4402432005-04-21 23:30:14 +0000834
Tanya Lattnera6820d62004-05-08 16:12:10 +0000835 assert(predDepth != -1 && "Predecessors ASAP should have been caclulated");
836
837 int currentDepth = predDepth + (*P)->getLatency();
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000838 maxDepth = std::max(maxDepth, currentDepth);
839 }
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000840 }
Tanya Lattnera6820d62004-05-08 16:12:10 +0000841 attributes.depth = maxDepth;
Misha Brukmanb4402432005-04-21 23:30:14 +0000842
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000843 DEBUG(std::cerr << "Depth: " << attributes.depth << " (" << *node << "*)\n");
Tanya Lattnera6820d62004-05-08 16:12:10 +0000844 return maxDepth;
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +0000845}
846
847
Tanya Lattnera6820d62004-05-08 16:12:10 +0000848
849void ModuloSchedulingPass::addReccurrence(std::vector<MSchedGraphNode*> &recurrence, int II, MSchedGraphNode *srcBENode, MSchedGraphNode *destBENode) {
850 //Check to make sure that this recurrence is unique
851 bool same = false;
852
853
854 //Loop over all recurrences already in our list
855 for(std::set<std::pair<int, std::vector<MSchedGraphNode*> > >::iterator R = recurrenceList.begin(), RE = recurrenceList.end(); R != RE; ++R) {
Misha Brukmanb4402432005-04-21 23:30:14 +0000856
Tanya Lattnera6820d62004-05-08 16:12:10 +0000857 bool all_same = true;
858 //First compare size
859 if(R->second.size() == recurrence.size()) {
Misha Brukmanb4402432005-04-21 23:30:14 +0000860
Tanya Lattnera6820d62004-05-08 16:12:10 +0000861 for(std::vector<MSchedGraphNode*>::const_iterator node = R->second.begin(), end = R->second.end(); node != end; ++node) {
Alkis Evlogimenos20f1b0b2004-09-28 14:42:44 +0000862 if(std::find(recurrence.begin(), recurrence.end(), *node) == recurrence.end()) {
Tanya Lattnera6820d62004-05-08 16:12:10 +0000863 all_same = all_same && false;
864 break;
865 }
866 else
867 all_same = all_same && true;
868 }
869 if(all_same) {
870 same = true;
871 break;
872 }
873 }
874 }
Misha Brukmanb4402432005-04-21 23:30:14 +0000875
Tanya Lattnera6820d62004-05-08 16:12:10 +0000876 if(!same) {
Tanya Lattnera066df62004-05-26 06:27:18 +0000877 srcBENode = recurrence.back();
878 destBENode = recurrence.front();
Misha Brukmanb4402432005-04-21 23:30:14 +0000879
Tanya Lattnera066df62004-05-26 06:27:18 +0000880 //FIXME
881 if(destBENode->getInEdge(srcBENode).getIteDiff() == 0) {
882 //DEBUG(std::cerr << "NOT A BACKEDGE\n");
Misha Brukmanb4402432005-04-21 23:30:14 +0000883 //find actual backedge HACK HACK
Tanya Lattnera066df62004-05-26 06:27:18 +0000884 for(unsigned i=0; i< recurrence.size()-1; ++i) {
885 if(recurrence[i+1]->getInEdge(recurrence[i]).getIteDiff() == 1) {
886 srcBENode = recurrence[i];
887 destBENode = recurrence[i+1];
888 break;
889 }
Misha Brukmanb4402432005-04-21 23:30:14 +0000890
Tanya Lattnera066df62004-05-26 06:27:18 +0000891 }
Misha Brukmanb4402432005-04-21 23:30:14 +0000892
Tanya Lattnera066df62004-05-26 06:27:18 +0000893 }
Tanya Lattnera6820d62004-05-08 16:12:10 +0000894 DEBUG(std::cerr << "Back Edge to Remove: " << *srcBENode << " to " << *destBENode << "\n");
895 edgesToIgnore.insert(std::make_pair(srcBENode, destBENode->getInEdgeNum(srcBENode)));
896 recurrenceList.insert(std::make_pair(II, recurrence));
897 }
Misha Brukmanb4402432005-04-21 23:30:14 +0000898
Tanya Lattnera6820d62004-05-08 16:12:10 +0000899}
900
Tanya Lattner56807c62005-02-10 17:02:58 +0000901int CircCount;
902
903void ModuloSchedulingPass::unblock(MSchedGraphNode *u, std::set<MSchedGraphNode*> &blocked,
904 std::map<MSchedGraphNode*, std::set<MSchedGraphNode*> > &B) {
905
906 //Unblock u
907 DEBUG(std::cerr << "Unblocking: " << *u << "\n");
908 blocked.erase(u);
909
910 //std::set<MSchedGraphNode*> toErase;
911 while (!B[u].empty()) {
912 MSchedGraphNode *W = *B[u].begin();
913 B[u].erase(W);
914 //toErase.insert(*W);
915 DEBUG(std::cerr << "Removed: " << *W << "from B-List\n");
916 if(blocked.count(W))
917 unblock(W, blocked, B);
918 }
919
920}
921
Misha Brukmanb4402432005-04-21 23:30:14 +0000922bool ModuloSchedulingPass::circuit(MSchedGraphNode *v, std::vector<MSchedGraphNode*> &stack,
923 std::set<MSchedGraphNode*> &blocked, std::vector<MSchedGraphNode*> &SCC,
924 MSchedGraphNode *s, std::map<MSchedGraphNode*, std::set<MSchedGraphNode*> > &B,
Tanya Lattner56807c62005-02-10 17:02:58 +0000925 int II, std::map<MSchedGraphNode*, MSchedGraphNode*> &newNodes) {
926 bool f = false;
Misha Brukmanb4402432005-04-21 23:30:14 +0000927
Tanya Lattner56807c62005-02-10 17:02:58 +0000928 DEBUG(std::cerr << "Finding Circuits Starting with: ( " << v << ")"<< *v << "\n");
929
930 //Push node onto the stack
931 stack.push_back(v);
932
933 //block this node
934 blocked.insert(v);
935
936 //Loop over all successors of node v that are in the scc, create Adjaceny list
937 std::set<MSchedGraphNode*> AkV;
938 for(MSchedGraphNode::succ_iterator I = v->succ_begin(), E = v->succ_end(); I != E; ++I) {
939 if((std::find(SCC.begin(), SCC.end(), *I) != SCC.end())) {
940 AkV.insert(*I);
941 }
942 }
943
944 for(std::set<MSchedGraphNode*>::iterator I = AkV.begin(), E = AkV.end(); I != E; ++I) {
945 if(*I == s) {
946 //We have a circuit, so add it to our list
Tanya Lattner42ed1482005-04-22 06:32:48 +0000947 addRecc(stack, newNodes);
Tanya Lattner56807c62005-02-10 17:02:58 +0000948 f = true;
Tanya Lattner56807c62005-02-10 17:02:58 +0000949 }
950 else if(!blocked.count(*I)) {
951 if(circuit(*I, stack, blocked, SCC, s, B, II, newNodes))
952 f = true;
953 }
954 else
955 DEBUG(std::cerr << "Blocked: " << **I << "\n");
956 }
957
958
959 if(f) {
960 unblock(v, blocked, B);
961 }
962 else {
Misha Brukmanb4402432005-04-21 23:30:14 +0000963 for(std::set<MSchedGraphNode*>::iterator I = AkV.begin(), E = AkV.end(); I != E; ++I)
Tanya Lattner56807c62005-02-10 17:02:58 +0000964 B[*I].insert(v);
965
966 }
967
968 //Pop v
969 stack.pop_back();
970
971 return f;
972
973}
974
Tanya Lattner42ed1482005-04-22 06:32:48 +0000975void ModuloSchedulingPass::addRecc(std::vector<MSchedGraphNode*> &stack, std::map<MSchedGraphNode*, MSchedGraphNode*> &newNodes) {
976 std::vector<MSchedGraphNode*> recc;
977 //Dump recurrence for now
978 DEBUG(std::cerr << "Starting Recc\n");
979
980 int totalDelay = 0;
981 int totalDistance = 0;
982 MSchedGraphNode *lastN = 0;
983 MSchedGraphNode *start = 0;
984 MSchedGraphNode *end = 0;
985
986 //Loop over recurrence, get delay and distance
987 for(std::vector<MSchedGraphNode*>::iterator N = stack.begin(), NE = stack.end(); N != NE; ++N) {
988 DEBUG(std::cerr << **N << "\n");
989 totalDelay += (*N)->getLatency();
990 if(lastN) {
991 int iteDiff = (*N)->getInEdge(lastN).getIteDiff();
992 totalDistance += iteDiff;
993
994 if(iteDiff > 0) {
995 start = lastN;
996 end = *N;
997 }
998 }
999 //Get the original node
1000 lastN = *N;
1001 recc.push_back(newNodes[*N]);
1002
1003
1004 }
1005
1006 //Get the loop edge
1007 totalDistance += lastN->getIteDiff(*stack.begin());
1008
1009 DEBUG(std::cerr << "End Recc\n");
1010 CircCount++;
1011
1012 if(start && end) {
1013 //Insert reccurrence into the list
1014 DEBUG(std::cerr << "Ignore Edge from!!: " << *start << " to " << *end << "\n");
1015 edgesToIgnore.insert(std::make_pair(newNodes[start], (newNodes[end])->getInEdgeNum(newNodes[start])));
1016 }
1017 else {
1018 //Insert reccurrence into the list
1019 DEBUG(std::cerr << "Ignore Edge from: " << *lastN << " to " << **stack.begin() << "\n");
1020 edgesToIgnore.insert(std::make_pair(newNodes[lastN], newNodes[(*stack.begin())]->getInEdgeNum(newNodes[lastN])));
1021
1022 }
1023 //Adjust II until we get close to the inequality delay - II*distance <= 0
1024 int RecMII = II; //Starting value
1025 int value = totalDelay-(RecMII * totalDistance);
1026 int lastII = II;
1027 while(value < 0) {
1028
1029 lastII = RecMII;
1030 RecMII--;
1031 value = totalDelay-(RecMII * totalDistance);
1032 }
1033
1034 recurrenceList.insert(std::make_pair(lastII, recc));
1035
1036}
1037
1038
Tanya Lattner56807c62005-02-10 17:02:58 +00001039void ModuloSchedulingPass::findAllCircuits(MSchedGraph *g, int II) {
1040
1041 CircCount = 0;
1042
Misha Brukmanb4402432005-04-21 23:30:14 +00001043 //Keep old to new node mapping information
Tanya Lattner56807c62005-02-10 17:02:58 +00001044 std::map<MSchedGraphNode*, MSchedGraphNode*> newNodes;
1045
1046 //copy the graph
1047 MSchedGraph *MSG = new MSchedGraph(*g, newNodes);
1048
1049 DEBUG(std::cerr << "Finding All Circuits\n");
1050
1051 //Set of blocked nodes
1052 std::set<MSchedGraphNode*> blocked;
1053
1054 //Stack holding current circuit
1055 std::vector<MSchedGraphNode*> stack;
1056
1057 //Map for B Lists
1058 std::map<MSchedGraphNode*, std::set<MSchedGraphNode*> > B;
1059
1060 //current node
1061 MSchedGraphNode *s;
1062
1063
1064 //Iterate over the graph until its down to one node or empty
1065 while(MSG->size() > 1) {
Misha Brukmanb4402432005-04-21 23:30:14 +00001066
Tanya Lattner56807c62005-02-10 17:02:58 +00001067 //Write Graph out to file
1068 //WriteGraphToFile(std::cerr, "Graph" + utostr(MSG->size()), MSG);
1069
1070 DEBUG(std::cerr << "Graph Size: " << MSG->size() << "\n");
1071 DEBUG(std::cerr << "Finding strong component Vk with least vertex\n");
1072
1073 //Iterate over all the SCCs in the graph
1074 std::set<MSchedGraphNode*> Visited;
1075 std::vector<MSchedGraphNode*> Vk;
1076 MSchedGraphNode* s = 0;
1077
1078 //Find scc with the least vertex
1079 for (MSchedGraph::iterator GI = MSG->begin(), E = MSG->end(); GI != E; ++GI)
1080 if (Visited.insert(GI->second).second) {
1081 for (scc_iterator<MSchedGraphNode*> SCCI = scc_begin(GI->second),
1082 E = scc_end(GI->second); SCCI != E; ++SCCI) {
1083 std::vector<MSchedGraphNode*> &nextSCC = *SCCI;
1084
1085 if (Visited.insert(nextSCC[0]).second) {
1086 Visited.insert(nextSCC.begin()+1, nextSCC.end());
1087
1088 DEBUG(std::cerr << "SCC size: " << nextSCC.size() << "\n");
1089
1090 //Ignore self loops
1091 if(nextSCC.size() > 1) {
Tanya Lattner13417b52005-03-23 01:47:20 +00001092
Tanya Lattner56807c62005-02-10 17:02:58 +00001093 //Get least vertex in Vk
1094 if(!s) {
1095 s = nextSCC[0];
1096 Vk = nextSCC;
1097 }
1098
1099 for(unsigned i = 0; i < nextSCC.size(); ++i) {
1100 if(nextSCC[i] < s) {
1101 s = nextSCC[i];
1102 Vk = nextSCC;
1103 }
1104 }
1105 }
1106 }
1107 }
1108 }
Misha Brukmanb4402432005-04-21 23:30:14 +00001109
1110
Tanya Lattner56807c62005-02-10 17:02:58 +00001111
1112 //Process SCC
1113 DEBUG(for(std::vector<MSchedGraphNode*>::iterator N = Vk.begin(), NE = Vk.end();
1114 N != NE; ++N) { std::cerr << *((*N)->getInst()); });
Misha Brukmanb4402432005-04-21 23:30:14 +00001115
Tanya Lattner56807c62005-02-10 17:02:58 +00001116 //Iterate over all nodes in this scc
1117 for(std::vector<MSchedGraphNode*>::iterator N = Vk.begin(), NE = Vk.end();
1118 N != NE; ++N) {
1119 blocked.erase(*N);
1120 B[*N].clear();
1121 }
1122 if(Vk.size() > 1) {
1123 circuit(s, stack, blocked, Vk, s, B, II, newNodes);
Misha Brukmanb4402432005-04-21 23:30:14 +00001124
Tanya Lattner42ed1482005-04-22 06:32:48 +00001125 //Delete nodes from the graph
Tanya Lattner56807c62005-02-10 17:02:58 +00001126 //Find all nodes up to s and delete them
1127 std::vector<MSchedGraphNode*> nodesToRemove;
1128 nodesToRemove.push_back(s);
1129 for(MSchedGraph::iterator N = MSG->begin(), NE = MSG->end(); N != NE; ++N) {
1130 if(N->second < s )
Tanya Lattner42ed1482005-04-22 06:32:48 +00001131 nodesToRemove.push_back(N->second);
Tanya Lattner56807c62005-02-10 17:02:58 +00001132 }
1133 for(std::vector<MSchedGraphNode*>::iterator N = nodesToRemove.begin(), NE = nodesToRemove.end(); N != NE; ++N) {
1134 DEBUG(std::cerr << "Deleting Node: " << **N << "\n");
1135 MSG->deleteNode(*N);
1136 }
1137 }
1138 else
1139 break;
Tanya Lattner42ed1482005-04-22 06:32:48 +00001140 }
Tanya Lattner56807c62005-02-10 17:02:58 +00001141 DEBUG(std::cerr << "Num Circuits found: " << CircCount << "\n");
1142}
1143
1144
Misha Brukmanb4402432005-04-21 23:30:14 +00001145void ModuloSchedulingPass::findAllReccurrences(MSchedGraphNode *node,
Tanya Lattnera6820d62004-05-08 16:12:10 +00001146 std::vector<MSchedGraphNode*> &visitedNodes,
1147 int II) {
Misha Brukmanb4402432005-04-21 23:30:14 +00001148
Tanya Lattnera6820d62004-05-08 16:12:10 +00001149
Alkis Evlogimenos20f1b0b2004-09-28 14:42:44 +00001150 if(std::find(visitedNodes.begin(), visitedNodes.end(), node) != visitedNodes.end()) {
Tanya Lattnera6820d62004-05-08 16:12:10 +00001151 std::vector<MSchedGraphNode*> recurrence;
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001152 bool first = true;
Tanya Lattnera6820d62004-05-08 16:12:10 +00001153 int delay = 0;
1154 int distance = 0;
1155 int RecMII = II; //Starting value
1156 MSchedGraphNode *last = node;
Chris Lattner3e689f82004-08-04 03:51:55 +00001157 MSchedGraphNode *srcBackEdge = 0;
1158 MSchedGraphNode *destBackEdge = 0;
Misha Brukmanb4402432005-04-21 23:30:14 +00001159
Tanya Lattnera6820d62004-05-08 16:12:10 +00001160
1161
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001162 for(std::vector<MSchedGraphNode*>::iterator I = visitedNodes.begin(), E = visitedNodes.end();
1163 I !=E; ++I) {
Tanya Lattnera6820d62004-05-08 16:12:10 +00001164
Misha Brukmanb4402432005-04-21 23:30:14 +00001165 if(*I == node)
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001166 first = false;
1167 if(first)
1168 continue;
Tanya Lattnera6820d62004-05-08 16:12:10 +00001169
1170 delay = delay + (*I)->getLatency();
1171
1172 if(*I != node) {
1173 int diff = (*I)->getInEdge(last).getIteDiff();
1174 distance += diff;
1175 if(diff > 0) {
1176 srcBackEdge = last;
1177 destBackEdge = *I;
1178 }
1179 }
1180
1181 recurrence.push_back(*I);
1182 last = *I;
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001183 }
Tanya Lattnera6820d62004-05-08 16:12:10 +00001184
1185
Misha Brukmanb4402432005-04-21 23:30:14 +00001186
Tanya Lattnera6820d62004-05-08 16:12:10 +00001187 //Get final distance calc
1188 distance += node->getInEdge(last).getIteDiff();
Tanya Lattnerab9cf272004-11-22 20:41:24 +00001189 DEBUG(std::cerr << "Reccurrence Distance: " << distance << "\n");
Tanya Lattnera6820d62004-05-08 16:12:10 +00001190
1191 //Adjust II until we get close to the inequality delay - II*distance <= 0
Misha Brukmanb4402432005-04-21 23:30:14 +00001192
Tanya Lattnera6820d62004-05-08 16:12:10 +00001193 int value = delay-(RecMII * distance);
1194 int lastII = II;
1195 while(value <= 0) {
Misha Brukmanb4402432005-04-21 23:30:14 +00001196
Tanya Lattnera6820d62004-05-08 16:12:10 +00001197 lastII = RecMII;
1198 RecMII--;
1199 value = delay-(RecMII * distance);
1200 }
Misha Brukmanb4402432005-04-21 23:30:14 +00001201
1202
Tanya Lattnera6820d62004-05-08 16:12:10 +00001203 DEBUG(std::cerr << "Final II for this recurrence: " << lastII << "\n");
1204 addReccurrence(recurrence, lastII, srcBackEdge, destBackEdge);
1205 assert(distance != 0 && "Recurrence distance should not be zero");
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001206 return;
1207 }
1208
Tanya Lattnerc227ad22005-01-18 04:15:41 +00001209 unsigned count = 0;
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001210 for(MSchedGraphNode::succ_iterator I = node->succ_begin(), E = node->succ_end(); I != E; ++I) {
1211 visitedNodes.push_back(node);
Tanya Lattnerc227ad22005-01-18 04:15:41 +00001212 //if(!edgesToIgnore.count(std::make_pair(node, count)))
Tanya Lattnera6820d62004-05-08 16:12:10 +00001213 findAllReccurrences(*I, visitedNodes, II);
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001214 visitedNodes.pop_back();
Tanya Lattnerc227ad22005-01-18 04:15:41 +00001215 count++;
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001216 }
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001217}
1218
Misha Brukmanb4402432005-04-21 23:30:14 +00001219void ModuloSchedulingPass::searchPath(MSchedGraphNode *node,
Tanya Lattnera31ad512005-02-23 02:01:42 +00001220 std::vector<MSchedGraphNode*> &path,
Tanya Lattner4d0ee752005-04-30 23:07:59 +00001221 std::set<MSchedGraphNode*> &nodesToAdd,
1222 std::set<MSchedGraphNode*> &new_reccurrence) {
Tanya Lattnera31ad512005-02-23 02:01:42 +00001223 //Push node onto the path
1224 path.push_back(node);
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001225
Misha Brukmanb4402432005-04-21 23:30:14 +00001226 //Loop over all successors and see if there is a path from this node to
Tanya Lattnera31ad512005-02-23 02:01:42 +00001227 //a recurrence in the partial order, if so.. add all nodes to be added to recc
Misha Brukmanb4402432005-04-21 23:30:14 +00001228 for(MSchedGraphNode::succ_iterator S = node->succ_begin(), SE = node->succ_end(); S != SE;
Tanya Lattnera31ad512005-02-23 02:01:42 +00001229 ++S) {
1230
Tanya Lattner4d0ee752005-04-30 23:07:59 +00001231 //Check if we should ignore this edge first
1232 if(ignoreEdge(node,*S))
1233 continue;
1234
1235 //check if successor is in this recurrence, we will get to it eventually
1236 if(new_reccurrence.count(*S))
1237 continue;
1238
1239 //If this node exists in a recurrence already in the partial
1240 //order, then add all nodes in the path to the set of nodes to add
1241 //Check if its already in our partial order, if not add it to the
1242 //final vector
1243 bool found = false;
Misha Brukmanb4402432005-04-21 23:30:14 +00001244 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(),
Tanya Lattnera31ad512005-02-23 02:01:42 +00001245 PE = partialOrder.end(); PO != PE; ++PO) {
Misha Brukmanb4402432005-04-21 23:30:14 +00001246
Tanya Lattnera31ad512005-02-23 02:01:42 +00001247 if(PO->count(*S)) {
Tanya Lattner4d0ee752005-04-30 23:07:59 +00001248 found = true;
1249 break;
Tanya Lattnera31ad512005-02-23 02:01:42 +00001250 }
Tanya Lattner4d0ee752005-04-30 23:07:59 +00001251 }
1252
1253 if(!found) {
1254 nodesToAdd.insert(*S);
1255 searchPath(*S, path, nodesToAdd, new_reccurrence);
1256 }
Tanya Lattnera31ad512005-02-23 02:01:42 +00001257 }
Misha Brukmanb4402432005-04-21 23:30:14 +00001258
Tanya Lattnera31ad512005-02-23 02:01:42 +00001259 //Pop Node off the path
1260 path.pop_back();
1261}
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001262
Misha Brukmanb4402432005-04-21 23:30:14 +00001263void ModuloSchedulingPass::pathToRecc(MSchedGraphNode *node,
Tanya Lattner13417b52005-03-23 01:47:20 +00001264 std::vector<MSchedGraphNode*> &path,
1265 std::set<MSchedGraphNode*> &poSet,
1266 std::set<MSchedGraphNode*> &lastNodes) {
1267 //Push node onto the path
1268 path.push_back(node);
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001269
Tanya Lattner13417b52005-03-23 01:47:20 +00001270 DEBUG(std::cerr << "Current node: " << *node << "\n");
1271
Misha Brukmanb4402432005-04-21 23:30:14 +00001272 //Loop over all successors and see if there is a path from this node to
Tanya Lattner13417b52005-03-23 01:47:20 +00001273 //a recurrence in the partial order, if so.. add all nodes to be added to recc
Misha Brukmanb4402432005-04-21 23:30:14 +00001274 for(MSchedGraphNode::succ_iterator S = node->succ_begin(), SE = node->succ_end(); S != SE;
Tanya Lattner13417b52005-03-23 01:47:20 +00001275 ++S) {
1276 DEBUG(std::cerr << "Succ:" << **S << "\n");
1277 //Check if we should ignore this edge first
1278 if(ignoreEdge(node,*S))
1279 continue;
Misha Brukmanb4402432005-04-21 23:30:14 +00001280
Tanya Lattner13417b52005-03-23 01:47:20 +00001281 if(poSet.count(*S)) {
1282 DEBUG(std::cerr << "Found path to recc from no pred\n");
1283 //Loop over path, if it exists in lastNodes, then add to poset, and remove from lastNodes
1284 for(std::vector<MSchedGraphNode*>::iterator I = path.begin(), IE = path.end(); I != IE; ++I) {
1285 if(lastNodes.count(*I)) {
1286 DEBUG(std::cerr << "Inserting node into recc: " << **I << "\n");
1287 poSet.insert(*I);
1288 lastNodes.erase(*I);
1289 }
1290 }
1291 }
1292 else
1293 pathToRecc(*S, path, poSet, lastNodes);
1294 }
Misha Brukmanb4402432005-04-21 23:30:14 +00001295
Tanya Lattner13417b52005-03-23 01:47:20 +00001296 //Pop Node off the path
1297 path.pop_back();
1298}
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001299
Tanya Lattnera6820d62004-05-08 16:12:10 +00001300void ModuloSchedulingPass::computePartialOrder() {
Tanya Lattner13c71ca2004-11-24 01:49:10 +00001301
Tanya Lattner56807c62005-02-10 17:02:58 +00001302 TIME_REGION(X, "calculatePartialOrder");
Tanya Lattner42ed1482005-04-22 06:32:48 +00001303
1304 DEBUG(std::cerr << "Computing Partial Order\n");
Misha Brukmanb4402432005-04-21 23:30:14 +00001305
Tanya Lattner42ed1482005-04-22 06:32:48 +00001306 //Only push BA branches onto the final node order, we put other
1307 //branches after it FIXME: Should we really be pushing branches on
1308 //it a specific order instead of relying on BA being there?
1309
Tanya Lattnerd8cc4fa2004-11-29 04:39:47 +00001310 std::vector<MSchedGraphNode*> branches;
Tanya Lattner42ed1482005-04-22 06:32:48 +00001311
1312 //Steps to add a recurrence to the partial order 1) Find reccurrence
1313 //with the highest RecMII. Add it to the partial order. 2) For each
1314 //recurrence with decreasing RecMII, add it to the partial order
1315 //along with any nodes that connect this recurrence to recurrences
1316 //already in the partial order
1317 for(std::set<std::pair<int, std::vector<MSchedGraphNode*> > >::reverse_iterator
Tanya Lattnera31ad512005-02-23 02:01:42 +00001318 I = recurrenceList.rbegin(), E=recurrenceList.rend(); I !=E; ++I) {
Tanya Lattnera6820d62004-05-08 16:12:10 +00001319
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001320 std::set<MSchedGraphNode*> new_recurrence;
Tanya Lattnera31ad512005-02-23 02:01:42 +00001321
Tanya Lattnera6820d62004-05-08 16:12:10 +00001322 //Loop through recurrence and remove any nodes already in the partial order
Misha Brukmanb4402432005-04-21 23:30:14 +00001323 for(std::vector<MSchedGraphNode*>::const_iterator N = I->second.begin(),
Tanya Lattnera31ad512005-02-23 02:01:42 +00001324 NE = I->second.end(); N != NE; ++N) {
1325
Tanya Lattnera6820d62004-05-08 16:12:10 +00001326 bool found = false;
Misha Brukmanb4402432005-04-21 23:30:14 +00001327 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(),
Tanya Lattnera31ad512005-02-23 02:01:42 +00001328 PE = partialOrder.end(); PO != PE; ++PO) {
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001329 if(PO->count(*N))
Tanya Lattnera6820d62004-05-08 16:12:10 +00001330 found = true;
1331 }
Tanya Lattnera31ad512005-02-23 02:01:42 +00001332
1333 //Check if its a branch, and remove to handle special
Tanya Lattnera6820d62004-05-08 16:12:10 +00001334 if(!found) {
Tanya Lattner13417b52005-03-23 01:47:20 +00001335 if((*N)->isBranch() && !(*N)->hasPredecessors()) {
Tanya Lattnerd8cc4fa2004-11-29 04:39:47 +00001336 branches.push_back(*N);
Tanya Lattner13c71ca2004-11-24 01:49:10 +00001337 }
1338 else
1339 new_recurrence.insert(*N);
Tanya Lattnera31ad512005-02-23 02:01:42 +00001340 }
1341
Tanya Lattnera6820d62004-05-08 16:12:10 +00001342 }
Misha Brukmanb4402432005-04-21 23:30:14 +00001343
Tanya Lattnera31ad512005-02-23 02:01:42 +00001344
1345 if(new_recurrence.size() > 0) {
Misha Brukmanb4402432005-04-21 23:30:14 +00001346
Tanya Lattnera31ad512005-02-23 02:01:42 +00001347 std::vector<MSchedGraphNode*> path;
1348 std::set<MSchedGraphNode*> nodesToAdd;
1349
Tanya Lattner42ed1482005-04-22 06:32:48 +00001350 //Dump recc we are dealing with (minus nodes already in PO)
1351 DEBUG(std::cerr << "Recc: ");
1352 DEBUG(for(std::set<MSchedGraphNode*>::iterator R = new_recurrence.begin(), RE = new_recurrence.end(); R != RE; ++R) { std::cerr << **R ; });
1353
Tanya Lattnera31ad512005-02-23 02:01:42 +00001354 //Add nodes that connect this recurrence to recurrences in the partial path
1355 for(std::set<MSchedGraphNode*>::iterator N = new_recurrence.begin(),
Tanya Lattner13417b52005-03-23 01:47:20 +00001356 NE = new_recurrence.end(); N != NE; ++N)
Tanya Lattner4d0ee752005-04-30 23:07:59 +00001357 searchPath(*N, path, nodesToAdd, new_recurrence);
Misha Brukmanb4402432005-04-21 23:30:14 +00001358
Tanya Lattnera31ad512005-02-23 02:01:42 +00001359 //Add nodes to this recurrence if they are not already in the partial order
1360 for(std::set<MSchedGraphNode*>::iterator N = nodesToAdd.begin(), NE = nodesToAdd.end();
1361 N != NE; ++N) {
1362 bool found = false;
Misha Brukmanb4402432005-04-21 23:30:14 +00001363 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(),
Tanya Lattnera31ad512005-02-23 02:01:42 +00001364 PE = partialOrder.end(); PO != PE; ++PO) {
1365 if(PO->count(*N))
1366 found = true;
1367 }
1368 if(!found) {
1369 assert("FOUND CONNECTOR");
1370 new_recurrence.insert(*N);
1371 }
1372 }
1373
Tanya Lattnera6820d62004-05-08 16:12:10 +00001374 partialOrder.push_back(new_recurrence);
Tanya Lattnera31ad512005-02-23 02:01:42 +00001375
Tanya Lattner42ed1482005-04-22 06:32:48 +00001376
1377 //Dump out partial order
1378 DEBUG(for(std::vector<std::set<MSchedGraphNode*> >::iterator I = partialOrder.begin(),
1379 E = partialOrder.end(); I !=E; ++I) {
1380 std::cerr << "Start set in PO\n";
1381 for(std::set<MSchedGraphNode*>::iterator J = I->begin(), JE = I->end(); J != JE; ++J)
1382 std::cerr << "PO:" << **J << "\n";
1383 });
1384
Tanya Lattnera31ad512005-02-23 02:01:42 +00001385 }
Tanya Lattnera6820d62004-05-08 16:12:10 +00001386 }
Misha Brukmanb4402432005-04-21 23:30:14 +00001387
Tanya Lattnera6820d62004-05-08 16:12:10 +00001388 //Add any nodes that are not already in the partial order
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001389 //Add them in a set, one set per connected component
1390 std::set<MSchedGraphNode*> lastNodes;
Tanya Lattner13417b52005-03-23 01:47:20 +00001391 std::set<MSchedGraphNode*> noPredNodes;
Misha Brukmanb4402432005-04-21 23:30:14 +00001392 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(),
Tanya Lattnera31ad512005-02-23 02:01:42 +00001393 E = nodeToAttributesMap.end(); I != E; ++I) {
Misha Brukmanb4402432005-04-21 23:30:14 +00001394
Tanya Lattnera6820d62004-05-08 16:12:10 +00001395 bool found = false;
Misha Brukmanb4402432005-04-21 23:30:14 +00001396
Tanya Lattnera6820d62004-05-08 16:12:10 +00001397 //Check if its already in our partial order, if not add it to the final vector
Misha Brukmanb4402432005-04-21 23:30:14 +00001398 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(),
Tanya Lattnera31ad512005-02-23 02:01:42 +00001399 PE = partialOrder.end(); PO != PE; ++PO) {
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001400 if(PO->count(I->first))
Tanya Lattnera6820d62004-05-08 16:12:10 +00001401 found = true;
1402 }
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00001403 if(!found)
1404 lastNodes.insert(I->first);
Tanya Lattnera6820d62004-05-08 16:12:10 +00001405 }
1406
Tanya Lattner13417b52005-03-23 01:47:20 +00001407 //For each node w/out preds, see if there is a path to one of the
1408 //recurrences, and if so add them to that current recc
1409 /*for(std::set<MSchedGraphNode*>::iterator N = noPredNodes.begin(), NE = noPredNodes.end();
1410 N != NE; ++N) {
1411 DEBUG(std::cerr << "No Pred Path from: " << **N << "\n");
Misha Brukmanb4402432005-04-21 23:30:14 +00001412 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(),
Tanya Lattner13417b52005-03-23 01:47:20 +00001413 PE = partialOrder.end(); PO != PE; ++PO) {
1414 std::vector<MSchedGraphNode*> path;
1415 pathToRecc(*N, path, *PO, lastNodes);
1416 }
1417 }*/
Misha Brukmanb4402432005-04-21 23:30:14 +00001418
Tanya Lattner13417b52005-03-23 01:47:20 +00001419
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001420 //Break up remaining nodes that are not in the partial order
Tanya Lattner13417b52005-03-23 01:47:20 +00001421 ///into their connected compoenents
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00001422 while(lastNodes.size() > 0) {
Tanya Lattner13417b52005-03-23 01:47:20 +00001423 std::set<MSchedGraphNode*> ccSet;
1424 connectedComponentSet(*(lastNodes.begin()),ccSet, lastNodes);
1425 if(ccSet.size() > 0)
1426 partialOrder.push_back(ccSet);
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00001427 }
Misha Brukmanb4402432005-04-21 23:30:14 +00001428
1429
Tanya Lattner13c71ca2004-11-24 01:49:10 +00001430 //Clean up branches by putting them in final order
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00001431 assert(branches.size() == 0 && "We should not have any branches in our graph");
Tanya Lattnera6820d62004-05-08 16:12:10 +00001432}
1433
1434
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001435void ModuloSchedulingPass::connectedComponentSet(MSchedGraphNode *node, std::set<MSchedGraphNode*> &ccSet, std::set<MSchedGraphNode*> &lastNodes) {
1436
Tanya Lattner13c71ca2004-11-24 01:49:10 +00001437//Add to final set
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00001438 if( !ccSet.count(node) && lastNodes.count(node)) {
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001439 lastNodes.erase(node);
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00001440 ccSet.insert(node);
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001441 }
1442 else
1443 return;
Misha Brukmanb4402432005-04-21 23:30:14 +00001444
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001445 //Loop over successors and recurse if we have not seen this node before
1446 for(MSchedGraphNode::succ_iterator node_succ = node->succ_begin(), end=node->succ_end(); node_succ != end; ++node_succ) {
1447 connectedComponentSet(*node_succ, ccSet, lastNodes);
1448 }
Misha Brukmanb4402432005-04-21 23:30:14 +00001449
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001450}
1451
1452void ModuloSchedulingPass::predIntersect(std::set<MSchedGraphNode*> &CurrentSet, std::set<MSchedGraphNode*> &IntersectResult) {
Misha Brukmanb4402432005-04-21 23:30:14 +00001453
Tanya Lattnera6820d62004-05-08 16:12:10 +00001454 for(unsigned j=0; j < FinalNodeOrder.size(); ++j) {
Misha Brukmanb4402432005-04-21 23:30:14 +00001455 for(MSchedGraphNode::pred_iterator P = FinalNodeOrder[j]->pred_begin(),
Tanya Lattnera6820d62004-05-08 16:12:10 +00001456 E = FinalNodeOrder[j]->pred_end(); P != E; ++P) {
Misha Brukmanb4402432005-04-21 23:30:14 +00001457
Tanya Lattnera6820d62004-05-08 16:12:10 +00001458 //Check if we are supposed to ignore this edge or not
1459 if(ignoreEdge(*P,FinalNodeOrder[j]))
1460 continue;
Misha Brukmanb4402432005-04-21 23:30:14 +00001461
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001462 if(CurrentSet.count(*P))
Alkis Evlogimenos20f1b0b2004-09-28 14:42:44 +00001463 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), *P) == FinalNodeOrder.end())
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001464 IntersectResult.insert(*P);
Tanya Lattnera6820d62004-05-08 16:12:10 +00001465 }
Misha Brukmanb4402432005-04-21 23:30:14 +00001466 }
Tanya Lattnera6820d62004-05-08 16:12:10 +00001467}
1468
Tanya Lattnera6820d62004-05-08 16:12:10 +00001469
Misha Brukmanb4402432005-04-21 23:30:14 +00001470
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001471
1472
1473void ModuloSchedulingPass::succIntersect(std::set<MSchedGraphNode*> &CurrentSet, std::set<MSchedGraphNode*> &IntersectResult) {
1474
Tanya Lattnera6820d62004-05-08 16:12:10 +00001475 for(unsigned j=0; j < FinalNodeOrder.size(); ++j) {
Misha Brukmanb4402432005-04-21 23:30:14 +00001476 for(MSchedGraphNode::succ_iterator P = FinalNodeOrder[j]->succ_begin(),
Tanya Lattnera6820d62004-05-08 16:12:10 +00001477 E = FinalNodeOrder[j]->succ_end(); P != E; ++P) {
1478
1479 //Check if we are supposed to ignore this edge or not
1480 if(ignoreEdge(FinalNodeOrder[j],*P))
1481 continue;
1482
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001483 if(CurrentSet.count(*P))
Alkis Evlogimenos20f1b0b2004-09-28 14:42:44 +00001484 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), *P) == FinalNodeOrder.end())
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001485 IntersectResult.insert(*P);
Tanya Lattnera6820d62004-05-08 16:12:10 +00001486 }
1487 }
1488}
1489
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001490void dumpIntersection(std::set<MSchedGraphNode*> &IntersectCurrent) {
Tanya Lattnera6820d62004-05-08 16:12:10 +00001491 std::cerr << "Intersection (";
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001492 for(std::set<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(), E = IntersectCurrent.end(); I != E; ++I)
Tanya Lattnera6820d62004-05-08 16:12:10 +00001493 std::cerr << **I << ", ";
1494 std::cerr << ")\n";
1495}
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001496
1497
1498
1499void ModuloSchedulingPass::orderNodes() {
Misha Brukmanb4402432005-04-21 23:30:14 +00001500
Tanya Lattner56807c62005-02-10 17:02:58 +00001501 TIME_REGION(X, "orderNodes");
1502
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001503 int BOTTOM_UP = 0;
1504 int TOP_DOWN = 1;
1505
Tanya Lattnera6820d62004-05-08 16:12:10 +00001506 //Set default order
1507 int order = BOTTOM_UP;
1508
Misha Brukmanb4402432005-04-21 23:30:14 +00001509
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001510 //Loop over all the sets and place them in the final node order
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001511 for(std::vector<std::set<MSchedGraphNode*> >::iterator CurrentSet = partialOrder.begin(), E= partialOrder.end(); CurrentSet != E; ++CurrentSet) {
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001512
Tanya Lattnera6820d62004-05-08 16:12:10 +00001513 DEBUG(std::cerr << "Processing set in S\n");
Tanya Lattner081fbd12004-07-30 23:36:10 +00001514 DEBUG(dumpIntersection(*CurrentSet));
1515
Tanya Lattnera6820d62004-05-08 16:12:10 +00001516 //Result of intersection
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001517 std::set<MSchedGraphNode*> IntersectCurrent;
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001518
Tanya Lattnera6820d62004-05-08 16:12:10 +00001519 predIntersect(*CurrentSet, IntersectCurrent);
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001520
1521 //If the intersection of predecessor and current set is not empty
1522 //sort nodes bottom up
Tanya Lattnera6820d62004-05-08 16:12:10 +00001523 if(IntersectCurrent.size() != 0) {
1524 DEBUG(std::cerr << "Final Node Order Predecessors and Current Set interesection is NOT empty\n");
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001525 order = BOTTOM_UP;
Tanya Lattnera6820d62004-05-08 16:12:10 +00001526 }
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001527 //If empty, use successors
1528 else {
Tanya Lattnera6820d62004-05-08 16:12:10 +00001529 DEBUG(std::cerr << "Final Node Order Predecessors and Current Set interesection is empty\n");
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001530
Tanya Lattnera6820d62004-05-08 16:12:10 +00001531 succIntersect(*CurrentSet, IntersectCurrent);
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001532
1533 //sort top-down
Tanya Lattnera6820d62004-05-08 16:12:10 +00001534 if(IntersectCurrent.size() != 0) {
1535 DEBUG(std::cerr << "Final Node Order Successors and Current Set interesection is NOT empty\n");
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001536 order = TOP_DOWN;
Tanya Lattnera6820d62004-05-08 16:12:10 +00001537 }
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001538 else {
Tanya Lattnera6820d62004-05-08 16:12:10 +00001539 DEBUG(std::cerr << "Final Node Order Successors and Current Set interesection is empty\n");
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001540 //Find node with max ASAP in current Set
1541 MSchedGraphNode *node;
1542 int maxASAP = 0;
Tanya Lattnera6820d62004-05-08 16:12:10 +00001543 DEBUG(std::cerr << "Using current set of size " << CurrentSet->size() << "to find max ASAP\n");
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001544 for(std::set<MSchedGraphNode*>::iterator J = CurrentSet->begin(), JE = CurrentSet->end(); J != JE; ++J) {
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001545 //Get node attributes
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001546 MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*J)->second;
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001547 //assert(nodeAttr != nodeToAttributesMap.end() && "Node not in attributes map!");
Misha Brukmanb4402432005-04-21 23:30:14 +00001548
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001549 if(maxASAP <= nodeAttr.ASAP) {
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001550 maxASAP = nodeAttr.ASAP;
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001551 node = *J;
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001552 }
1553 }
Tanya Lattnera6820d62004-05-08 16:12:10 +00001554 assert(node != 0 && "In node ordering node should not be null");
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001555 IntersectCurrent.insert(node);
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001556 order = BOTTOM_UP;
1557 }
1558 }
Misha Brukmanb4402432005-04-21 23:30:14 +00001559
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001560 //Repeat until all nodes are put into the final order from current set
Tanya Lattnera6820d62004-05-08 16:12:10 +00001561 while(IntersectCurrent.size() > 0) {
1562
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001563 if(order == TOP_DOWN) {
Tanya Lattnera6820d62004-05-08 16:12:10 +00001564 DEBUG(std::cerr << "Order is TOP DOWN\n");
1565
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001566 while(IntersectCurrent.size() > 0) {
Tanya Lattnera6820d62004-05-08 16:12:10 +00001567 DEBUG(std::cerr << "Intersection is not empty, so find heighest height\n");
Misha Brukmanb4402432005-04-21 23:30:14 +00001568
Tanya Lattnera6820d62004-05-08 16:12:10 +00001569 int MOB = 0;
1570 int height = 0;
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001571 MSchedGraphNode *highestHeightNode = *(IntersectCurrent.begin());
Misha Brukmanb4402432005-04-21 23:30:14 +00001572
Tanya Lattnera6820d62004-05-08 16:12:10 +00001573 //Find node in intersection with highest heigh and lowest MOB
Misha Brukmanb4402432005-04-21 23:30:14 +00001574 for(std::set<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(),
Tanya Lattnera6820d62004-05-08 16:12:10 +00001575 E = IntersectCurrent.end(); I != E; ++I) {
Misha Brukmanb4402432005-04-21 23:30:14 +00001576
Tanya Lattnera6820d62004-05-08 16:12:10 +00001577 //Get current nodes properties
1578 MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*I)->second;
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001579
Tanya Lattnera6820d62004-05-08 16:12:10 +00001580 if(height < nodeAttr.height) {
1581 highestHeightNode = *I;
1582 height = nodeAttr.height;
1583 MOB = nodeAttr.MOB;
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001584 }
Tanya Lattnera6820d62004-05-08 16:12:10 +00001585 else if(height == nodeAttr.height) {
1586 if(MOB > nodeAttr.height) {
1587 highestHeightNode = *I;
1588 height = nodeAttr.height;
1589 MOB = nodeAttr.MOB;
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001590 }
1591 }
1592 }
Misha Brukmanb4402432005-04-21 23:30:14 +00001593
Tanya Lattnera6820d62004-05-08 16:12:10 +00001594 //Append our node with greatest height to the NodeOrder
Alkis Evlogimenos20f1b0b2004-09-28 14:42:44 +00001595 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), highestHeightNode) == FinalNodeOrder.end()) {
Tanya Lattnera6820d62004-05-08 16:12:10 +00001596 DEBUG(std::cerr << "Adding node to Final Order: " << *highestHeightNode << "\n");
1597 FinalNodeOrder.push_back(highestHeightNode);
1598 }
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001599
1600 //Remove V from IntersectOrder
Misha Brukmanb4402432005-04-21 23:30:14 +00001601 IntersectCurrent.erase(std::find(IntersectCurrent.begin(),
Tanya Lattnera6820d62004-05-08 16:12:10 +00001602 IntersectCurrent.end(), highestHeightNode));
1603
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001604
1605 //Intersect V's successors with CurrentSet
Tanya Lattnera6820d62004-05-08 16:12:10 +00001606 for(MSchedGraphNode::succ_iterator P = highestHeightNode->succ_begin(),
1607 E = highestHeightNode->succ_end(); P != E; ++P) {
Misha Brukmanb4402432005-04-21 23:30:14 +00001608 //if(lower_bound(CurrentSet->begin(),
Tanya Lattnera6820d62004-05-08 16:12:10 +00001609 // CurrentSet->end(), *P) != CurrentSet->end()) {
Misha Brukmanb4402432005-04-21 23:30:14 +00001610 if(std::find(CurrentSet->begin(), CurrentSet->end(), *P) != CurrentSet->end()) {
Tanya Lattnera6820d62004-05-08 16:12:10 +00001611 if(ignoreEdge(highestHeightNode, *P))
1612 continue;
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001613 //If not already in Intersect, add
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001614 if(!IntersectCurrent.count(*P))
1615 IntersectCurrent.insert(*P);
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001616 }
1617 }
1618 } //End while loop over Intersect Size
1619
1620 //Change direction
1621 order = BOTTOM_UP;
1622
1623 //Reset Intersect to reflect changes in OrderNodes
1624 IntersectCurrent.clear();
Tanya Lattnera6820d62004-05-08 16:12:10 +00001625 predIntersect(*CurrentSet, IntersectCurrent);
1626
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001627 } //End If TOP_DOWN
1628
1629 //Begin if BOTTOM_UP
Tanya Lattnera6820d62004-05-08 16:12:10 +00001630 else {
1631 DEBUG(std::cerr << "Order is BOTTOM UP\n");
1632 while(IntersectCurrent.size() > 0) {
1633 DEBUG(std::cerr << "Intersection of size " << IntersectCurrent.size() << ", finding highest depth\n");
1634
1635 //dump intersection
1636 DEBUG(dumpIntersection(IntersectCurrent));
1637 //Get node with highest depth, if a tie, use one with lowest
1638 //MOB
1639 int MOB = 0;
1640 int depth = 0;
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001641 MSchedGraphNode *highestDepthNode = *(IntersectCurrent.begin());
Misha Brukmanb4402432005-04-21 23:30:14 +00001642
1643 for(std::set<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(),
Tanya Lattnera6820d62004-05-08 16:12:10 +00001644 E = IntersectCurrent.end(); I != E; ++I) {
1645 //Find node attribute in graph
1646 MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*I)->second;
Misha Brukmanb4402432005-04-21 23:30:14 +00001647
Tanya Lattnera6820d62004-05-08 16:12:10 +00001648 if(depth < nodeAttr.depth) {
1649 highestDepthNode = *I;
1650 depth = nodeAttr.depth;
1651 MOB = nodeAttr.MOB;
1652 }
1653 else if(depth == nodeAttr.depth) {
1654 if(MOB > nodeAttr.MOB) {
1655 highestDepthNode = *I;
1656 depth = nodeAttr.depth;
1657 MOB = nodeAttr.MOB;
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001658 }
1659 }
Tanya Lattnera6820d62004-05-08 16:12:10 +00001660 }
Misha Brukmanb4402432005-04-21 23:30:14 +00001661
1662
Tanya Lattnera6820d62004-05-08 16:12:10 +00001663
1664 //Append highest depth node to the NodeOrder
Alkis Evlogimenos20f1b0b2004-09-28 14:42:44 +00001665 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), highestDepthNode) == FinalNodeOrder.end()) {
Tanya Lattnera6820d62004-05-08 16:12:10 +00001666 DEBUG(std::cerr << "Adding node to Final Order: " << *highestDepthNode << "\n");
1667 FinalNodeOrder.push_back(highestDepthNode);
1668 }
1669 //Remove heightestDepthNode from IntersectOrder
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001670 IntersectCurrent.erase(highestDepthNode);
Misha Brukmanb4402432005-04-21 23:30:14 +00001671
Tanya Lattnera6820d62004-05-08 16:12:10 +00001672
1673 //Intersect heightDepthNode's pred with CurrentSet
Misha Brukmanb4402432005-04-21 23:30:14 +00001674 for(MSchedGraphNode::pred_iterator P = highestDepthNode->pred_begin(),
Tanya Lattnera6820d62004-05-08 16:12:10 +00001675 E = highestDepthNode->pred_end(); P != E; ++P) {
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001676 if(CurrentSet->count(*P)) {
Tanya Lattnera6820d62004-05-08 16:12:10 +00001677 if(ignoreEdge(*P, highestDepthNode))
1678 continue;
Misha Brukmanb4402432005-04-21 23:30:14 +00001679
Tanya Lattnera6820d62004-05-08 16:12:10 +00001680 //If not already in Intersect, add
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001681 if(!IntersectCurrent.count(*P))
1682 IntersectCurrent.insert(*P);
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001683 }
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001684 }
Misha Brukmanb4402432005-04-21 23:30:14 +00001685
Tanya Lattnera6820d62004-05-08 16:12:10 +00001686 } //End while loop over Intersect Size
1687
1688 //Change order
1689 order = TOP_DOWN;
1690
1691 //Reset IntersectCurrent to reflect changes in OrderNodes
1692 IntersectCurrent.clear();
1693 succIntersect(*CurrentSet, IntersectCurrent);
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001694 } //End if BOTTOM_DOWN
1695
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00001696 DEBUG(std::cerr << "Current Intersection Size: " << IntersectCurrent.size() << "\n");
Tanya Lattnera6820d62004-05-08 16:12:10 +00001697 }
1698 //End Wrapping while loop
Misha Brukmanb4402432005-04-21 23:30:14 +00001699 DEBUG(std::cerr << "Ending Size of Current Set: " << CurrentSet->size() << "\n");
Tanya Lattnera6820d62004-05-08 16:12:10 +00001700 }//End for over all sets of nodes
Misha Brukmanb4402432005-04-21 23:30:14 +00001701
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00001702 //FIXME: As the algorithm stands it will NEVER add an instruction such as ba (with no
1703 //data dependencies) to the final order. We add this manually. It will always be
1704 //in the last set of S since its not part of a recurrence
1705 //Loop over all the sets and place them in the final node order
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001706 std::vector<std::set<MSchedGraphNode*> > ::reverse_iterator LastSet = partialOrder.rbegin();
1707 for(std::set<MSchedGraphNode*>::iterator CurrentNode = LastSet->begin(), LastNode = LastSet->end();
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00001708 CurrentNode != LastNode; ++CurrentNode) {
1709 if((*CurrentNode)->getInst()->getOpcode() == V9::BA)
1710 FinalNodeOrder.push_back(*CurrentNode);
1711 }
Tanya Lattnera6820d62004-05-08 16:12:10 +00001712 //Return final Order
1713 //return FinalNodeOrder;
1714}
1715
Tanya Lattner42ed1482005-04-22 06:32:48 +00001716bool ModuloSchedulingPass::computeSchedule(const MachineBasicBlock *BB, MSchedGraph *MSG) {
Tanya Lattnera6820d62004-05-08 16:12:10 +00001717
Tanya Lattner56807c62005-02-10 17:02:58 +00001718 TIME_REGION(X, "computeSchedule");
1719
Tanya Lattnera6820d62004-05-08 16:12:10 +00001720 bool success = false;
Misha Brukmanb4402432005-04-21 23:30:14 +00001721
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001722 //FIXME: Should be set to max II of the original loop
1723 //Cap II in order to prevent infinite loop
Tanya Lattner42ed1482005-04-22 06:32:48 +00001724 int capII = MSG->totalDelay();
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001725
Tanya Lattnera6820d62004-05-08 16:12:10 +00001726 while(!success) {
Tanya Lattnerd8cc4fa2004-11-29 04:39:47 +00001727
Tanya Lattnera31ad512005-02-23 02:01:42 +00001728 //Keep track of branches, but do not insert into the schedule
1729 std::vector<MSchedGraphNode*> branches;
Tanya Lattnerd8cc4fa2004-11-29 04:39:47 +00001730
Tanya Lattnera6820d62004-05-08 16:12:10 +00001731 //Loop over the final node order and process each node
Misha Brukmanb4402432005-04-21 23:30:14 +00001732 for(std::vector<MSchedGraphNode*>::iterator I = FinalNodeOrder.begin(),
Tanya Lattnera6820d62004-05-08 16:12:10 +00001733 E = FinalNodeOrder.end(); I != E; ++I) {
Misha Brukmanb4402432005-04-21 23:30:14 +00001734
Tanya Lattnera6820d62004-05-08 16:12:10 +00001735 //CalculateEarly and Late start
Tanya Lattner4d0ee752005-04-30 23:07:59 +00001736 bool initialLSVal = false;
1737 bool initialESVal = false;
1738 int EarlyStart = 0;
1739 int LateStart = 0;
Tanya Lattnera6820d62004-05-08 16:12:10 +00001740 bool hasSucc = false;
1741 bool hasPred = false;
Tanya Lattner13417b52005-03-23 01:47:20 +00001742 bool sched;
1743
1744 if((*I)->isBranch())
1745 if((*I)->hasPredecessors())
1746 sched = true;
1747 else
1748 sched = false;
1749 else
1750 sched = true;
1751
1752 if(sched) {
Tanya Lattnera066df62004-05-26 06:27:18 +00001753 //Loop over nodes in the schedule and determine if they are predecessors
1754 //or successors of the node we are trying to schedule
Misha Brukmanb4402432005-04-21 23:30:14 +00001755 for(MSSchedule::schedule_iterator nodesByCycle = schedule.begin(), nodesByCycleEnd = schedule.end();
Tanya Lattnera066df62004-05-26 06:27:18 +00001756 nodesByCycle != nodesByCycleEnd; ++nodesByCycle) {
Misha Brukmanb4402432005-04-21 23:30:14 +00001757
Tanya Lattnera066df62004-05-26 06:27:18 +00001758 //For this cycle, get the vector of nodes schedule and loop over it
1759 for(std::vector<MSchedGraphNode*>::iterator schedNode = nodesByCycle->second.begin(), SNE = nodesByCycle->second.end(); schedNode != SNE; ++schedNode) {
Misha Brukmanb4402432005-04-21 23:30:14 +00001760
Tanya Lattnera066df62004-05-26 06:27:18 +00001761 if((*I)->isPredecessor(*schedNode)) {
Tanya Lattnera31ad512005-02-23 02:01:42 +00001762 int diff = (*I)->getInEdge(*schedNode).getIteDiff();
1763 int ES_Temp = nodesByCycle->first + (*schedNode)->getLatency() - diff * II;
1764 DEBUG(std::cerr << "Diff: " << diff << " Cycle: " << nodesByCycle->first << "\n");
1765 DEBUG(std::cerr << "Temp EarlyStart: " << ES_Temp << " Prev EarlyStart: " << EarlyStart << "\n");
Tanya Lattner4d0ee752005-04-30 23:07:59 +00001766 if(initialESVal)
1767 EarlyStart = std::max(EarlyStart, ES_Temp);
1768 else {
1769 EarlyStart = ES_Temp;
1770 initialESVal = true;
1771 }
Tanya Lattnera31ad512005-02-23 02:01:42 +00001772 hasPred = true;
Tanya Lattnera6820d62004-05-08 16:12:10 +00001773 }
Tanya Lattnera066df62004-05-26 06:27:18 +00001774 if((*I)->isSuccessor(*schedNode)) {
Tanya Lattnera31ad512005-02-23 02:01:42 +00001775 int diff = (*schedNode)->getInEdge(*I).getIteDiff();
1776 int LS_Temp = nodesByCycle->first - (*I)->getLatency() + diff * II;
1777 DEBUG(std::cerr << "Diff: " << diff << " Cycle: " << nodesByCycle->first << "\n");
1778 DEBUG(std::cerr << "Temp LateStart: " << LS_Temp << " Prev LateStart: " << LateStart << "\n");
Tanya Lattner4d0ee752005-04-30 23:07:59 +00001779 if(initialLSVal)
1780 LateStart = std::min(LateStart, LS_Temp);
1781 else {
1782 LateStart = LS_Temp;
1783 initialLSVal = true;
1784 }
Tanya Lattnera31ad512005-02-23 02:01:42 +00001785 hasSucc = true;
Tanya Lattnera6820d62004-05-08 16:12:10 +00001786 }
Tanya Lattnera6820d62004-05-08 16:12:10 +00001787 }
1788 }
1789 }
Tanya Lattnera066df62004-05-26 06:27:18 +00001790 else {
Tanya Lattnera31ad512005-02-23 02:01:42 +00001791 branches.push_back(*I);
1792 continue;
1793 }
1794
1795 //Check if this node is a pred or succ to a branch, and restrict its placement
1796 //even though the branch is not in the schedule
Tanya Lattner4d0ee752005-04-30 23:07:59 +00001797 /*int count = branches.size();
Tanya Lattnera31ad512005-02-23 02:01:42 +00001798 for(std::vector<MSchedGraphNode*>::iterator B = branches.begin(), BE = branches.end();
1799 B != BE; ++B) {
1800 if((*I)->isPredecessor(*B)) {
1801 int diff = (*I)->getInEdge(*B).getIteDiff();
Tanya Lattner13417b52005-03-23 01:47:20 +00001802 int ES_Temp = (II+count-1) + (*B)->getLatency() - diff * II;
1803 DEBUG(std::cerr << "Diff: " << diff << " Cycle: " << (II+count)-1 << "\n");
Tanya Lattnera31ad512005-02-23 02:01:42 +00001804 DEBUG(std::cerr << "Temp EarlyStart: " << ES_Temp << " Prev EarlyStart: " << EarlyStart << "\n");
1805 EarlyStart = std::max(EarlyStart, ES_Temp);
1806 hasPred = true;
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00001807 }
Tanya Lattnera31ad512005-02-23 02:01:42 +00001808
1809 if((*I)->isSuccessor(*B)) {
1810 int diff = (*B)->getInEdge(*I).getIteDiff();
Tanya Lattner13417b52005-03-23 01:47:20 +00001811 int LS_Temp = (II+count-1) - (*I)->getLatency() + diff * II;
1812 DEBUG(std::cerr << "Diff: " << diff << " Cycle: " << (II+count-1) << "\n");
Tanya Lattnera31ad512005-02-23 02:01:42 +00001813 DEBUG(std::cerr << "Temp LateStart: " << LS_Temp << " Prev LateStart: " << LateStart << "\n");
1814 LateStart = std::min(LateStart, LS_Temp);
1815 hasSucc = true;
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00001816 }
Tanya Lattnera31ad512005-02-23 02:01:42 +00001817
1818 count--;
Tanya Lattner4d0ee752005-04-30 23:07:59 +00001819 }*/
Misha Brukmanb4402432005-04-21 23:30:14 +00001820
Tanya Lattnera6820d62004-05-08 16:12:10 +00001821 //Check if the node has no pred or successors and set Early Start to its ASAP
1822 if(!hasSucc && !hasPred)
1823 EarlyStart = nodeToAttributesMap.find(*I)->second.ASAP;
Misha Brukmanb4402432005-04-21 23:30:14 +00001824
Tanya Lattnera31ad512005-02-23 02:01:42 +00001825 DEBUG(std::cerr << "Has Successors: " << hasSucc << ", Has Pred: " << hasPred << "\n");
1826 DEBUG(std::cerr << "EarlyStart: " << EarlyStart << ", LateStart: " << LateStart << "\n");
1827
Tanya Lattnera6820d62004-05-08 16:12:10 +00001828 //Now, try to schedule this node depending upon its pred and successor in the schedule
1829 //already
1830 if(!hasSucc && hasPred)
1831 success = scheduleNode(*I, EarlyStart, (EarlyStart + II -1));
1832 else if(!hasPred && hasSucc)
1833 success = scheduleNode(*I, LateStart, (LateStart - II +1));
Tanya Lattnerc227ad22005-01-18 04:15:41 +00001834 else if(hasPred && hasSucc) {
Tanya Lattnera31ad512005-02-23 02:01:42 +00001835 if(EarlyStart > LateStart) {
Tanya Lattner13417b52005-03-23 01:47:20 +00001836 success = false;
1837 //LateStart = EarlyStart;
Tanya Lattnera31ad512005-02-23 02:01:42 +00001838 DEBUG(std::cerr << "Early Start can not be later then the late start cycle, schedule fails\n");
1839 }
Tanya Lattner13417b52005-03-23 01:47:20 +00001840 else
1841 success = scheduleNode(*I, EarlyStart, std::min(LateStart, (EarlyStart + II -1)));
Tanya Lattnerc227ad22005-01-18 04:15:41 +00001842 }
Tanya Lattnera6820d62004-05-08 16:12:10 +00001843 else
1844 success = scheduleNode(*I, EarlyStart, EarlyStart + II - 1);
Misha Brukmanb4402432005-04-21 23:30:14 +00001845
Tanya Lattnera6820d62004-05-08 16:12:10 +00001846 if(!success) {
Tanya Lattner42ed1482005-04-22 06:32:48 +00001847 ++II;
Tanya Lattnera6820d62004-05-08 16:12:10 +00001848 schedule.clear();
1849 break;
1850 }
Misha Brukmanb4402432005-04-21 23:30:14 +00001851
Tanya Lattnera6820d62004-05-08 16:12:10 +00001852 }
Tanya Lattnera066df62004-05-26 06:27:18 +00001853
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001854 if(success) {
1855 DEBUG(std::cerr << "Constructing Schedule Kernel\n");
Tanya Lattner13417b52005-03-23 01:47:20 +00001856 success = schedule.constructKernel(II, branches, indVarInstrs[BB]);
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001857 DEBUG(std::cerr << "Done Constructing Schedule Kernel\n");
1858 if(!success) {
1859 ++II;
1860 schedule.clear();
1861 }
Tanya Lattner13417b52005-03-23 01:47:20 +00001862 DEBUG(std::cerr << "Final II: " << II << "\n");
Tanya Lattner42ed1482005-04-22 06:32:48 +00001863 FinalIISum += II;
Tanya Lattnera066df62004-05-26 06:27:18 +00001864 }
Misha Brukmanb4402432005-04-21 23:30:14 +00001865
Tanya Lattnera31ad512005-02-23 02:01:42 +00001866 if(II >= capII) {
1867 DEBUG(std::cerr << "Maximum II reached, giving up\n");
Tanya Lattner201e9722004-12-02 07:22:15 +00001868 return false;
Tanya Lattnera31ad512005-02-23 02:01:42 +00001869 }
Tanya Lattner201e9722004-12-02 07:22:15 +00001870
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001871 assert(II < capII && "The II should not exceed the original loop number of cycles");
Misha Brukmanb4402432005-04-21 23:30:14 +00001872 }
Tanya Lattner201e9722004-12-02 07:22:15 +00001873 return true;
Tanya Lattnera6820d62004-05-08 16:12:10 +00001874}
1875
1876
Misha Brukmanb4402432005-04-21 23:30:14 +00001877bool ModuloSchedulingPass::scheduleNode(MSchedGraphNode *node,
Tanya Lattnera6820d62004-05-08 16:12:10 +00001878 int start, int end) {
1879 bool success = false;
1880
1881 DEBUG(std::cerr << *node << " (Start Cycle: " << start << ", End Cycle: " << end << ")\n");
1882
Tanya Lattnera6820d62004-05-08 16:12:10 +00001883 //Make sure start and end are not negative
Tanya Lattner13417b52005-03-23 01:47:20 +00001884 //if(start < 0) {
1885 //start = 0;
Misha Brukmanb4402432005-04-21 23:30:14 +00001886
Tanya Lattner13417b52005-03-23 01:47:20 +00001887 //}
1888 //if(end < 0)
1889 //end = 0;
Tanya Lattnera6820d62004-05-08 16:12:10 +00001890
1891 bool forward = true;
1892 if(start > end)
1893 forward = false;
1894
Tanya Lattnera6820d62004-05-08 16:12:10 +00001895 bool increaseSC = true;
Tanya Lattnera6820d62004-05-08 16:12:10 +00001896 int cycle = start ;
1897
1898
1899 while(increaseSC) {
Misha Brukmanb4402432005-04-21 23:30:14 +00001900
Tanya Lattnera6820d62004-05-08 16:12:10 +00001901 increaseSC = false;
1902
Tanya Lattnera066df62004-05-26 06:27:18 +00001903 increaseSC = schedule.insert(node, cycle);
Misha Brukmanb4402432005-04-21 23:30:14 +00001904
1905 if(!increaseSC)
Tanya Lattnera6820d62004-05-08 16:12:10 +00001906 return true;
1907
1908 //Increment cycle to try again
1909 if(forward) {
1910 ++cycle;
1911 DEBUG(std::cerr << "Increase cycle: " << cycle << "\n");
1912 if(cycle > end)
1913 return false;
1914 }
1915 else {
1916 --cycle;
1917 DEBUG(std::cerr << "Decrease cycle: " << cycle << "\n");
1918 if(cycle < end)
1919 return false;
1920 }
1921 }
Tanya Lattnera066df62004-05-26 06:27:18 +00001922
Tanya Lattnera6820d62004-05-08 16:12:10 +00001923 return success;
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001924}
Tanya Lattnera066df62004-05-26 06:27:18 +00001925
Tanya Lattner13417b52005-03-23 01:47:20 +00001926void ModuloSchedulingPass::writePrologues(std::vector<MachineBasicBlock *> &prologues, MachineBasicBlock *origBB, std::vector<BasicBlock*> &llvm_prologues, std::map<const Value*, std::pair<const MachineInstr*, int> > &valuesToSave, std::map<Value*, std::map<int, Value*> > &newValues, std::map<Value*, MachineBasicBlock*> &newValLocation) {
Tanya Lattnera066df62004-05-26 06:27:18 +00001927
Tanya Lattner081fbd12004-07-30 23:36:10 +00001928 //Keep a map to easily know whats in the kernel
Tanya Lattnera066df62004-05-26 06:27:18 +00001929 std::map<int, std::set<const MachineInstr*> > inKernel;
1930 int maxStageCount = 0;
1931
Tanya Lattner201e9722004-12-02 07:22:15 +00001932 //Keep a map of new values we consumed in case they need to be added back
1933 std::map<Value*, std::map<int, Value*> > consumedValues;
1934
Tanya Lattner081fbd12004-07-30 23:36:10 +00001935 MSchedGraphNode *branch = 0;
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001936 MSchedGraphNode *BAbranch = 0;
Tanya Lattner081fbd12004-07-30 23:36:10 +00001937
Tanya Lattner91964492005-03-29 20:35:10 +00001938 DEBUG(schedule.print(std::cerr));
Tanya Lattnerab9cf272004-11-22 20:41:24 +00001939
Tanya Lattner201e9722004-12-02 07:22:15 +00001940 std::vector<MSchedGraphNode*> branches;
1941
Tanya Lattnera066df62004-05-26 06:27:18 +00001942 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
1943 maxStageCount = std::max(maxStageCount, I->second);
Misha Brukmanb4402432005-04-21 23:30:14 +00001944
Tanya Lattnera066df62004-05-26 06:27:18 +00001945 //Put int the map so we know what instructions in each stage are in the kernel
Tanya Lattner13417b52005-03-23 01:47:20 +00001946 DEBUG(std::cerr << "Inserting instruction " << *(I->first) << " into map at stage " << I->second << "\n");
1947 inKernel[I->second].insert(I->first);
Tanya Lattnera066df62004-05-26 06:27:18 +00001948 }
1949
Tanya Lattner081fbd12004-07-30 23:36:10 +00001950 //Get target information to look at machine operands
1951 const TargetInstrInfo *mii = target.getInstrInfo();
1952
1953 //Now write the prologues
1954 for(int i = 0; i < maxStageCount; ++i) {
1955 BasicBlock *llvmBB = new BasicBlock("PROLOGUE", (Function*) (origBB->getBasicBlock()->getParent()));
Tanya Lattnera066df62004-05-26 06:27:18 +00001956 MachineBasicBlock *machineBB = new MachineBasicBlock(llvmBB);
Misha Brukmanb4402432005-04-21 23:30:14 +00001957
Tanya Lattner081fbd12004-07-30 23:36:10 +00001958 DEBUG(std::cerr << "i=" << i << "\n");
Tanya Lattner13417b52005-03-23 01:47:20 +00001959 for(int j = i; j >= 0; --j) {
Tanya Lattner081fbd12004-07-30 23:36:10 +00001960 for(MachineBasicBlock::const_iterator MI = origBB->begin(), ME = origBB->end(); ME != MI; ++MI) {
1961 if(inKernel[j].count(&*MI)) {
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00001962 MachineInstr *instClone = MI->clone();
1963 machineBB->push_back(instClone);
Tanya Lattner13417b52005-03-23 01:47:20 +00001964
1965 //If its a branch, insert a nop
1966 if(mii->isBranch(instClone->getOpcode()))
1967 BuildMI(machineBB, V9::NOP, 0);
Misha Brukmanb4402432005-04-21 23:30:14 +00001968
1969
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00001970 DEBUG(std::cerr << "Cloning: " << *MI << "\n");
1971
Tanya Lattner081fbd12004-07-30 23:36:10 +00001972 //After cloning, we may need to save the value that this instruction defines
1973 for(unsigned opNum=0; opNum < MI->getNumOperands(); ++opNum) {
Tanya Lattner13417b52005-03-23 01:47:20 +00001974 Instruction *tmp;
Misha Brukmanb4402432005-04-21 23:30:14 +00001975
Tanya Lattner081fbd12004-07-30 23:36:10 +00001976 //get machine operand
Tanya Lattner201e9722004-12-02 07:22:15 +00001977 MachineOperand &mOp = instClone->getOperand(opNum);
Tanya Lattner081fbd12004-07-30 23:36:10 +00001978 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef()) {
1979
Tanya Lattner081fbd12004-07-30 23:36:10 +00001980 //Check if this is a value we should save
1981 if(valuesToSave.count(mOp.getVRegValue())) {
1982 //Save copy in tmpInstruction
1983 tmp = new TmpInstruction(mOp.getVRegValue());
1984
Tanya Lattner444be612004-11-02 21:04:56 +00001985 //Add TmpInstruction to safe LLVM Instruction MCFI
1986 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnerd38a7602004-10-14 06:04:28 +00001987 tempMvec.addTemp((Value*) tmp);
1988
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00001989 DEBUG(std::cerr << "Value: " << *(mOp.getVRegValue()) << " New Value: " << *tmp << " Stage: " << i << "\n");
1990
1991 newValues[mOp.getVRegValue()][i]= tmp;
Tanya Lattner081fbd12004-07-30 23:36:10 +00001992 newValLocation[tmp] = machineBB;
1993
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00001994 DEBUG(std::cerr << "Machine Instr Operands: " << *(mOp.getVRegValue()) << ", 0, " << *tmp << "\n");
Tanya Lattner081fbd12004-07-30 23:36:10 +00001995
1996 //Create machine instruction and put int machineBB
Tanya Lattner13417b52005-03-23 01:47:20 +00001997 MachineInstr *saveValue;
1998 if(mOp.getVRegValue()->getType() == Type::FloatTy)
1999 saveValue = BuildMI(machineBB, V9::FMOVS, 3).addReg(mOp.getVRegValue()).addRegDef(tmp);
2000 else if(mOp.getVRegValue()->getType() == Type::DoubleTy)
2001 saveValue = BuildMI(machineBB, V9::FMOVD, 3).addReg(mOp.getVRegValue()).addRegDef(tmp);
Misha Brukmanb4402432005-04-21 23:30:14 +00002002 else
Tanya Lattner13417b52005-03-23 01:47:20 +00002003 saveValue = BuildMI(machineBB, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
2004
2005
Tanya Lattner081fbd12004-07-30 23:36:10 +00002006 DEBUG(std::cerr << "Created new machine instr: " << *saveValue << "\n");
2007 }
2008 }
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002009
2010 //We may also need to update the value that we use if its from an earlier prologue
2011 if(j != 0) {
2012 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse()) {
Tanya Lattner201e9722004-12-02 07:22:15 +00002013 if(newValues.count(mOp.getVRegValue())) {
2014 if(newValues[mOp.getVRegValue()].count(i-1)) {
2015 Value *oldV = mOp.getVRegValue();
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002016 DEBUG(std::cerr << "Replaced this value: " << mOp.getVRegValue() << " With:" << (newValues[mOp.getVRegValue()][i-1]) << "\n");
2017 //Update the operand with the right value
Tanya Lattner201e9722004-12-02 07:22:15 +00002018 mOp.setValueReg(newValues[mOp.getVRegValue()][i-1]);
2019
2020 //Remove this value since we have consumed it
2021 //NOTE: Should this only be done if j != maxStage?
2022 consumedValues[oldV][i-1] = (newValues[oldV][i-1]);
2023 DEBUG(std::cerr << "Deleted value: " << consumedValues[oldV][i-1] << "\n");
2024 newValues[oldV].erase(i-1);
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002025 }
Tanya Lattner201e9722004-12-02 07:22:15 +00002026 }
2027 else
2028 if(consumedValues.count(mOp.getVRegValue()))
2029 assert(!consumedValues[mOp.getVRegValue()].count(i-1) && "Found a case where we need the value");
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002030 }
2031 }
Tanya Lattner081fbd12004-07-30 23:36:10 +00002032 }
2033 }
Tanya Lattner50cbb9a2004-05-28 20:14:12 +00002034 }
Tanya Lattnera066df62004-05-26 06:27:18 +00002035 }
2036
Tanya Lattner081fbd12004-07-30 23:36:10 +00002037
Tanya Lattner13417b52005-03-23 01:47:20 +00002038 /*for(std::vector<MSchedGraphNode*>::iterator BR = branches.begin(), BE = branches.end(); BR != BE; ++BR) {
Misha Brukmanb4402432005-04-21 23:30:14 +00002039
Tanya Lattner201e9722004-12-02 07:22:15 +00002040 //Stick in branch at the end
2041 machineBB->push_back((*BR)->getInst()->clone());
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00002042
Tanya Lattner201e9722004-12-02 07:22:15 +00002043 //Add nop
2044 BuildMI(machineBB, V9::NOP, 0);
Tanya Lattner13417b52005-03-23 01:47:20 +00002045 }*/
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00002046
Tanya Lattner081fbd12004-07-30 23:36:10 +00002047
Misha Brukmanb4402432005-04-21 23:30:14 +00002048 (((MachineBasicBlock*)origBB)->getParent())->getBasicBlockList().push_back(machineBB);
Tanya Lattnera066df62004-05-26 06:27:18 +00002049 prologues.push_back(machineBB);
2050 llvm_prologues.push_back(llvmBB);
2051 }
2052}
2053
Tanya Lattner13417b52005-03-23 01:47:20 +00002054void ModuloSchedulingPass::writeEpilogues(std::vector<MachineBasicBlock *> &epilogues, const MachineBasicBlock *origBB, std::vector<BasicBlock*> &llvm_epilogues, std::map<const Value*, std::pair<const MachineInstr*, int> > &valuesToSave, std::map<Value*, std::map<int, Value*> > &newValues,std::map<Value*, MachineBasicBlock*> &newValLocation, std::map<Value*, std::map<int, Value*> > &kernelPHIs ) {
Misha Brukmanb4402432005-04-21 23:30:14 +00002055
Tanya Lattner50cbb9a2004-05-28 20:14:12 +00002056 std::map<int, std::set<const MachineInstr*> > inKernel;
Misha Brukmanb4402432005-04-21 23:30:14 +00002057
Tanya Lattner50cbb9a2004-05-28 20:14:12 +00002058 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
Misha Brukmanb4402432005-04-21 23:30:14 +00002059
Tanya Lattner50cbb9a2004-05-28 20:14:12 +00002060 //Ignore the branch, we will handle this separately
Tanya Lattner13417b52005-03-23 01:47:20 +00002061 //if(I->first->isBranch())
2062 //continue;
Tanya Lattner50cbb9a2004-05-28 20:14:12 +00002063
2064 //Put int the map so we know what instructions in each stage are in the kernel
Tanya Lattner13417b52005-03-23 01:47:20 +00002065 inKernel[I->second].insert(I->first);
Tanya Lattner50cbb9a2004-05-28 20:14:12 +00002066 }
2067
Tanya Lattner081fbd12004-07-30 23:36:10 +00002068 std::map<Value*, Value*> valPHIs;
2069
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002070 //some debug stuff, will remove later
2071 DEBUG(for(std::map<Value*, std::map<int, Value*> >::iterator V = newValues.begin(), E = newValues.end(); V !=E; ++V) {
2072 std::cerr << "Old Value: " << *(V->first) << "\n";
2073 for(std::map<int, Value*>::iterator I = V->second.begin(), IE = V->second.end(); I != IE; ++I)
2074 std::cerr << "Stage: " << I->first << " Value: " << *(I->second) << "\n";
2075 });
2076
2077 //some debug stuff, will remove later
2078 DEBUG(for(std::map<Value*, std::map<int, Value*> >::iterator V = kernelPHIs.begin(), E = kernelPHIs.end(); V !=E; ++V) {
2079 std::cerr << "Old Value: " << *(V->first) << "\n";
2080 for(std::map<int, Value*>::iterator I = V->second.begin(), IE = V->second.end(); I != IE; ++I)
2081 std::cerr << "Stage: " << I->first << " Value: " << *(I->second) << "\n";
2082 });
2083
Tanya Lattner50cbb9a2004-05-28 20:14:12 +00002084 //Now write the epilogues
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002085 for(int i = schedule.getMaxStage()-1; i >= 0; --i) {
Tanya Lattner081fbd12004-07-30 23:36:10 +00002086 BasicBlock *llvmBB = new BasicBlock("EPILOGUE", (Function*) (origBB->getBasicBlock()->getParent()));
Tanya Lattner50cbb9a2004-05-28 20:14:12 +00002087 MachineBasicBlock *machineBB = new MachineBasicBlock(llvmBB);
Misha Brukmanb4402432005-04-21 23:30:14 +00002088
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002089 DEBUG(std::cerr << " Epilogue #: " << i << "\n");
Tanya Lattner081fbd12004-07-30 23:36:10 +00002090
Tanya Lattner081fbd12004-07-30 23:36:10 +00002091
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002092 std::map<Value*, int> inEpilogue;
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002093
2094 for(MachineBasicBlock::const_iterator MI = origBB->begin(), ME = origBB->end(); ME != MI; ++MI) {
2095 for(int j=schedule.getMaxStage(); j > i; --j) {
Tanya Lattner081fbd12004-07-30 23:36:10 +00002096 if(inKernel[j].count(&*MI)) {
2097 DEBUG(std::cerr << "Cloning instruction " << *MI << "\n");
2098 MachineInstr *clone = MI->clone();
Misha Brukmanb4402432005-04-21 23:30:14 +00002099
Tanya Lattner081fbd12004-07-30 23:36:10 +00002100 //Update operands that need to use the result from the phi
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002101 for(unsigned opNum=0; opNum < clone->getNumOperands(); ++opNum) {
Tanya Lattner081fbd12004-07-30 23:36:10 +00002102 //get machine operand
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002103 const MachineOperand &mOp = clone->getOperand(opNum);
Misha Brukmanb4402432005-04-21 23:30:14 +00002104
Tanya Lattner081fbd12004-07-30 23:36:10 +00002105 if((mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse())) {
Misha Brukmanb4402432005-04-21 23:30:14 +00002106
Tanya Lattner13417b52005-03-23 01:47:20 +00002107 DEBUG(std::cerr << "Writing PHI for " << (mOp.getVRegValue()) << "\n");
Misha Brukmanb4402432005-04-21 23:30:14 +00002108
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002109 //If this is the last instructions for the max iterations ago, don't update operands
2110 if(inEpilogue.count(mOp.getVRegValue()))
2111 if(inEpilogue[mOp.getVRegValue()] == i)
2112 continue;
Misha Brukmanb4402432005-04-21 23:30:14 +00002113
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002114 //Quickly write appropriate phis for this operand
2115 if(newValues.count(mOp.getVRegValue())) {
2116 if(newValues[mOp.getVRegValue()].count(i)) {
2117 Instruction *tmp = new TmpInstruction(newValues[mOp.getVRegValue()][i]);
Misha Brukmanb4402432005-04-21 23:30:14 +00002118
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002119 //Get machine code for this instruction
Tanya Lattner444be612004-11-02 21:04:56 +00002120 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002121 tempMvec.addTemp((Value*) tmp);
2122
Tanya Lattner13417b52005-03-23 01:47:20 +00002123 //assert of no kernelPHI for this value
2124 assert(kernelPHIs[mOp.getVRegValue()][i] !=0 && "Must have final kernel phi to construct epilogue phi");
2125
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002126 MachineInstr *saveValue = BuildMI(machineBB, V9::PHI, 3).addReg(newValues[mOp.getVRegValue()][i]).addReg(kernelPHIs[mOp.getVRegValue()][i]).addRegDef(tmp);
2127 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
2128 valPHIs[mOp.getVRegValue()] = tmp;
2129 }
2130 }
Misha Brukmanb4402432005-04-21 23:30:14 +00002131
Tanya Lattner081fbd12004-07-30 23:36:10 +00002132 if(valPHIs.count(mOp.getVRegValue())) {
2133 //Update the operand in the cloned instruction
Misha Brukmanb4402432005-04-21 23:30:14 +00002134 clone->getOperand(opNum).setValueReg(valPHIs[mOp.getVRegValue()]);
Tanya Lattner081fbd12004-07-30 23:36:10 +00002135 }
2136 }
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002137 else if((mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef())) {
2138 inEpilogue[mOp.getVRegValue()] = i;
2139 }
Tanya Lattner081fbd12004-07-30 23:36:10 +00002140 }
2141 machineBB->push_back(clone);
2142 }
2143 }
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002144 }
Tanya Lattner081fbd12004-07-30 23:36:10 +00002145
Tanya Lattner50cbb9a2004-05-28 20:14:12 +00002146 (((MachineBasicBlock*)origBB)->getParent())->getBasicBlockList().push_back(machineBB);
2147 epilogues.push_back(machineBB);
2148 llvm_epilogues.push_back(llvmBB);
Misha Brukmanb4402432005-04-21 23:30:14 +00002149
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002150 DEBUG(std::cerr << "EPILOGUE #" << i << "\n");
2151 DEBUG(machineBB->print(std::cerr));
Tanya Lattner50cbb9a2004-05-28 20:14:12 +00002152 }
Tanya Lattner081fbd12004-07-30 23:36:10 +00002153}
2154
Tanya Lattner13417b52005-03-23 01:47:20 +00002155void ModuloSchedulingPass::writeKernel(BasicBlock *llvmBB, MachineBasicBlock *machineBB, std::map<const Value*, std::pair<const MachineInstr*, int> > &valuesToSave, std::map<Value*, std::map<int, Value*> > &newValues, std::map<Value*, MachineBasicBlock*> &newValLocation, std::map<Value*, std::map<int, Value*> > &kernelPHIs) {
Misha Brukmanb4402432005-04-21 23:30:14 +00002156
Tanya Lattner081fbd12004-07-30 23:36:10 +00002157 //Keep track of operands that are read and saved from a previous iteration. The new clone
2158 //instruction will use the result of the phi instead.
2159 std::map<Value*, Value*> finalPHIValue;
2160 std::map<Value*, Value*> kernelValue;
2161
Tanya Lattnerc0d9dcd2004-12-03 05:25:22 +00002162 //Branches are a special case
2163 std::vector<MachineInstr*> branches;
2164
Tanya Lattner13417b52005-03-23 01:47:20 +00002165 //Get target information to look at machine operands
2166 const TargetInstrInfo *mii = target.getInstrInfo();
Misha Brukmanb4402432005-04-21 23:30:14 +00002167
Tanya Lattner13417b52005-03-23 01:47:20 +00002168 //Create TmpInstructions for the final phis
2169 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
Tanya Lattner081fbd12004-07-30 23:36:10 +00002170
Tanya Lattner13417b52005-03-23 01:47:20 +00002171 DEBUG(std::cerr << "Stage: " << I->second << " Inst: " << *(I->first) << "\n";);
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002172
Tanya Lattner13417b52005-03-23 01:47:20 +00002173 /*if(I->first->isBranch()) {
Tanya Lattnerc0d9dcd2004-12-03 05:25:22 +00002174 //Clone instruction
2175 const MachineInstr *inst = I->first->getInst();
2176 MachineInstr *instClone = inst->clone();
2177 branches.push_back(instClone);
Tanya Lattnerc227ad22005-01-18 04:15:41 +00002178 continue;
Tanya Lattner13417b52005-03-23 01:47:20 +00002179 }*/
Misha Brukmanb4402432005-04-21 23:30:14 +00002180
Tanya Lattner081fbd12004-07-30 23:36:10 +00002181 //Clone instruction
Tanya Lattner13417b52005-03-23 01:47:20 +00002182 const MachineInstr *inst = I->first;
Tanya Lattner081fbd12004-07-30 23:36:10 +00002183 MachineInstr *instClone = inst->clone();
Tanya Lattner081fbd12004-07-30 23:36:10 +00002184
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002185 //Insert into machine basic block
2186 machineBB->push_back(instClone);
2187
Tanya Lattner13417b52005-03-23 01:47:20 +00002188 if(mii->isBranch(instClone->getOpcode()))
2189 BuildMI(machineBB, V9::NOP, 0);
2190
Tanya Lattner7beb51c2004-11-16 21:31:37 +00002191 DEBUG(std::cerr << "Cloned Inst: " << *instClone << "\n");
2192
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002193 //Loop over Machine Operands
2194 for(unsigned i=0; i < inst->getNumOperands(); ++i) {
2195 //get machine operand
2196 const MachineOperand &mOp = inst->getOperand(i);
Misha Brukmanb4402432005-04-21 23:30:14 +00002197
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002198 if(I->second != 0) {
Tanya Lattner081fbd12004-07-30 23:36:10 +00002199 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse()) {
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002200
2201 //Check to see where this operand is defined if this instruction is from max stage
2202 if(I->second == schedule.getMaxStage()) {
2203 DEBUG(std::cerr << "VREG: " << *(mOp.getVRegValue()) << "\n");
2204 }
2205
Tanya Lattner081fbd12004-07-30 23:36:10 +00002206 //If its in the value saved, we need to create a temp instruction and use that instead
2207 if(valuesToSave.count(mOp.getVRegValue())) {
Tanya Lattner7beb51c2004-11-16 21:31:37 +00002208
2209 //Check if we already have a final PHI value for this
2210 if(!finalPHIValue.count(mOp.getVRegValue())) {
2211 TmpInstruction *tmp = new TmpInstruction(mOp.getVRegValue());
Misha Brukmanb4402432005-04-21 23:30:14 +00002212
Tanya Lattner7beb51c2004-11-16 21:31:37 +00002213 //Get machine code for this instruction
2214 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
2215 tempMvec.addTemp((Value*) tmp);
Misha Brukmanb4402432005-04-21 23:30:14 +00002216
Tanya Lattner7beb51c2004-11-16 21:31:37 +00002217 //Update the operand in the cloned instruction
2218 instClone->getOperand(i).setValueReg(tmp);
Misha Brukmanb4402432005-04-21 23:30:14 +00002219
Tanya Lattner7beb51c2004-11-16 21:31:37 +00002220 //save this as our final phi
2221 finalPHIValue[mOp.getVRegValue()] = tmp;
2222 newValLocation[tmp] = machineBB;
2223 }
2224 else {
2225 //Use the previous final phi value
Misha Brukmanb4402432005-04-21 23:30:14 +00002226 instClone->getOperand(i).setValueReg(finalPHIValue[mOp.getVRegValue()]);
Tanya Lattner7beb51c2004-11-16 21:31:37 +00002227 }
Tanya Lattner081fbd12004-07-30 23:36:10 +00002228 }
2229 }
Tanya Lattner081fbd12004-07-30 23:36:10 +00002230 }
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002231 if(I->second != schedule.getMaxStage()) {
Tanya Lattner081fbd12004-07-30 23:36:10 +00002232 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef()) {
2233 if(valuesToSave.count(mOp.getVRegValue())) {
Misha Brukmanb4402432005-04-21 23:30:14 +00002234
Tanya Lattner081fbd12004-07-30 23:36:10 +00002235 TmpInstruction *tmp = new TmpInstruction(mOp.getVRegValue());
Misha Brukmanb4402432005-04-21 23:30:14 +00002236
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002237 //Get machine code for this instruction
Tanya Lattner444be612004-11-02 21:04:56 +00002238 MachineCodeForInstruction & tempVec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002239 tempVec.addTemp((Value*) tmp);
2240
Tanya Lattner081fbd12004-07-30 23:36:10 +00002241 //Create new machine instr and put in MBB
Tanya Lattner13417b52005-03-23 01:47:20 +00002242 MachineInstr *saveValue;
2243 if(mOp.getVRegValue()->getType() == Type::FloatTy)
2244 saveValue = BuildMI(machineBB, V9::FMOVS, 3).addReg(mOp.getVRegValue()).addRegDef(tmp);
2245 else if(mOp.getVRegValue()->getType() == Type::DoubleTy)
2246 saveValue = BuildMI(machineBB, V9::FMOVD, 3).addReg(mOp.getVRegValue()).addRegDef(tmp);
Misha Brukmanb4402432005-04-21 23:30:14 +00002247 else
Tanya Lattner13417b52005-03-23 01:47:20 +00002248 saveValue = BuildMI(machineBB, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
Misha Brukmanb4402432005-04-21 23:30:14 +00002249
2250
Tanya Lattner081fbd12004-07-30 23:36:10 +00002251 //Save for future cleanup
2252 kernelValue[mOp.getVRegValue()] = tmp;
2253 newValLocation[tmp] = machineBB;
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002254 kernelPHIs[mOp.getVRegValue()][schedule.getMaxStage()-1] = tmp;
Tanya Lattner081fbd12004-07-30 23:36:10 +00002255 }
2256 }
2257 }
2258 }
Misha Brukmanb4402432005-04-21 23:30:14 +00002259
Tanya Lattner081fbd12004-07-30 23:36:10 +00002260 }
2261
Tanya Lattnerc0d9dcd2004-12-03 05:25:22 +00002262 //Add branches
2263 for(std::vector<MachineInstr*>::iterator I = branches.begin(), E = branches.end(); I != E; ++I) {
2264 machineBB->push_back(*I);
2265 BuildMI(machineBB, V9::NOP, 0);
2266 }
2267
2268
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002269 DEBUG(std::cerr << "KERNEL before PHIs\n");
2270 DEBUG(machineBB->print(std::cerr));
2271
2272
2273 //Loop over each value we need to generate phis for
Misha Brukmanb4402432005-04-21 23:30:14 +00002274 for(std::map<Value*, std::map<int, Value*> >::iterator V = newValues.begin(),
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002275 E = newValues.end(); V != E; ++V) {
2276
Tanya Lattner081fbd12004-07-30 23:36:10 +00002277
2278 DEBUG(std::cerr << "Writing phi for" << *(V->first));
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002279 DEBUG(std::cerr << "\nMap of Value* for this phi\n");
Misha Brukmanb4402432005-04-21 23:30:14 +00002280 DEBUG(for(std::map<int, Value*>::iterator I = V->second.begin(),
2281 IE = V->second.end(); I != IE; ++I) {
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002282 std::cerr << "Stage: " << I->first;
2283 std::cerr << " Value: " << *(I->second) << "\n";
2284 });
Tanya Lattner081fbd12004-07-30 23:36:10 +00002285
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002286 //If we only have one current iteration live, its safe to set lastPhi = to kernel value
2287 if(V->second.size() == 1) {
2288 assert(kernelValue[V->first] != 0 && "Kernel value* must exist to create phi");
Misha Brukmanb4402432005-04-21 23:30:14 +00002289 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(),V9::PHI, 3).addReg(V->second.begin()->second).addReg(kernelValue[V->first]).addRegDef(finalPHIValue[V->first]);
Tanya Lattner13417b52005-03-23 01:47:20 +00002290 DEBUG(std::cerr << "Resulting PHI (one live): " << *saveValue << "\n");
2291 kernelPHIs[V->first][V->second.begin()->first] = kernelValue[V->first];
2292 DEBUG(std::cerr << "Put kernel phi in at stage: " << schedule.getMaxStage()-1 << " (map stage = " << V->second.begin()->first << ")\n");
2293 }
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002294 else {
2295
2296 //Keep track of last phi created.
2297 Instruction *lastPhi = 0;
Misha Brukmanb4402432005-04-21 23:30:14 +00002298
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002299 unsigned count = 1;
2300 //Loop over the the map backwards to generate phis
Misha Brukmanb4402432005-04-21 23:30:14 +00002301 for(std::map<int, Value*>::reverse_iterator I = V->second.rbegin(), IE = V->second.rend();
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002302 I != IE; ++I) {
2303
2304 if(count < (V->second).size()) {
2305 if(lastPhi == 0) {
2306 lastPhi = new TmpInstruction(I->second);
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002307
2308 //Get machine code for this instruction
Tanya Lattner444be612004-11-02 21:04:56 +00002309 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002310 tempMvec.addTemp((Value*) lastPhi);
2311
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002312 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(), V9::PHI, 3).addReg(kernelValue[V->first]).addReg(I->second).addRegDef(lastPhi);
2313 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
2314 newValLocation[lastPhi] = machineBB;
2315 }
2316 else {
2317 Instruction *tmp = new TmpInstruction(I->second);
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002318
2319 //Get machine code for this instruction
Tanya Lattner444be612004-11-02 21:04:56 +00002320 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002321 tempMvec.addTemp((Value*) tmp);
Misha Brukmanb4402432005-04-21 23:30:14 +00002322
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002323
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002324 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(), V9::PHI, 3).addReg(lastPhi).addReg(I->second).addRegDef(tmp);
2325 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
2326 lastPhi = tmp;
2327 kernelPHIs[V->first][I->first] = lastPhi;
2328 newValLocation[lastPhi] = machineBB;
2329 }
2330 }
2331 //Final phi value
2332 else {
2333 //The resulting value must be the Value* we created earlier
2334 assert(lastPhi != 0 && "Last phi is NULL!\n");
2335 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(), V9::PHI, 3).addReg(lastPhi).addReg(I->second).addRegDef(finalPHIValue[V->first]);
2336 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
2337 kernelPHIs[V->first][I->first] = finalPHIValue[V->first];
2338 }
2339
2340 ++count;
2341 }
2342
2343 }
Misha Brukmanb4402432005-04-21 23:30:14 +00002344 }
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002345
2346 DEBUG(std::cerr << "KERNEL after PHIs\n");
2347 DEBUG(machineBB->print(std::cerr));
Tanya Lattner081fbd12004-07-30 23:36:10 +00002348}
2349
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002350
Tanya Lattner081fbd12004-07-30 23:36:10 +00002351void ModuloSchedulingPass::removePHIs(const MachineBasicBlock *origBB, std::vector<MachineBasicBlock *> &prologues, std::vector<MachineBasicBlock *> &epilogues, MachineBasicBlock *kernelBB, std::map<Value*, MachineBasicBlock*> &newValLocation) {
2352
2353 //Worklist to delete things
2354 std::vector<std::pair<MachineBasicBlock*, MachineBasicBlock::iterator> > worklist;
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002355
2356 //Worklist of TmpInstructions that need to be added to a MCFI
2357 std::vector<Instruction*> addToMCFI;
Misha Brukmanb4402432005-04-21 23:30:14 +00002358
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002359 //Worklist to add OR instructions to end of kernel so not to invalidate the iterator
2360 //std::vector<std::pair<Instruction*, Value*> > newORs;
2361
Tanya Lattner081fbd12004-07-30 23:36:10 +00002362 const TargetInstrInfo *TMI = target.getInstrInfo();
2363
2364 //Start with the kernel and for each phi insert a copy for the phi def and for each arg
2365 for(MachineBasicBlock::iterator I = kernelBB->begin(), E = kernelBB->end(); I != E; ++I) {
Misha Brukmanb4402432005-04-21 23:30:14 +00002366
Tanya Lattner444be612004-11-02 21:04:56 +00002367 DEBUG(std::cerr << "Looking at Instr: " << *I << "\n");
Tanya Lattner081fbd12004-07-30 23:36:10 +00002368 //Get op code and check if its a phi
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002369 if(I->getOpcode() == V9::PHI) {
Misha Brukmanb4402432005-04-21 23:30:14 +00002370
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002371 DEBUG(std::cerr << "Replacing PHI: " << *I << "\n");
2372 Instruction *tmp = 0;
Tanya Lattner081fbd12004-07-30 23:36:10 +00002373
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002374 for(unsigned i = 0; i < I->getNumOperands(); ++i) {
2375 //Get Operand
2376 const MachineOperand &mOp = I->getOperand(i);
2377 assert(mOp.getType() == MachineOperand::MO_VirtualRegister && "Should be a Value*\n");
2378
2379 if(!tmp) {
2380 tmp = new TmpInstruction(mOp.getVRegValue());
2381 addToMCFI.push_back(tmp);
2382 }
Tanya Lattner081fbd12004-07-30 23:36:10 +00002383
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002384 //Now for all our arguments we read, OR to the new TmpInstruction that we created
2385 if(mOp.isUse()) {
2386 DEBUG(std::cerr << "Use: " << mOp << "\n");
2387 //Place a copy at the end of its BB but before the branches
2388 assert(newValLocation.count(mOp.getVRegValue()) && "We must know where this value is located\n");
2389 //Reverse iterate to find the branches, we can safely assume no instructions have been
2390 //put in the nop positions
2391 for(MachineBasicBlock::iterator inst = --(newValLocation[mOp.getVRegValue()])->end(), endBB = (newValLocation[mOp.getVRegValue()])->begin(); inst != endBB; --inst) {
2392 MachineOpCode opc = inst->getOpcode();
2393 if(TMI->isBranch(opc) || TMI->isNop(opc))
2394 continue;
2395 else {
Tanya Lattner13417b52005-03-23 01:47:20 +00002396 if(mOp.getVRegValue()->getType() == Type::FloatTy)
2397 BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::FMOVS, 3).addReg(mOp.getVRegValue()).addRegDef(tmp);
2398 else if(mOp.getVRegValue()->getType() == Type::DoubleTy)
2399 BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::FMOVD, 3).addReg(mOp.getVRegValue()).addRegDef(tmp);
Misha Brukmanb4402432005-04-21 23:30:14 +00002400 else
Tanya Lattner13417b52005-03-23 01:47:20 +00002401 BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
Misha Brukmanb4402432005-04-21 23:30:14 +00002402
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002403 break;
2404 }
Misha Brukmanb4402432005-04-21 23:30:14 +00002405
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002406 }
Tanya Lattner081fbd12004-07-30 23:36:10 +00002407
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002408 }
2409 else {
2410 //Remove the phi and replace it with an OR
2411 DEBUG(std::cerr << "Def: " << mOp << "\n");
2412 //newORs.push_back(std::make_pair(tmp, mOp.getVRegValue()));
Tanya Lattner13417b52005-03-23 01:47:20 +00002413 if(tmp->getType() == Type::FloatTy)
2414 BuildMI(*kernelBB, I, V9::FMOVS, 3).addReg(tmp).addRegDef(mOp.getVRegValue());
2415 else if(tmp->getType() == Type::DoubleTy)
2416 BuildMI(*kernelBB, I, V9::FMOVD, 3).addReg(tmp).addRegDef(mOp.getVRegValue());
Misha Brukmanb4402432005-04-21 23:30:14 +00002417 else
Tanya Lattner13417b52005-03-23 01:47:20 +00002418 BuildMI(*kernelBB, I, V9::ORr, 3).addReg(tmp).addImm(0).addRegDef(mOp.getVRegValue());
Misha Brukmanb4402432005-04-21 23:30:14 +00002419
2420
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002421 worklist.push_back(std::make_pair(kernelBB, I));
2422 }
2423
2424 }
Misha Brukmanb4402432005-04-21 23:30:14 +00002425
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002426 }
2427
Misha Brukmanb4402432005-04-21 23:30:14 +00002428
Tanya Lattner081fbd12004-07-30 23:36:10 +00002429 }
2430
Tanya Lattner444be612004-11-02 21:04:56 +00002431 //Add TmpInstructions to some MCFI
2432 if(addToMCFI.size() > 0) {
2433 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
2434 for(unsigned x = 0; x < addToMCFI.size(); ++x) {
2435 tempMvec.addTemp(addToMCFI[x]);
2436 }
2437 addToMCFI.clear();
2438 }
2439
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002440
Tanya Lattner081fbd12004-07-30 23:36:10 +00002441 //Remove phis from epilogue
2442 for(std::vector<MachineBasicBlock*>::iterator MB = epilogues.begin(), ME = epilogues.end(); MB != ME; ++MB) {
2443 for(MachineBasicBlock::iterator I = (*MB)->begin(), E = (*MB)->end(); I != E; ++I) {
Misha Brukmanb4402432005-04-21 23:30:14 +00002444
Tanya Lattner444be612004-11-02 21:04:56 +00002445 DEBUG(std::cerr << "Looking at Instr: " << *I << "\n");
Tanya Lattner081fbd12004-07-30 23:36:10 +00002446 //Get op code and check if its a phi
Brian Gaeke75935252004-08-18 20:04:24 +00002447 if(I->getOpcode() == V9::PHI) {
Tanya Lattner081fbd12004-07-30 23:36:10 +00002448 Instruction *tmp = 0;
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002449
Tanya Lattner081fbd12004-07-30 23:36:10 +00002450 for(unsigned i = 0; i < I->getNumOperands(); ++i) {
2451 //Get Operand
2452 const MachineOperand &mOp = I->getOperand(i);
2453 assert(mOp.getType() == MachineOperand::MO_VirtualRegister && "Should be a Value*\n");
Misha Brukmanb4402432005-04-21 23:30:14 +00002454
Tanya Lattner081fbd12004-07-30 23:36:10 +00002455 if(!tmp) {
2456 tmp = new TmpInstruction(mOp.getVRegValue());
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002457 addToMCFI.push_back(tmp);
Tanya Lattner081fbd12004-07-30 23:36:10 +00002458 }
Misha Brukmanb4402432005-04-21 23:30:14 +00002459
Tanya Lattner081fbd12004-07-30 23:36:10 +00002460 //Now for all our arguments we read, OR to the new TmpInstruction that we created
2461 if(mOp.isUse()) {
2462 DEBUG(std::cerr << "Use: " << mOp << "\n");
2463 //Place a copy at the end of its BB but before the branches
2464 assert(newValLocation.count(mOp.getVRegValue()) && "We must know where this value is located\n");
2465 //Reverse iterate to find the branches, we can safely assume no instructions have been
2466 //put in the nop positions
2467 for(MachineBasicBlock::iterator inst = --(newValLocation[mOp.getVRegValue()])->end(), endBB = (newValLocation[mOp.getVRegValue()])->begin(); inst != endBB; --inst) {
2468 MachineOpCode opc = inst->getOpcode();
2469 if(TMI->isBranch(opc) || TMI->isNop(opc))
2470 continue;
2471 else {
Tanya Lattner13417b52005-03-23 01:47:20 +00002472 if(mOp.getVRegValue()->getType() == Type::FloatTy)
2473 BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::FMOVS, 3).addReg(mOp.getVRegValue()).addRegDef(tmp);
2474 else if(mOp.getVRegValue()->getType() == Type::DoubleTy)
2475 BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::FMOVD, 3).addReg(mOp.getVRegValue()).addRegDef(tmp);
Misha Brukmanb4402432005-04-21 23:30:14 +00002476 else
Tanya Lattner13417b52005-03-23 01:47:20 +00002477 BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
2478
2479
Tanya Lattner081fbd12004-07-30 23:36:10 +00002480 break;
2481 }
Misha Brukmanb4402432005-04-21 23:30:14 +00002482
Tanya Lattner081fbd12004-07-30 23:36:10 +00002483 }
Misha Brukmanb4402432005-04-21 23:30:14 +00002484
Tanya Lattner081fbd12004-07-30 23:36:10 +00002485 }
2486 else {
2487 //Remove the phi and replace it with an OR
2488 DEBUG(std::cerr << "Def: " << mOp << "\n");
Tanya Lattner13417b52005-03-23 01:47:20 +00002489 if(tmp->getType() == Type::FloatTy)
2490 BuildMI(**MB, I, V9::FMOVS, 3).addReg(tmp).addRegDef(mOp.getVRegValue());
2491 else if(tmp->getType() == Type::DoubleTy)
2492 BuildMI(**MB, I, V9::FMOVD, 3).addReg(tmp).addRegDef(mOp.getVRegValue());
Misha Brukmanb4402432005-04-21 23:30:14 +00002493 else
Tanya Lattner13417b52005-03-23 01:47:20 +00002494 BuildMI(**MB, I, V9::ORr, 3).addReg(tmp).addImm(0).addRegDef(mOp.getVRegValue());
2495
Tanya Lattner081fbd12004-07-30 23:36:10 +00002496 worklist.push_back(std::make_pair(*MB,I));
2497 }
Misha Brukmanb4402432005-04-21 23:30:14 +00002498
Tanya Lattner081fbd12004-07-30 23:36:10 +00002499 }
2500 }
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002501
Misha Brukmanb4402432005-04-21 23:30:14 +00002502
Tanya Lattner081fbd12004-07-30 23:36:10 +00002503 }
2504 }
2505
Tanya Lattner444be612004-11-02 21:04:56 +00002506
2507 if(addToMCFI.size() > 0) {
2508 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
2509 for(unsigned x = 0; x < addToMCFI.size(); ++x) {
2510 tempMvec.addTemp(addToMCFI[x]);
2511 }
2512 addToMCFI.clear();
2513 }
2514
Tanya Lattner081fbd12004-07-30 23:36:10 +00002515 //Delete the phis
2516 for(std::vector<std::pair<MachineBasicBlock*, MachineBasicBlock::iterator> >::iterator I = worklist.begin(), E = worklist.end(); I != E; ++I) {
Misha Brukmanb4402432005-04-21 23:30:14 +00002517
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002518 DEBUG(std::cerr << "Deleting PHI " << *I->second << "\n");
Tanya Lattner081fbd12004-07-30 23:36:10 +00002519 I->first->erase(I->second);
Misha Brukmanb4402432005-04-21 23:30:14 +00002520
Tanya Lattner081fbd12004-07-30 23:36:10 +00002521 }
2522
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002523
2524 assert((addToMCFI.size() == 0) && "We should have added all TmpInstructions to some MachineCodeForInstruction");
Tanya Lattner50cbb9a2004-05-28 20:14:12 +00002525}
2526
2527
Tanya Lattner081fbd12004-07-30 23:36:10 +00002528void ModuloSchedulingPass::reconstructLoop(MachineBasicBlock *BB) {
Tanya Lattnera066df62004-05-26 06:27:18 +00002529
Tanya Lattner56807c62005-02-10 17:02:58 +00002530 TIME_REGION(X, "reconstructLoop");
2531
2532
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002533 DEBUG(std::cerr << "Reconstructing Loop\n");
2534
Tanya Lattner081fbd12004-07-30 23:36:10 +00002535 //First find the value *'s that we need to "save"
Tanya Lattner13417b52005-03-23 01:47:20 +00002536 std::map<const Value*, std::pair<const MachineInstr*, int> > valuesToSave;
Tanya Lattnera066df62004-05-26 06:27:18 +00002537
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002538 //Keep track of instructions we have already seen and their stage because
2539 //we don't want to "save" values if they are used in the kernel immediately
2540 std::map<const MachineInstr*, int> lastInstrs;
2541
Tanya Lattner081fbd12004-07-30 23:36:10 +00002542 //Loop over kernel and only look at instructions from a stage > 0
2543 //Look at its operands and save values *'s that are read
Tanya Lattnera066df62004-05-26 06:27:18 +00002544 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
Tanya Lattnera066df62004-05-26 06:27:18 +00002545
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002546 if(I->second !=0) {
Tanya Lattnera066df62004-05-26 06:27:18 +00002547 //For this instruction, get the Value*'s that it reads and put them into the set.
2548 //Assert if there is an operand of another type that we need to save
Tanya Lattner13417b52005-03-23 01:47:20 +00002549 const MachineInstr *inst = I->first;
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002550 lastInstrs[inst] = I->second;
2551
Tanya Lattnera066df62004-05-26 06:27:18 +00002552 for(unsigned i=0; i < inst->getNumOperands(); ++i) {
2553 //get machine operand
2554 const MachineOperand &mOp = inst->getOperand(i);
Tanya Lattner081fbd12004-07-30 23:36:10 +00002555
Tanya Lattnera066df62004-05-26 06:27:18 +00002556 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse()) {
2557 //find the value in the map
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002558 if (const Value* srcI = mOp.getVRegValue()) {
2559
Tanya Lattner7beb51c2004-11-16 21:31:37 +00002560 if(isa<Constant>(srcI) || isa<Argument>(srcI) || isa<PHINode>(srcI))
Tanya Lattner444be612004-11-02 21:04:56 +00002561 continue;
2562
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002563 //Before we declare this Value* one that we should save
2564 //make sure its def is not of the same stage as this instruction
2565 //because it will be consumed before its used
2566 Instruction *defInst = (Instruction*) srcI;
Misha Brukmanb4402432005-04-21 23:30:14 +00002567
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002568 //Should we save this value?
2569 bool save = true;
2570
Tanya Lattner7beb51c2004-11-16 21:31:37 +00002571 //Continue if not in the def map, loop invariant code does not need to be saved
2572 if(!defMap.count(srcI))
2573 continue;
2574
Tanya Lattner444be612004-11-02 21:04:56 +00002575 MachineInstr *defInstr = defMap[srcI];
Misha Brukmanb4402432005-04-21 23:30:14 +00002576
Tanya Lattner7beb51c2004-11-16 21:31:37 +00002577
Tanya Lattner444be612004-11-02 21:04:56 +00002578 if(lastInstrs.count(defInstr)) {
Tanya Lattner7beb51c2004-11-16 21:31:37 +00002579 if(lastInstrs[defInstr] == I->second) {
Tanya Lattner444be612004-11-02 21:04:56 +00002580 save = false;
Tanya Lattner7beb51c2004-11-16 21:31:37 +00002581
2582 }
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002583 }
Misha Brukmanb4402432005-04-21 23:30:14 +00002584
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002585 if(save)
2586 valuesToSave[srcI] = std::make_pair(I->first, i);
Misha Brukmanb4402432005-04-21 23:30:14 +00002587 }
Tanya Lattnera066df62004-05-26 06:27:18 +00002588 }
2589
2590 if(mOp.getType() != MachineOperand::MO_VirtualRegister && mOp.isUse()) {
2591 assert("Our assumption is wrong. We have another type of register that needs to be saved\n");
2592 }
2593 }
Tanya Lattnera066df62004-05-26 06:27:18 +00002594 }
2595 }
2596
Tanya Lattner081fbd12004-07-30 23:36:10 +00002597 //The new loop will consist of one or more prologues, the kernel, and one or more epilogues.
2598
2599 //Map to keep track of old to new values
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002600 std::map<Value*, std::map<int, Value*> > newValues;
Misha Brukmanb4402432005-04-21 23:30:14 +00002601
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002602 //Map to keep track of old to new values in kernel
2603 std::map<Value*, std::map<int, Value*> > kernelPHIs;
2604
Tanya Lattner081fbd12004-07-30 23:36:10 +00002605 //Another map to keep track of what machine basic blocks these new value*s are in since
2606 //they have no llvm instruction equivalent
2607 std::map<Value*, MachineBasicBlock*> newValLocation;
2608
2609 std::vector<MachineBasicBlock*> prologues;
2610 std::vector<BasicBlock*> llvm_prologues;
2611
2612
2613 //Write prologue
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00002614 if(schedule.getMaxStage() != 0)
2615 writePrologues(prologues, BB, llvm_prologues, valuesToSave, newValues, newValLocation);
Misha Brukmanb4402432005-04-21 23:30:14 +00002616
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002617 //Print out epilogues and prologue
Misha Brukmanb4402432005-04-21 23:30:14 +00002618 DEBUG(for(std::vector<MachineBasicBlock*>::iterator I = prologues.begin(), E = prologues.end();
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002619 I != E; ++I) {
2620 std::cerr << "PROLOGUE\n";
2621 (*I)->print(std::cerr);
2622 });
Tanya Lattner081fbd12004-07-30 23:36:10 +00002623
2624 BasicBlock *llvmKernelBB = new BasicBlock("Kernel", (Function*) (BB->getBasicBlock()->getParent()));
2625 MachineBasicBlock *machineKernelBB = new MachineBasicBlock(llvmKernelBB);
Tanya Lattner081fbd12004-07-30 23:36:10 +00002626 (((MachineBasicBlock*)BB)->getParent())->getBasicBlockList().push_back(machineKernelBB);
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002627 writeKernel(llvmKernelBB, machineKernelBB, valuesToSave, newValues, newValLocation, kernelPHIs);
Misha Brukmanb4402432005-04-21 23:30:14 +00002628
2629
Tanya Lattner081fbd12004-07-30 23:36:10 +00002630 std::vector<MachineBasicBlock*> epilogues;
2631 std::vector<BasicBlock*> llvm_epilogues;
2632
2633 //Write epilogues
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00002634 if(schedule.getMaxStage() != 0)
2635 writeEpilogues(epilogues, BB, llvm_epilogues, valuesToSave, newValues, newValLocation, kernelPHIs);
Tanya Lattner081fbd12004-07-30 23:36:10 +00002636
2637
Tanya Lattnerd8cc4fa2004-11-29 04:39:47 +00002638 //Fix our branches
2639 fixBranches(prologues, llvm_prologues, machineKernelBB, llvmKernelBB, epilogues, llvm_epilogues, BB);
2640
2641 //Remove phis
2642 removePHIs(BB, prologues, epilogues, machineKernelBB, newValLocation);
Misha Brukmanb4402432005-04-21 23:30:14 +00002643
Tanya Lattnerd8cc4fa2004-11-29 04:39:47 +00002644 //Print out epilogues and prologue
Misha Brukmanb4402432005-04-21 23:30:14 +00002645 DEBUG(for(std::vector<MachineBasicBlock*>::iterator I = prologues.begin(), E = prologues.end();
Tanya Lattnerd8cc4fa2004-11-29 04:39:47 +00002646 I != E; ++I) {
2647 std::cerr << "PROLOGUE\n";
2648 (*I)->print(std::cerr);
2649 });
Misha Brukmanb4402432005-04-21 23:30:14 +00002650
Tanya Lattnerd8cc4fa2004-11-29 04:39:47 +00002651 DEBUG(std::cerr << "KERNEL\n");
2652 DEBUG(machineKernelBB->print(std::cerr));
2653
Misha Brukmanb4402432005-04-21 23:30:14 +00002654 DEBUG(for(std::vector<MachineBasicBlock*>::iterator I = epilogues.begin(), E = epilogues.end();
Tanya Lattnerd8cc4fa2004-11-29 04:39:47 +00002655 I != E; ++I) {
2656 std::cerr << "EPILOGUE\n";
2657 (*I)->print(std::cerr);
2658 });
2659
2660
2661 DEBUG(std::cerr << "New Machine Function" << "\n");
2662 DEBUG(std::cerr << BB->getParent() << "\n");
2663
2664
2665}
2666
2667void ModuloSchedulingPass::fixBranches(std::vector<MachineBasicBlock *> &prologues, std::vector<BasicBlock*> &llvm_prologues, MachineBasicBlock *machineKernelBB, BasicBlock *llvmKernelBB, std::vector<MachineBasicBlock *> &epilogues, std::vector<BasicBlock*> &llvm_epilogues, MachineBasicBlock *BB) {
2668
Tanya Lattner081fbd12004-07-30 23:36:10 +00002669 const TargetInstrInfo *TMI = target.getInstrInfo();
2670
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00002671 if(schedule.getMaxStage() != 0) {
2672 //Fix prologue branches
2673 for(unsigned I = 0; I < prologues.size(); ++I) {
Misha Brukmanb4402432005-04-21 23:30:14 +00002674
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00002675 //Find terminator since getFirstTerminator does not work!
2676 for(MachineBasicBlock::reverse_iterator mInst = prologues[I]->rbegin(), mInstEnd = prologues[I]->rend(); mInst != mInstEnd; ++mInst) {
2677 MachineOpCode OC = mInst->getOpcode();
2678 //If its a branch update its branchto
2679 if(TMI->isBranch(OC)) {
2680 for(unsigned opNum = 0; opNum < mInst->getNumOperands(); ++opNum) {
2681 MachineOperand &mOp = mInst->getOperand(opNum);
2682 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2683 //Check if we are branching to the kernel, if not branch to epilogue
Misha Brukmanb4402432005-04-21 23:30:14 +00002684 if(mOp.getVRegValue() == BB->getBasicBlock()) {
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00002685 if(I == prologues.size()-1)
2686 mOp.setValueReg(llvmKernelBB);
2687 else
2688 mOp.setValueReg(llvm_prologues[I+1]);
2689 }
2690 else {
2691 mOp.setValueReg(llvm_epilogues[(llvm_epilogues.size()-1-I)]);
2692 }
Tanya Lattnerd8cc4fa2004-11-29 04:39:47 +00002693 }
2694 }
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00002695
2696 DEBUG(std::cerr << "New Prologue Branch: " << *mInst << "\n");
Tanya Lattnerd8cc4fa2004-11-29 04:39:47 +00002697 }
Tanya Lattner081fbd12004-07-30 23:36:10 +00002698 }
Tanya Lattner081fbd12004-07-30 23:36:10 +00002699
Tanya Lattner081fbd12004-07-30 23:36:10 +00002700
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00002701 //Update llvm basic block with our new branch instr
2702 DEBUG(std::cerr << BB->getBasicBlock()->getTerminator() << "\n");
2703 const BranchInst *branchVal = dyn_cast<BranchInst>(BB->getBasicBlock()->getTerminator());
Misha Brukmanb4402432005-04-21 23:30:14 +00002704
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00002705 if(I == prologues.size()-1) {
2706 TerminatorInst *newBranch = new BranchInst(llvmKernelBB,
Misha Brukmanb4402432005-04-21 23:30:14 +00002707 llvm_epilogues[(llvm_epilogues.size()-1-I)],
2708 branchVal->getCondition(),
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00002709 llvm_prologues[I]);
2710 }
2711 else
2712 TerminatorInst *newBranch = new BranchInst(llvm_prologues[I+1],
Misha Brukmanb4402432005-04-21 23:30:14 +00002713 llvm_epilogues[(llvm_epilogues.size()-1-I)],
2714 branchVal->getCondition(),
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00002715 llvm_prologues[I]);
Tanya Lattner081fbd12004-07-30 23:36:10 +00002716
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00002717 }
Tanya Lattner081fbd12004-07-30 23:36:10 +00002718 }
2719
Tanya Lattnerd8cc4fa2004-11-29 04:39:47 +00002720 Value *origBranchExit = 0;
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002721
Tanya Lattnerd8cc4fa2004-11-29 04:39:47 +00002722 //Fix up kernel machine branches
Tanya Lattner081fbd12004-07-30 23:36:10 +00002723 for(MachineBasicBlock::reverse_iterator mInst = machineKernelBB->rbegin(), mInstEnd = machineKernelBB->rend(); mInst != mInstEnd; ++mInst) {
2724 MachineOpCode OC = mInst->getOpcode();
2725 if(TMI->isBranch(OC)) {
Tanya Lattnerd8cc4fa2004-11-29 04:39:47 +00002726 for(unsigned opNum = 0; opNum < mInst->getNumOperands(); ++opNum) {
2727 MachineOperand &mOp = mInst->getOperand(opNum);
2728
2729 if(mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2730 if(mOp.getVRegValue() == BB->getBasicBlock())
2731 mOp.setValueReg(llvmKernelBB);
2732 else
2733 if(llvm_epilogues.size() > 0) {
2734 assert(origBranchExit == 0 && "There should only be one branch out of the loop");
Misha Brukmanb4402432005-04-21 23:30:14 +00002735
Tanya Lattnerd8cc4fa2004-11-29 04:39:47 +00002736 origBranchExit = mOp.getVRegValue();
2737 mOp.setValueReg(llvm_epilogues[0]);
2738 }
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00002739 else
2740 origBranchExit = mOp.getVRegValue();
Tanya Lattnerd8cc4fa2004-11-29 04:39:47 +00002741 }
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002742 }
Tanya Lattner081fbd12004-07-30 23:36:10 +00002743 }
2744 }
Misha Brukmanb4402432005-04-21 23:30:14 +00002745
Tanya Lattner081fbd12004-07-30 23:36:10 +00002746 //Update kernelLLVM branches
2747 const BranchInst *branchVal = dyn_cast<BranchInst>(BB->getBasicBlock()->getTerminator());
Misha Brukmanb4402432005-04-21 23:30:14 +00002748
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00002749 assert(origBranchExit != 0 && "We must have the original bb the kernel exits to!");
Misha Brukmanb4402432005-04-21 23:30:14 +00002750
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00002751 if(epilogues.size() > 0) {
2752 TerminatorInst *newBranch = new BranchInst(llvmKernelBB,
Misha Brukmanb4402432005-04-21 23:30:14 +00002753 llvm_epilogues[0],
2754 branchVal->getCondition(),
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00002755 llvmKernelBB);
2756 }
2757 else {
2758 BasicBlock *origBBExit = dyn_cast<BasicBlock>(origBranchExit);
2759 assert(origBBExit !=0 && "Original exit basic block must be set");
2760 TerminatorInst *newBranch = new BranchInst(llvmKernelBB,
2761 origBBExit,
Misha Brukmanb4402432005-04-21 23:30:14 +00002762 branchVal->getCondition(),
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00002763 llvmKernelBB);
2764 }
Tanya Lattner081fbd12004-07-30 23:36:10 +00002765
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00002766 if(schedule.getMaxStage() != 0) {
Tanya Lattner081fbd12004-07-30 23:36:10 +00002767 //Lastly add unconditional branches for the epilogues
2768 for(unsigned I = 0; I < epilogues.size(); ++I) {
Misha Brukmanb4402432005-04-21 23:30:14 +00002769
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002770 //Now since we don't have fall throughs, add a unconditional branch to the next prologue
Tanya Lattner081fbd12004-07-30 23:36:10 +00002771 if(I != epilogues.size()-1) {
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002772 BuildMI(epilogues[I], V9::BA, 1).addPCDisp(llvm_epilogues[I+1]);
Tanya Lattner081fbd12004-07-30 23:36:10 +00002773 //Add unconditional branch to end of epilogue
Misha Brukmanb4402432005-04-21 23:30:14 +00002774 TerminatorInst *newBranch = new BranchInst(llvm_epilogues[I+1],
Tanya Lattner081fbd12004-07-30 23:36:10 +00002775 llvm_epilogues[I]);
2776
Tanya Lattnera066df62004-05-26 06:27:18 +00002777 }
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002778 else {
Tanya Lattnerd8cc4fa2004-11-29 04:39:47 +00002779 BuildMI(epilogues[I], V9::BA, 1).addPCDisp(origBranchExit);
Misha Brukmanb4402432005-04-21 23:30:14 +00002780
2781
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002782 //Update last epilogue exit branch
2783 BranchInst *branchVal = (BranchInst*) dyn_cast<BranchInst>(BB->getBasicBlock()->getTerminator());
2784 //Find where we are supposed to branch to
2785 BasicBlock *nextBlock = 0;
2786 for(unsigned j=0; j <branchVal->getNumSuccessors(); ++j) {
2787 if(branchVal->getSuccessor(j) != BB->getBasicBlock())
2788 nextBlock = branchVal->getSuccessor(j);
2789 }
Misha Brukmanb4402432005-04-21 23:30:14 +00002790
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002791 assert((nextBlock != 0) && "Next block should not be null!");
2792 TerminatorInst *newBranch = new BranchInst(nextBlock, llvm_epilogues[I]);
2793 }
2794 //Add one more nop!
2795 BuildMI(epilogues[I], V9::NOP, 0);
Misha Brukmanb4402432005-04-21 23:30:14 +00002796
Tanya Lattner081fbd12004-07-30 23:36:10 +00002797 }
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00002798 }
Tanya Lattnera066df62004-05-26 06:27:18 +00002799
Tanya Lattner081fbd12004-07-30 23:36:10 +00002800 //FIX UP Machine BB entry!!
2801 //We are looking at the predecesor of our loop basic block and we want to change its ba instruction
Misha Brukmanb4402432005-04-21 23:30:14 +00002802
Tanya Lattnera066df62004-05-26 06:27:18 +00002803
Tanya Lattner081fbd12004-07-30 23:36:10 +00002804 //Find all llvm basic blocks that branch to the loop entry and change to our first prologue.
2805 const BasicBlock *llvmBB = BB->getBasicBlock();
2806
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00002807 std::vector<const BasicBlock*>Preds (pred_begin(llvmBB), pred_end(llvmBB));
2808
2809 //for(pred_const_iterator P = pred_begin(llvmBB), PE = pred_end(llvmBB); P != PE; ++PE) {
Misha Brukmanb4402432005-04-21 23:30:14 +00002810 for(std::vector<const BasicBlock*>::iterator P = Preds.begin(), PE = Preds.end(); P != PE; ++P) {
Tanya Lattner081fbd12004-07-30 23:36:10 +00002811 if(*P == llvmBB)
2812 continue;
2813 else {
2814 DEBUG(std::cerr << "Found our entry BB\n");
2815 //Get the Terminator instruction for this basic block and print it out
2816 DEBUG(std::cerr << *((*P)->getTerminator()) << "\n");
2817 //Update the terminator
2818 TerminatorInst *term = ((BasicBlock*)*P)->getTerminator();
2819 for(unsigned i=0; i < term->getNumSuccessors(); ++i) {
2820 if(term->getSuccessor(i) == llvmBB) {
2821 DEBUG(std::cerr << "Replacing successor bb\n");
2822 if(llvm_prologues.size() > 0) {
2823 term->setSuccessor(i, llvm_prologues[0]);
2824 //Also update its corresponding machine instruction
2825 MachineCodeForInstruction & tempMvec =
2826 MachineCodeForInstruction::get(term);
2827 for (unsigned j = 0; j < tempMvec.size(); j++) {
2828 MachineInstr *temp = tempMvec[j];
2829 MachineOpCode opc = temp->getOpcode();
2830 if(TMI->isBranch(opc)) {
2831 DEBUG(std::cerr << *temp << "\n");
2832 //Update branch
2833 for(unsigned opNum = 0; opNum < temp->getNumOperands(); ++opNum) {
2834 MachineOperand &mOp = temp->getOperand(opNum);
2835 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2836 mOp.setValueReg(llvm_prologues[0]);
2837 }
2838 }
2839 }
Misha Brukmanb4402432005-04-21 23:30:14 +00002840 }
Tanya Lattner081fbd12004-07-30 23:36:10 +00002841 }
2842 else {
2843 term->setSuccessor(i, llvmKernelBB);
2844 //Also update its corresponding machine instruction
2845 MachineCodeForInstruction & tempMvec =
2846 MachineCodeForInstruction::get(term);
2847 for (unsigned j = 0; j < tempMvec.size(); j++) {
2848 MachineInstr *temp = tempMvec[j];
2849 MachineOpCode opc = temp->getOpcode();
2850 if(TMI->isBranch(opc)) {
2851 DEBUG(std::cerr << *temp << "\n");
2852 //Update branch
2853 for(unsigned opNum = 0; opNum < temp->getNumOperands(); ++opNum) {
2854 MachineOperand &mOp = temp->getOperand(opNum);
2855 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2856 mOp.setValueReg(llvmKernelBB);
2857 }
2858 }
2859 }
2860 }
2861 }
2862 }
2863 }
2864 break;
2865 }
2866 }
Misha Brukmanb4402432005-04-21 23:30:14 +00002867
Tanya Lattner081fbd12004-07-30 23:36:10 +00002868
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002869 //BB->getParent()->getBasicBlockList().erase(BB);
Tanya Lattnera066df62004-05-26 06:27:18 +00002870
2871}
2872