blob: e5b8d3c53d3b0161c203e198308608abb47f5fa5 [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,
1221 std::set<MSchedGraphNode*> &nodesToAdd) {
1222 //Push node onto the path
1223 path.push_back(node);
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001224
Misha Brukmanb4402432005-04-21 23:30:14 +00001225 //Loop over all successors and see if there is a path from this node to
Tanya Lattnera31ad512005-02-23 02:01:42 +00001226 //a recurrence in the partial order, if so.. add all nodes to be added to recc
Misha Brukmanb4402432005-04-21 23:30:14 +00001227 for(MSchedGraphNode::succ_iterator S = node->succ_begin(), SE = node->succ_end(); S != SE;
Tanya Lattnera31ad512005-02-23 02:01:42 +00001228 ++S) {
1229
1230 //If this node exists in a recurrence already in the partial order, then add all
1231 //nodes in the path to the set of nodes to add
1232 //Check if its already in our partial order, if not add it to the final vector
Misha Brukmanb4402432005-04-21 23:30:14 +00001233 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(),
Tanya Lattnera31ad512005-02-23 02:01:42 +00001234 PE = partialOrder.end(); PO != PE; ++PO) {
Misha Brukmanb4402432005-04-21 23:30:14 +00001235
Tanya Lattnera31ad512005-02-23 02:01:42 +00001236 //Check if we should ignore this edge first
1237 if(ignoreEdge(node,*S))
1238 continue;
1239
1240 if(PO->count(*S)) {
1241 nodesToAdd.insert(*S);
1242 }
Tanya Lattner13417b52005-03-23 01:47:20 +00001243 //terminate
1244 else
1245 searchPath(*S, path, nodesToAdd);
Tanya Lattnera31ad512005-02-23 02:01:42 +00001246 }
Tanya Lattnera31ad512005-02-23 02:01:42 +00001247 }
Misha Brukmanb4402432005-04-21 23:30:14 +00001248
Tanya Lattnera31ad512005-02-23 02:01:42 +00001249 //Pop Node off the path
1250 path.pop_back();
1251}
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001252
Misha Brukmanb4402432005-04-21 23:30:14 +00001253void ModuloSchedulingPass::pathToRecc(MSchedGraphNode *node,
Tanya Lattner13417b52005-03-23 01:47:20 +00001254 std::vector<MSchedGraphNode*> &path,
1255 std::set<MSchedGraphNode*> &poSet,
1256 std::set<MSchedGraphNode*> &lastNodes) {
1257 //Push node onto the path
1258 path.push_back(node);
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001259
Tanya Lattner13417b52005-03-23 01:47:20 +00001260 DEBUG(std::cerr << "Current node: " << *node << "\n");
1261
Misha Brukmanb4402432005-04-21 23:30:14 +00001262 //Loop over all successors and see if there is a path from this node to
Tanya Lattner13417b52005-03-23 01:47:20 +00001263 //a recurrence in the partial order, if so.. add all nodes to be added to recc
Misha Brukmanb4402432005-04-21 23:30:14 +00001264 for(MSchedGraphNode::succ_iterator S = node->succ_begin(), SE = node->succ_end(); S != SE;
Tanya Lattner13417b52005-03-23 01:47:20 +00001265 ++S) {
1266 DEBUG(std::cerr << "Succ:" << **S << "\n");
1267 //Check if we should ignore this edge first
1268 if(ignoreEdge(node,*S))
1269 continue;
Misha Brukmanb4402432005-04-21 23:30:14 +00001270
Tanya Lattner13417b52005-03-23 01:47:20 +00001271 if(poSet.count(*S)) {
1272 DEBUG(std::cerr << "Found path to recc from no pred\n");
1273 //Loop over path, if it exists in lastNodes, then add to poset, and remove from lastNodes
1274 for(std::vector<MSchedGraphNode*>::iterator I = path.begin(), IE = path.end(); I != IE; ++I) {
1275 if(lastNodes.count(*I)) {
1276 DEBUG(std::cerr << "Inserting node into recc: " << **I << "\n");
1277 poSet.insert(*I);
1278 lastNodes.erase(*I);
1279 }
1280 }
1281 }
1282 else
1283 pathToRecc(*S, path, poSet, lastNodes);
1284 }
Misha Brukmanb4402432005-04-21 23:30:14 +00001285
Tanya Lattner13417b52005-03-23 01:47:20 +00001286 //Pop Node off the path
1287 path.pop_back();
1288}
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001289
Tanya Lattnera6820d62004-05-08 16:12:10 +00001290void ModuloSchedulingPass::computePartialOrder() {
Tanya Lattner13c71ca2004-11-24 01:49:10 +00001291
Tanya Lattner56807c62005-02-10 17:02:58 +00001292 TIME_REGION(X, "calculatePartialOrder");
Tanya Lattner42ed1482005-04-22 06:32:48 +00001293
1294 DEBUG(std::cerr << "Computing Partial Order\n");
Misha Brukmanb4402432005-04-21 23:30:14 +00001295
Tanya Lattner42ed1482005-04-22 06:32:48 +00001296 //Only push BA branches onto the final node order, we put other
1297 //branches after it FIXME: Should we really be pushing branches on
1298 //it a specific order instead of relying on BA being there?
1299
Tanya Lattnerd8cc4fa2004-11-29 04:39:47 +00001300 std::vector<MSchedGraphNode*> branches;
Tanya Lattner42ed1482005-04-22 06:32:48 +00001301
1302 //Steps to add a recurrence to the partial order 1) Find reccurrence
1303 //with the highest RecMII. Add it to the partial order. 2) For each
1304 //recurrence with decreasing RecMII, add it to the partial order
1305 //along with any nodes that connect this recurrence to recurrences
1306 //already in the partial order
1307 for(std::set<std::pair<int, std::vector<MSchedGraphNode*> > >::reverse_iterator
Tanya Lattnera31ad512005-02-23 02:01:42 +00001308 I = recurrenceList.rbegin(), E=recurrenceList.rend(); I !=E; ++I) {
Tanya Lattnera6820d62004-05-08 16:12:10 +00001309
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001310 std::set<MSchedGraphNode*> new_recurrence;
Tanya Lattnera31ad512005-02-23 02:01:42 +00001311
Tanya Lattnera6820d62004-05-08 16:12:10 +00001312 //Loop through recurrence and remove any nodes already in the partial order
Misha Brukmanb4402432005-04-21 23:30:14 +00001313 for(std::vector<MSchedGraphNode*>::const_iterator N = I->second.begin(),
Tanya Lattnera31ad512005-02-23 02:01:42 +00001314 NE = I->second.end(); N != NE; ++N) {
1315
Tanya Lattnera6820d62004-05-08 16:12:10 +00001316 bool found = false;
Misha Brukmanb4402432005-04-21 23:30:14 +00001317 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(),
Tanya Lattnera31ad512005-02-23 02:01:42 +00001318 PE = partialOrder.end(); PO != PE; ++PO) {
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001319 if(PO->count(*N))
Tanya Lattnera6820d62004-05-08 16:12:10 +00001320 found = true;
1321 }
Tanya Lattnera31ad512005-02-23 02:01:42 +00001322
1323 //Check if its a branch, and remove to handle special
Tanya Lattnera6820d62004-05-08 16:12:10 +00001324 if(!found) {
Tanya Lattner13417b52005-03-23 01:47:20 +00001325 if((*N)->isBranch() && !(*N)->hasPredecessors()) {
Tanya Lattnerd8cc4fa2004-11-29 04:39:47 +00001326 branches.push_back(*N);
Tanya Lattner13c71ca2004-11-24 01:49:10 +00001327 }
1328 else
1329 new_recurrence.insert(*N);
Tanya Lattnera31ad512005-02-23 02:01:42 +00001330 }
1331
Tanya Lattnera6820d62004-05-08 16:12:10 +00001332 }
Misha Brukmanb4402432005-04-21 23:30:14 +00001333
Tanya Lattnera31ad512005-02-23 02:01:42 +00001334
1335 if(new_recurrence.size() > 0) {
Misha Brukmanb4402432005-04-21 23:30:14 +00001336
Tanya Lattnera31ad512005-02-23 02:01:42 +00001337 std::vector<MSchedGraphNode*> path;
1338 std::set<MSchedGraphNode*> nodesToAdd;
1339
Tanya Lattner42ed1482005-04-22 06:32:48 +00001340 //Dump recc we are dealing with (minus nodes already in PO)
1341 DEBUG(std::cerr << "Recc: ");
1342 DEBUG(for(std::set<MSchedGraphNode*>::iterator R = new_recurrence.begin(), RE = new_recurrence.end(); R != RE; ++R) { std::cerr << **R ; });
1343
Tanya Lattnera31ad512005-02-23 02:01:42 +00001344 //Add nodes that connect this recurrence to recurrences in the partial path
1345 for(std::set<MSchedGraphNode*>::iterator N = new_recurrence.begin(),
Tanya Lattner13417b52005-03-23 01:47:20 +00001346 NE = new_recurrence.end(); N != NE; ++N)
1347 searchPath(*N, path, nodesToAdd);
Misha Brukmanb4402432005-04-21 23:30:14 +00001348
Tanya Lattnera31ad512005-02-23 02:01:42 +00001349 //Add nodes to this recurrence if they are not already in the partial order
1350 for(std::set<MSchedGraphNode*>::iterator N = nodesToAdd.begin(), NE = nodesToAdd.end();
1351 N != NE; ++N) {
1352 bool found = false;
Misha Brukmanb4402432005-04-21 23:30:14 +00001353 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(),
Tanya Lattnera31ad512005-02-23 02:01:42 +00001354 PE = partialOrder.end(); PO != PE; ++PO) {
1355 if(PO->count(*N))
1356 found = true;
1357 }
1358 if(!found) {
1359 assert("FOUND CONNECTOR");
1360 new_recurrence.insert(*N);
1361 }
1362 }
1363
Tanya Lattnera6820d62004-05-08 16:12:10 +00001364 partialOrder.push_back(new_recurrence);
Tanya Lattnera31ad512005-02-23 02:01:42 +00001365
Tanya Lattner42ed1482005-04-22 06:32:48 +00001366
1367 //Dump out partial order
1368 DEBUG(for(std::vector<std::set<MSchedGraphNode*> >::iterator I = partialOrder.begin(),
1369 E = partialOrder.end(); I !=E; ++I) {
1370 std::cerr << "Start set in PO\n";
1371 for(std::set<MSchedGraphNode*>::iterator J = I->begin(), JE = I->end(); J != JE; ++J)
1372 std::cerr << "PO:" << **J << "\n";
1373 });
1374
Tanya Lattnera31ad512005-02-23 02:01:42 +00001375 }
Tanya Lattnera6820d62004-05-08 16:12:10 +00001376 }
Misha Brukmanb4402432005-04-21 23:30:14 +00001377
Tanya Lattnera6820d62004-05-08 16:12:10 +00001378 //Add any nodes that are not already in the partial order
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001379 //Add them in a set, one set per connected component
1380 std::set<MSchedGraphNode*> lastNodes;
Tanya Lattner13417b52005-03-23 01:47:20 +00001381 std::set<MSchedGraphNode*> noPredNodes;
Misha Brukmanb4402432005-04-21 23:30:14 +00001382 for(std::map<MSchedGraphNode*, MSNodeAttributes>::iterator I = nodeToAttributesMap.begin(),
Tanya Lattnera31ad512005-02-23 02:01:42 +00001383 E = nodeToAttributesMap.end(); I != E; ++I) {
Misha Brukmanb4402432005-04-21 23:30:14 +00001384
Tanya Lattnera6820d62004-05-08 16:12:10 +00001385 bool found = false;
Misha Brukmanb4402432005-04-21 23:30:14 +00001386
Tanya Lattnera6820d62004-05-08 16:12:10 +00001387 //Check if its already in our partial order, if not add it to the final vector
Misha Brukmanb4402432005-04-21 23:30:14 +00001388 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(),
Tanya Lattnera31ad512005-02-23 02:01:42 +00001389 PE = partialOrder.end(); PO != PE; ++PO) {
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001390 if(PO->count(I->first))
Tanya Lattnera6820d62004-05-08 16:12:10 +00001391 found = true;
1392 }
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00001393 if(!found)
1394 lastNodes.insert(I->first);
Tanya Lattnera6820d62004-05-08 16:12:10 +00001395 }
1396
Tanya Lattner13417b52005-03-23 01:47:20 +00001397 //For each node w/out preds, see if there is a path to one of the
1398 //recurrences, and if so add them to that current recc
1399 /*for(std::set<MSchedGraphNode*>::iterator N = noPredNodes.begin(), NE = noPredNodes.end();
1400 N != NE; ++N) {
1401 DEBUG(std::cerr << "No Pred Path from: " << **N << "\n");
Misha Brukmanb4402432005-04-21 23:30:14 +00001402 for(std::vector<std::set<MSchedGraphNode*> >::iterator PO = partialOrder.begin(),
Tanya Lattner13417b52005-03-23 01:47:20 +00001403 PE = partialOrder.end(); PO != PE; ++PO) {
1404 std::vector<MSchedGraphNode*> path;
1405 pathToRecc(*N, path, *PO, lastNodes);
1406 }
1407 }*/
Misha Brukmanb4402432005-04-21 23:30:14 +00001408
Tanya Lattner13417b52005-03-23 01:47:20 +00001409
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001410 //Break up remaining nodes that are not in the partial order
Tanya Lattner13417b52005-03-23 01:47:20 +00001411 ///into their connected compoenents
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00001412 while(lastNodes.size() > 0) {
Tanya Lattner13417b52005-03-23 01:47:20 +00001413 std::set<MSchedGraphNode*> ccSet;
1414 connectedComponentSet(*(lastNodes.begin()),ccSet, lastNodes);
1415 if(ccSet.size() > 0)
1416 partialOrder.push_back(ccSet);
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00001417 }
Misha Brukmanb4402432005-04-21 23:30:14 +00001418
1419
Tanya Lattner13c71ca2004-11-24 01:49:10 +00001420 //Clean up branches by putting them in final order
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00001421 assert(branches.size() == 0 && "We should not have any branches in our graph");
Tanya Lattnera6820d62004-05-08 16:12:10 +00001422}
1423
1424
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001425void ModuloSchedulingPass::connectedComponentSet(MSchedGraphNode *node, std::set<MSchedGraphNode*> &ccSet, std::set<MSchedGraphNode*> &lastNodes) {
1426
Tanya Lattner13c71ca2004-11-24 01:49:10 +00001427//Add to final set
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00001428 if( !ccSet.count(node) && lastNodes.count(node)) {
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001429 lastNodes.erase(node);
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00001430 ccSet.insert(node);
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001431 }
1432 else
1433 return;
Misha Brukmanb4402432005-04-21 23:30:14 +00001434
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001435 //Loop over successors and recurse if we have not seen this node before
1436 for(MSchedGraphNode::succ_iterator node_succ = node->succ_begin(), end=node->succ_end(); node_succ != end; ++node_succ) {
1437 connectedComponentSet(*node_succ, ccSet, lastNodes);
1438 }
Misha Brukmanb4402432005-04-21 23:30:14 +00001439
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001440}
1441
1442void ModuloSchedulingPass::predIntersect(std::set<MSchedGraphNode*> &CurrentSet, std::set<MSchedGraphNode*> &IntersectResult) {
Misha Brukmanb4402432005-04-21 23:30:14 +00001443
Tanya Lattnera6820d62004-05-08 16:12:10 +00001444 for(unsigned j=0; j < FinalNodeOrder.size(); ++j) {
Misha Brukmanb4402432005-04-21 23:30:14 +00001445 for(MSchedGraphNode::pred_iterator P = FinalNodeOrder[j]->pred_begin(),
Tanya Lattnera6820d62004-05-08 16:12:10 +00001446 E = FinalNodeOrder[j]->pred_end(); P != E; ++P) {
Misha Brukmanb4402432005-04-21 23:30:14 +00001447
Tanya Lattnera6820d62004-05-08 16:12:10 +00001448 //Check if we are supposed to ignore this edge or not
1449 if(ignoreEdge(*P,FinalNodeOrder[j]))
1450 continue;
Misha Brukmanb4402432005-04-21 23:30:14 +00001451
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001452 if(CurrentSet.count(*P))
Alkis Evlogimenos20f1b0b2004-09-28 14:42:44 +00001453 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), *P) == FinalNodeOrder.end())
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001454 IntersectResult.insert(*P);
Tanya Lattnera6820d62004-05-08 16:12:10 +00001455 }
Misha Brukmanb4402432005-04-21 23:30:14 +00001456 }
Tanya Lattnera6820d62004-05-08 16:12:10 +00001457}
1458
Tanya Lattnera6820d62004-05-08 16:12:10 +00001459
Misha Brukmanb4402432005-04-21 23:30:14 +00001460
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001461
1462
1463void ModuloSchedulingPass::succIntersect(std::set<MSchedGraphNode*> &CurrentSet, std::set<MSchedGraphNode*> &IntersectResult) {
1464
Tanya Lattnera6820d62004-05-08 16:12:10 +00001465 for(unsigned j=0; j < FinalNodeOrder.size(); ++j) {
Misha Brukmanb4402432005-04-21 23:30:14 +00001466 for(MSchedGraphNode::succ_iterator P = FinalNodeOrder[j]->succ_begin(),
Tanya Lattnera6820d62004-05-08 16:12:10 +00001467 E = FinalNodeOrder[j]->succ_end(); P != E; ++P) {
1468
1469 //Check if we are supposed to ignore this edge or not
1470 if(ignoreEdge(FinalNodeOrder[j],*P))
1471 continue;
1472
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001473 if(CurrentSet.count(*P))
Alkis Evlogimenos20f1b0b2004-09-28 14:42:44 +00001474 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), *P) == FinalNodeOrder.end())
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001475 IntersectResult.insert(*P);
Tanya Lattnera6820d62004-05-08 16:12:10 +00001476 }
1477 }
1478}
1479
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001480void dumpIntersection(std::set<MSchedGraphNode*> &IntersectCurrent) {
Tanya Lattnera6820d62004-05-08 16:12:10 +00001481 std::cerr << "Intersection (";
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001482 for(std::set<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(), E = IntersectCurrent.end(); I != E; ++I)
Tanya Lattnera6820d62004-05-08 16:12:10 +00001483 std::cerr << **I << ", ";
1484 std::cerr << ")\n";
1485}
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001486
1487
1488
1489void ModuloSchedulingPass::orderNodes() {
Misha Brukmanb4402432005-04-21 23:30:14 +00001490
Tanya Lattner56807c62005-02-10 17:02:58 +00001491 TIME_REGION(X, "orderNodes");
1492
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001493 int BOTTOM_UP = 0;
1494 int TOP_DOWN = 1;
1495
Tanya Lattnera6820d62004-05-08 16:12:10 +00001496 //Set default order
1497 int order = BOTTOM_UP;
1498
Misha Brukmanb4402432005-04-21 23:30:14 +00001499
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001500 //Loop over all the sets and place them in the final node order
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001501 for(std::vector<std::set<MSchedGraphNode*> >::iterator CurrentSet = partialOrder.begin(), E= partialOrder.end(); CurrentSet != E; ++CurrentSet) {
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001502
Tanya Lattnera6820d62004-05-08 16:12:10 +00001503 DEBUG(std::cerr << "Processing set in S\n");
Tanya Lattner081fbd12004-07-30 23:36:10 +00001504 DEBUG(dumpIntersection(*CurrentSet));
1505
Tanya Lattnera6820d62004-05-08 16:12:10 +00001506 //Result of intersection
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001507 std::set<MSchedGraphNode*> IntersectCurrent;
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001508
Tanya Lattnera6820d62004-05-08 16:12:10 +00001509 predIntersect(*CurrentSet, IntersectCurrent);
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001510
1511 //If the intersection of predecessor and current set is not empty
1512 //sort nodes bottom up
Tanya Lattnera6820d62004-05-08 16:12:10 +00001513 if(IntersectCurrent.size() != 0) {
1514 DEBUG(std::cerr << "Final Node Order Predecessors and Current Set interesection is NOT empty\n");
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001515 order = BOTTOM_UP;
Tanya Lattnera6820d62004-05-08 16:12:10 +00001516 }
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001517 //If empty, use successors
1518 else {
Tanya Lattnera6820d62004-05-08 16:12:10 +00001519 DEBUG(std::cerr << "Final Node Order Predecessors and Current Set interesection is empty\n");
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001520
Tanya Lattnera6820d62004-05-08 16:12:10 +00001521 succIntersect(*CurrentSet, IntersectCurrent);
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001522
1523 //sort top-down
Tanya Lattnera6820d62004-05-08 16:12:10 +00001524 if(IntersectCurrent.size() != 0) {
1525 DEBUG(std::cerr << "Final Node Order Successors and Current Set interesection is NOT empty\n");
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001526 order = TOP_DOWN;
Tanya Lattnera6820d62004-05-08 16:12:10 +00001527 }
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001528 else {
Tanya Lattnera6820d62004-05-08 16:12:10 +00001529 DEBUG(std::cerr << "Final Node Order Successors and Current Set interesection is empty\n");
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001530 //Find node with max ASAP in current Set
1531 MSchedGraphNode *node;
1532 int maxASAP = 0;
Tanya Lattnera6820d62004-05-08 16:12:10 +00001533 DEBUG(std::cerr << "Using current set of size " << CurrentSet->size() << "to find max ASAP\n");
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001534 for(std::set<MSchedGraphNode*>::iterator J = CurrentSet->begin(), JE = CurrentSet->end(); J != JE; ++J) {
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001535 //Get node attributes
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001536 MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*J)->second;
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001537 //assert(nodeAttr != nodeToAttributesMap.end() && "Node not in attributes map!");
Misha Brukmanb4402432005-04-21 23:30:14 +00001538
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001539 if(maxASAP <= nodeAttr.ASAP) {
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001540 maxASAP = nodeAttr.ASAP;
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001541 node = *J;
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001542 }
1543 }
Tanya Lattnera6820d62004-05-08 16:12:10 +00001544 assert(node != 0 && "In node ordering node should not be null");
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001545 IntersectCurrent.insert(node);
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001546 order = BOTTOM_UP;
1547 }
1548 }
Misha Brukmanb4402432005-04-21 23:30:14 +00001549
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001550 //Repeat until all nodes are put into the final order from current set
Tanya Lattnera6820d62004-05-08 16:12:10 +00001551 while(IntersectCurrent.size() > 0) {
1552
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001553 if(order == TOP_DOWN) {
Tanya Lattnera6820d62004-05-08 16:12:10 +00001554 DEBUG(std::cerr << "Order is TOP DOWN\n");
1555
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001556 while(IntersectCurrent.size() > 0) {
Tanya Lattnera6820d62004-05-08 16:12:10 +00001557 DEBUG(std::cerr << "Intersection is not empty, so find heighest height\n");
Misha Brukmanb4402432005-04-21 23:30:14 +00001558
Tanya Lattnera6820d62004-05-08 16:12:10 +00001559 int MOB = 0;
1560 int height = 0;
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001561 MSchedGraphNode *highestHeightNode = *(IntersectCurrent.begin());
Misha Brukmanb4402432005-04-21 23:30:14 +00001562
Tanya Lattnera6820d62004-05-08 16:12:10 +00001563 //Find node in intersection with highest heigh and lowest MOB
Misha Brukmanb4402432005-04-21 23:30:14 +00001564 for(std::set<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(),
Tanya Lattnera6820d62004-05-08 16:12:10 +00001565 E = IntersectCurrent.end(); I != E; ++I) {
Misha Brukmanb4402432005-04-21 23:30:14 +00001566
Tanya Lattnera6820d62004-05-08 16:12:10 +00001567 //Get current nodes properties
1568 MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*I)->second;
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001569
Tanya Lattnera6820d62004-05-08 16:12:10 +00001570 if(height < nodeAttr.height) {
1571 highestHeightNode = *I;
1572 height = nodeAttr.height;
1573 MOB = nodeAttr.MOB;
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001574 }
Tanya Lattnera6820d62004-05-08 16:12:10 +00001575 else if(height == nodeAttr.height) {
1576 if(MOB > nodeAttr.height) {
1577 highestHeightNode = *I;
1578 height = nodeAttr.height;
1579 MOB = nodeAttr.MOB;
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001580 }
1581 }
1582 }
Misha Brukmanb4402432005-04-21 23:30:14 +00001583
Tanya Lattnera6820d62004-05-08 16:12:10 +00001584 //Append our node with greatest height to the NodeOrder
Alkis Evlogimenos20f1b0b2004-09-28 14:42:44 +00001585 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), highestHeightNode) == FinalNodeOrder.end()) {
Tanya Lattnera6820d62004-05-08 16:12:10 +00001586 DEBUG(std::cerr << "Adding node to Final Order: " << *highestHeightNode << "\n");
1587 FinalNodeOrder.push_back(highestHeightNode);
1588 }
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001589
1590 //Remove V from IntersectOrder
Misha Brukmanb4402432005-04-21 23:30:14 +00001591 IntersectCurrent.erase(std::find(IntersectCurrent.begin(),
Tanya Lattnera6820d62004-05-08 16:12:10 +00001592 IntersectCurrent.end(), highestHeightNode));
1593
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001594
1595 //Intersect V's successors with CurrentSet
Tanya Lattnera6820d62004-05-08 16:12:10 +00001596 for(MSchedGraphNode::succ_iterator P = highestHeightNode->succ_begin(),
1597 E = highestHeightNode->succ_end(); P != E; ++P) {
Misha Brukmanb4402432005-04-21 23:30:14 +00001598 //if(lower_bound(CurrentSet->begin(),
Tanya Lattnera6820d62004-05-08 16:12:10 +00001599 // CurrentSet->end(), *P) != CurrentSet->end()) {
Misha Brukmanb4402432005-04-21 23:30:14 +00001600 if(std::find(CurrentSet->begin(), CurrentSet->end(), *P) != CurrentSet->end()) {
Tanya Lattnera6820d62004-05-08 16:12:10 +00001601 if(ignoreEdge(highestHeightNode, *P))
1602 continue;
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001603 //If not already in Intersect, add
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001604 if(!IntersectCurrent.count(*P))
1605 IntersectCurrent.insert(*P);
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001606 }
1607 }
1608 } //End while loop over Intersect Size
1609
1610 //Change direction
1611 order = BOTTOM_UP;
1612
1613 //Reset Intersect to reflect changes in OrderNodes
1614 IntersectCurrent.clear();
Tanya Lattnera6820d62004-05-08 16:12:10 +00001615 predIntersect(*CurrentSet, IntersectCurrent);
1616
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001617 } //End If TOP_DOWN
1618
1619 //Begin if BOTTOM_UP
Tanya Lattnera6820d62004-05-08 16:12:10 +00001620 else {
1621 DEBUG(std::cerr << "Order is BOTTOM UP\n");
1622 while(IntersectCurrent.size() > 0) {
1623 DEBUG(std::cerr << "Intersection of size " << IntersectCurrent.size() << ", finding highest depth\n");
1624
1625 //dump intersection
1626 DEBUG(dumpIntersection(IntersectCurrent));
1627 //Get node with highest depth, if a tie, use one with lowest
1628 //MOB
1629 int MOB = 0;
1630 int depth = 0;
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001631 MSchedGraphNode *highestDepthNode = *(IntersectCurrent.begin());
Misha Brukmanb4402432005-04-21 23:30:14 +00001632
1633 for(std::set<MSchedGraphNode*>::iterator I = IntersectCurrent.begin(),
Tanya Lattnera6820d62004-05-08 16:12:10 +00001634 E = IntersectCurrent.end(); I != E; ++I) {
1635 //Find node attribute in graph
1636 MSNodeAttributes nodeAttr= nodeToAttributesMap.find(*I)->second;
Misha Brukmanb4402432005-04-21 23:30:14 +00001637
Tanya Lattnera6820d62004-05-08 16:12:10 +00001638 if(depth < nodeAttr.depth) {
1639 highestDepthNode = *I;
1640 depth = nodeAttr.depth;
1641 MOB = nodeAttr.MOB;
1642 }
1643 else if(depth == nodeAttr.depth) {
1644 if(MOB > nodeAttr.MOB) {
1645 highestDepthNode = *I;
1646 depth = nodeAttr.depth;
1647 MOB = nodeAttr.MOB;
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001648 }
1649 }
Tanya Lattnera6820d62004-05-08 16:12:10 +00001650 }
Misha Brukmanb4402432005-04-21 23:30:14 +00001651
1652
Tanya Lattnera6820d62004-05-08 16:12:10 +00001653
1654 //Append highest depth node to the NodeOrder
Alkis Evlogimenos20f1b0b2004-09-28 14:42:44 +00001655 if(std::find(FinalNodeOrder.begin(), FinalNodeOrder.end(), highestDepthNode) == FinalNodeOrder.end()) {
Tanya Lattnera6820d62004-05-08 16:12:10 +00001656 DEBUG(std::cerr << "Adding node to Final Order: " << *highestDepthNode << "\n");
1657 FinalNodeOrder.push_back(highestDepthNode);
1658 }
1659 //Remove heightestDepthNode from IntersectOrder
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001660 IntersectCurrent.erase(highestDepthNode);
Misha Brukmanb4402432005-04-21 23:30:14 +00001661
Tanya Lattnera6820d62004-05-08 16:12:10 +00001662
1663 //Intersect heightDepthNode's pred with CurrentSet
Misha Brukmanb4402432005-04-21 23:30:14 +00001664 for(MSchedGraphNode::pred_iterator P = highestDepthNode->pred_begin(),
Tanya Lattnera6820d62004-05-08 16:12:10 +00001665 E = highestDepthNode->pred_end(); P != E; ++P) {
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001666 if(CurrentSet->count(*P)) {
Tanya Lattnera6820d62004-05-08 16:12:10 +00001667 if(ignoreEdge(*P, highestDepthNode))
1668 continue;
Misha Brukmanb4402432005-04-21 23:30:14 +00001669
Tanya Lattnera6820d62004-05-08 16:12:10 +00001670 //If not already in Intersect, add
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001671 if(!IntersectCurrent.count(*P))
1672 IntersectCurrent.insert(*P);
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001673 }
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001674 }
Misha Brukmanb4402432005-04-21 23:30:14 +00001675
Tanya Lattnera6820d62004-05-08 16:12:10 +00001676 } //End while loop over Intersect Size
1677
1678 //Change order
1679 order = TOP_DOWN;
1680
1681 //Reset IntersectCurrent to reflect changes in OrderNodes
1682 IntersectCurrent.clear();
1683 succIntersect(*CurrentSet, IntersectCurrent);
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001684 } //End if BOTTOM_DOWN
1685
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00001686 DEBUG(std::cerr << "Current Intersection Size: " << IntersectCurrent.size() << "\n");
Tanya Lattnera6820d62004-05-08 16:12:10 +00001687 }
1688 //End Wrapping while loop
Misha Brukmanb4402432005-04-21 23:30:14 +00001689 DEBUG(std::cerr << "Ending Size of Current Set: " << CurrentSet->size() << "\n");
Tanya Lattnera6820d62004-05-08 16:12:10 +00001690 }//End for over all sets of nodes
Misha Brukmanb4402432005-04-21 23:30:14 +00001691
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00001692 //FIXME: As the algorithm stands it will NEVER add an instruction such as ba (with no
1693 //data dependencies) to the final order. We add this manually. It will always be
1694 //in the last set of S since its not part of a recurrence
1695 //Loop over all the sets and place them in the final node order
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001696 std::vector<std::set<MSchedGraphNode*> > ::reverse_iterator LastSet = partialOrder.rbegin();
1697 for(std::set<MSchedGraphNode*>::iterator CurrentNode = LastSet->begin(), LastNode = LastSet->end();
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00001698 CurrentNode != LastNode; ++CurrentNode) {
1699 if((*CurrentNode)->getInst()->getOpcode() == V9::BA)
1700 FinalNodeOrder.push_back(*CurrentNode);
1701 }
Tanya Lattnera6820d62004-05-08 16:12:10 +00001702 //Return final Order
1703 //return FinalNodeOrder;
1704}
1705
Tanya Lattner42ed1482005-04-22 06:32:48 +00001706bool ModuloSchedulingPass::computeSchedule(const MachineBasicBlock *BB, MSchedGraph *MSG) {
Tanya Lattnera6820d62004-05-08 16:12:10 +00001707
Tanya Lattner56807c62005-02-10 17:02:58 +00001708 TIME_REGION(X, "computeSchedule");
1709
Tanya Lattnera6820d62004-05-08 16:12:10 +00001710 bool success = false;
Misha Brukmanb4402432005-04-21 23:30:14 +00001711
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001712 //FIXME: Should be set to max II of the original loop
1713 //Cap II in order to prevent infinite loop
Tanya Lattner42ed1482005-04-22 06:32:48 +00001714 int capII = MSG->totalDelay();
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001715
Tanya Lattnera6820d62004-05-08 16:12:10 +00001716 while(!success) {
Tanya Lattnerd8cc4fa2004-11-29 04:39:47 +00001717
Tanya Lattnera31ad512005-02-23 02:01:42 +00001718 //Keep track of branches, but do not insert into the schedule
1719 std::vector<MSchedGraphNode*> branches;
Tanya Lattnerd8cc4fa2004-11-29 04:39:47 +00001720
Tanya Lattnera6820d62004-05-08 16:12:10 +00001721 //Loop over the final node order and process each node
Misha Brukmanb4402432005-04-21 23:30:14 +00001722 for(std::vector<MSchedGraphNode*>::iterator I = FinalNodeOrder.begin(),
Tanya Lattnera6820d62004-05-08 16:12:10 +00001723 E = FinalNodeOrder.end(); I != E; ++I) {
Misha Brukmanb4402432005-04-21 23:30:14 +00001724
Tanya Lattnera6820d62004-05-08 16:12:10 +00001725 //CalculateEarly and Late start
1726 int EarlyStart = -1;
1727 int LateStart = 99999; //Set to something higher then we would ever expect (FIXME)
1728 bool hasSucc = false;
1729 bool hasPred = false;
Tanya Lattner13417b52005-03-23 01:47:20 +00001730 bool sched;
1731
1732 if((*I)->isBranch())
1733 if((*I)->hasPredecessors())
1734 sched = true;
1735 else
1736 sched = false;
1737 else
1738 sched = true;
1739
1740 if(sched) {
Tanya Lattnera066df62004-05-26 06:27:18 +00001741 //Loop over nodes in the schedule and determine if they are predecessors
1742 //or successors of the node we are trying to schedule
Misha Brukmanb4402432005-04-21 23:30:14 +00001743 for(MSSchedule::schedule_iterator nodesByCycle = schedule.begin(), nodesByCycleEnd = schedule.end();
Tanya Lattnera066df62004-05-26 06:27:18 +00001744 nodesByCycle != nodesByCycleEnd; ++nodesByCycle) {
Misha Brukmanb4402432005-04-21 23:30:14 +00001745
Tanya Lattnera066df62004-05-26 06:27:18 +00001746 //For this cycle, get the vector of nodes schedule and loop over it
1747 for(std::vector<MSchedGraphNode*>::iterator schedNode = nodesByCycle->second.begin(), SNE = nodesByCycle->second.end(); schedNode != SNE; ++schedNode) {
Misha Brukmanb4402432005-04-21 23:30:14 +00001748
Tanya Lattnera066df62004-05-26 06:27:18 +00001749 if((*I)->isPredecessor(*schedNode)) {
Tanya Lattnera31ad512005-02-23 02:01:42 +00001750 int diff = (*I)->getInEdge(*schedNode).getIteDiff();
1751 int ES_Temp = nodesByCycle->first + (*schedNode)->getLatency() - diff * II;
1752 DEBUG(std::cerr << "Diff: " << diff << " Cycle: " << nodesByCycle->first << "\n");
1753 DEBUG(std::cerr << "Temp EarlyStart: " << ES_Temp << " Prev EarlyStart: " << EarlyStart << "\n");
1754 EarlyStart = std::max(EarlyStart, ES_Temp);
1755 hasPred = true;
Tanya Lattnera6820d62004-05-08 16:12:10 +00001756 }
Tanya Lattnera066df62004-05-26 06:27:18 +00001757 if((*I)->isSuccessor(*schedNode)) {
Tanya Lattnera31ad512005-02-23 02:01:42 +00001758 int diff = (*schedNode)->getInEdge(*I).getIteDiff();
1759 int LS_Temp = nodesByCycle->first - (*I)->getLatency() + diff * II;
1760 DEBUG(std::cerr << "Diff: " << diff << " Cycle: " << nodesByCycle->first << "\n");
1761 DEBUG(std::cerr << "Temp LateStart: " << LS_Temp << " Prev LateStart: " << LateStart << "\n");
1762 LateStart = std::min(LateStart, LS_Temp);
1763 hasSucc = true;
Tanya Lattnera6820d62004-05-08 16:12:10 +00001764 }
Tanya Lattnera6820d62004-05-08 16:12:10 +00001765 }
1766 }
1767 }
Tanya Lattnera066df62004-05-26 06:27:18 +00001768 else {
Tanya Lattnera31ad512005-02-23 02:01:42 +00001769 branches.push_back(*I);
1770 continue;
1771 }
1772
1773 //Check if this node is a pred or succ to a branch, and restrict its placement
1774 //even though the branch is not in the schedule
1775 int count = branches.size();
1776 for(std::vector<MSchedGraphNode*>::iterator B = branches.begin(), BE = branches.end();
1777 B != BE; ++B) {
1778 if((*I)->isPredecessor(*B)) {
1779 int diff = (*I)->getInEdge(*B).getIteDiff();
Tanya Lattner13417b52005-03-23 01:47:20 +00001780 int ES_Temp = (II+count-1) + (*B)->getLatency() - diff * II;
1781 DEBUG(std::cerr << "Diff: " << diff << " Cycle: " << (II+count)-1 << "\n");
Tanya Lattnera31ad512005-02-23 02:01:42 +00001782 DEBUG(std::cerr << "Temp EarlyStart: " << ES_Temp << " Prev EarlyStart: " << EarlyStart << "\n");
1783 EarlyStart = std::max(EarlyStart, ES_Temp);
1784 hasPred = true;
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00001785 }
Tanya Lattnera31ad512005-02-23 02:01:42 +00001786
1787 if((*I)->isSuccessor(*B)) {
1788 int diff = (*B)->getInEdge(*I).getIteDiff();
Tanya Lattner13417b52005-03-23 01:47:20 +00001789 int LS_Temp = (II+count-1) - (*I)->getLatency() + diff * II;
1790 DEBUG(std::cerr << "Diff: " << diff << " Cycle: " << (II+count-1) << "\n");
Tanya Lattnera31ad512005-02-23 02:01:42 +00001791 DEBUG(std::cerr << "Temp LateStart: " << LS_Temp << " Prev LateStart: " << LateStart << "\n");
1792 LateStart = std::min(LateStart, LS_Temp);
1793 hasSucc = true;
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00001794 }
Tanya Lattnera31ad512005-02-23 02:01:42 +00001795
1796 count--;
Tanya Lattnera066df62004-05-26 06:27:18 +00001797 }
Misha Brukmanb4402432005-04-21 23:30:14 +00001798
Tanya Lattnera6820d62004-05-08 16:12:10 +00001799 //Check if the node has no pred or successors and set Early Start to its ASAP
1800 if(!hasSucc && !hasPred)
1801 EarlyStart = nodeToAttributesMap.find(*I)->second.ASAP;
Misha Brukmanb4402432005-04-21 23:30:14 +00001802
Tanya Lattnera31ad512005-02-23 02:01:42 +00001803 DEBUG(std::cerr << "Has Successors: " << hasSucc << ", Has Pred: " << hasPred << "\n");
1804 DEBUG(std::cerr << "EarlyStart: " << EarlyStart << ", LateStart: " << LateStart << "\n");
1805
Tanya Lattnera6820d62004-05-08 16:12:10 +00001806 //Now, try to schedule this node depending upon its pred and successor in the schedule
1807 //already
1808 if(!hasSucc && hasPred)
1809 success = scheduleNode(*I, EarlyStart, (EarlyStart + II -1));
1810 else if(!hasPred && hasSucc)
1811 success = scheduleNode(*I, LateStart, (LateStart - II +1));
Tanya Lattnerc227ad22005-01-18 04:15:41 +00001812 else if(hasPred && hasSucc) {
Tanya Lattnera31ad512005-02-23 02:01:42 +00001813 if(EarlyStart > LateStart) {
Tanya Lattner13417b52005-03-23 01:47:20 +00001814 success = false;
1815 //LateStart = EarlyStart;
Tanya Lattnera31ad512005-02-23 02:01:42 +00001816 DEBUG(std::cerr << "Early Start can not be later then the late start cycle, schedule fails\n");
1817 }
Tanya Lattner13417b52005-03-23 01:47:20 +00001818 else
1819 success = scheduleNode(*I, EarlyStart, std::min(LateStart, (EarlyStart + II -1)));
Tanya Lattnerc227ad22005-01-18 04:15:41 +00001820 }
Tanya Lattnera6820d62004-05-08 16:12:10 +00001821 else
1822 success = scheduleNode(*I, EarlyStart, EarlyStart + II - 1);
Misha Brukmanb4402432005-04-21 23:30:14 +00001823
Tanya Lattnera6820d62004-05-08 16:12:10 +00001824 if(!success) {
Tanya Lattner42ed1482005-04-22 06:32:48 +00001825 ++II;
Tanya Lattnera6820d62004-05-08 16:12:10 +00001826 schedule.clear();
1827 break;
1828 }
Misha Brukmanb4402432005-04-21 23:30:14 +00001829
Tanya Lattnera6820d62004-05-08 16:12:10 +00001830 }
Tanya Lattnera066df62004-05-26 06:27:18 +00001831
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001832 if(success) {
1833 DEBUG(std::cerr << "Constructing Schedule Kernel\n");
Tanya Lattner13417b52005-03-23 01:47:20 +00001834 success = schedule.constructKernel(II, branches, indVarInstrs[BB]);
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001835 DEBUG(std::cerr << "Done Constructing Schedule Kernel\n");
1836 if(!success) {
1837 ++II;
1838 schedule.clear();
1839 }
Tanya Lattner13417b52005-03-23 01:47:20 +00001840 DEBUG(std::cerr << "Final II: " << II << "\n");
Tanya Lattner42ed1482005-04-22 06:32:48 +00001841 FinalIISum += II;
Tanya Lattnera066df62004-05-26 06:27:18 +00001842 }
Misha Brukmanb4402432005-04-21 23:30:14 +00001843
Tanya Lattnera31ad512005-02-23 02:01:42 +00001844 if(II >= capII) {
1845 DEBUG(std::cerr << "Maximum II reached, giving up\n");
Tanya Lattner201e9722004-12-02 07:22:15 +00001846 return false;
Tanya Lattnera31ad512005-02-23 02:01:42 +00001847 }
Tanya Lattner201e9722004-12-02 07:22:15 +00001848
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001849 assert(II < capII && "The II should not exceed the original loop number of cycles");
Misha Brukmanb4402432005-04-21 23:30:14 +00001850 }
Tanya Lattner201e9722004-12-02 07:22:15 +00001851 return true;
Tanya Lattnera6820d62004-05-08 16:12:10 +00001852}
1853
1854
Misha Brukmanb4402432005-04-21 23:30:14 +00001855bool ModuloSchedulingPass::scheduleNode(MSchedGraphNode *node,
Tanya Lattnera6820d62004-05-08 16:12:10 +00001856 int start, int end) {
1857 bool success = false;
1858
1859 DEBUG(std::cerr << *node << " (Start Cycle: " << start << ", End Cycle: " << end << ")\n");
1860
Tanya Lattnera6820d62004-05-08 16:12:10 +00001861 //Make sure start and end are not negative
Tanya Lattner13417b52005-03-23 01:47:20 +00001862 //if(start < 0) {
1863 //start = 0;
Misha Brukmanb4402432005-04-21 23:30:14 +00001864
Tanya Lattner13417b52005-03-23 01:47:20 +00001865 //}
1866 //if(end < 0)
1867 //end = 0;
Tanya Lattnera6820d62004-05-08 16:12:10 +00001868
1869 bool forward = true;
1870 if(start > end)
1871 forward = false;
1872
Tanya Lattnera6820d62004-05-08 16:12:10 +00001873 bool increaseSC = true;
Tanya Lattnera6820d62004-05-08 16:12:10 +00001874 int cycle = start ;
1875
1876
1877 while(increaseSC) {
Misha Brukmanb4402432005-04-21 23:30:14 +00001878
Tanya Lattnera6820d62004-05-08 16:12:10 +00001879 increaseSC = false;
1880
Tanya Lattnera066df62004-05-26 06:27:18 +00001881 increaseSC = schedule.insert(node, cycle);
Misha Brukmanb4402432005-04-21 23:30:14 +00001882
1883 if(!increaseSC)
Tanya Lattnera6820d62004-05-08 16:12:10 +00001884 return true;
1885
1886 //Increment cycle to try again
1887 if(forward) {
1888 ++cycle;
1889 DEBUG(std::cerr << "Increase cycle: " << cycle << "\n");
1890 if(cycle > end)
1891 return false;
1892 }
1893 else {
1894 --cycle;
1895 DEBUG(std::cerr << "Decrease cycle: " << cycle << "\n");
1896 if(cycle < end)
1897 return false;
1898 }
1899 }
Tanya Lattnera066df62004-05-26 06:27:18 +00001900
Tanya Lattnera6820d62004-05-08 16:12:10 +00001901 return success;
Tanya Lattnerdd10fbe2004-03-01 02:50:01 +00001902}
Tanya Lattnera066df62004-05-26 06:27:18 +00001903
Tanya Lattner13417b52005-03-23 01:47:20 +00001904void 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 +00001905
Tanya Lattner081fbd12004-07-30 23:36:10 +00001906 //Keep a map to easily know whats in the kernel
Tanya Lattnera066df62004-05-26 06:27:18 +00001907 std::map<int, std::set<const MachineInstr*> > inKernel;
1908 int maxStageCount = 0;
1909
Tanya Lattner201e9722004-12-02 07:22:15 +00001910 //Keep a map of new values we consumed in case they need to be added back
1911 std::map<Value*, std::map<int, Value*> > consumedValues;
1912
Tanya Lattner081fbd12004-07-30 23:36:10 +00001913 MSchedGraphNode *branch = 0;
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00001914 MSchedGraphNode *BAbranch = 0;
Tanya Lattner081fbd12004-07-30 23:36:10 +00001915
Tanya Lattner91964492005-03-29 20:35:10 +00001916 DEBUG(schedule.print(std::cerr));
Tanya Lattnerab9cf272004-11-22 20:41:24 +00001917
Tanya Lattner201e9722004-12-02 07:22:15 +00001918 std::vector<MSchedGraphNode*> branches;
1919
Tanya Lattnera066df62004-05-26 06:27:18 +00001920 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
1921 maxStageCount = std::max(maxStageCount, I->second);
Misha Brukmanb4402432005-04-21 23:30:14 +00001922
Tanya Lattnera066df62004-05-26 06:27:18 +00001923 //Put int the map so we know what instructions in each stage are in the kernel
Tanya Lattner13417b52005-03-23 01:47:20 +00001924 DEBUG(std::cerr << "Inserting instruction " << *(I->first) << " into map at stage " << I->second << "\n");
1925 inKernel[I->second].insert(I->first);
Tanya Lattnera066df62004-05-26 06:27:18 +00001926 }
1927
Tanya Lattner081fbd12004-07-30 23:36:10 +00001928 //Get target information to look at machine operands
1929 const TargetInstrInfo *mii = target.getInstrInfo();
1930
1931 //Now write the prologues
1932 for(int i = 0; i < maxStageCount; ++i) {
1933 BasicBlock *llvmBB = new BasicBlock("PROLOGUE", (Function*) (origBB->getBasicBlock()->getParent()));
Tanya Lattnera066df62004-05-26 06:27:18 +00001934 MachineBasicBlock *machineBB = new MachineBasicBlock(llvmBB);
Misha Brukmanb4402432005-04-21 23:30:14 +00001935
Tanya Lattner081fbd12004-07-30 23:36:10 +00001936 DEBUG(std::cerr << "i=" << i << "\n");
Tanya Lattner13417b52005-03-23 01:47:20 +00001937 for(int j = i; j >= 0; --j) {
Tanya Lattner081fbd12004-07-30 23:36:10 +00001938 for(MachineBasicBlock::const_iterator MI = origBB->begin(), ME = origBB->end(); ME != MI; ++MI) {
1939 if(inKernel[j].count(&*MI)) {
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00001940 MachineInstr *instClone = MI->clone();
1941 machineBB->push_back(instClone);
Tanya Lattner13417b52005-03-23 01:47:20 +00001942
1943 //If its a branch, insert a nop
1944 if(mii->isBranch(instClone->getOpcode()))
1945 BuildMI(machineBB, V9::NOP, 0);
Misha Brukmanb4402432005-04-21 23:30:14 +00001946
1947
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00001948 DEBUG(std::cerr << "Cloning: " << *MI << "\n");
1949
Tanya Lattner081fbd12004-07-30 23:36:10 +00001950 //After cloning, we may need to save the value that this instruction defines
1951 for(unsigned opNum=0; opNum < MI->getNumOperands(); ++opNum) {
Tanya Lattner13417b52005-03-23 01:47:20 +00001952 Instruction *tmp;
Misha Brukmanb4402432005-04-21 23:30:14 +00001953
Tanya Lattner081fbd12004-07-30 23:36:10 +00001954 //get machine operand
Tanya Lattner201e9722004-12-02 07:22:15 +00001955 MachineOperand &mOp = instClone->getOperand(opNum);
Tanya Lattner081fbd12004-07-30 23:36:10 +00001956 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef()) {
1957
Tanya Lattner081fbd12004-07-30 23:36:10 +00001958 //Check if this is a value we should save
1959 if(valuesToSave.count(mOp.getVRegValue())) {
1960 //Save copy in tmpInstruction
1961 tmp = new TmpInstruction(mOp.getVRegValue());
1962
Tanya Lattner444be612004-11-02 21:04:56 +00001963 //Add TmpInstruction to safe LLVM Instruction MCFI
1964 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnerd38a7602004-10-14 06:04:28 +00001965 tempMvec.addTemp((Value*) tmp);
1966
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00001967 DEBUG(std::cerr << "Value: " << *(mOp.getVRegValue()) << " New Value: " << *tmp << " Stage: " << i << "\n");
1968
1969 newValues[mOp.getVRegValue()][i]= tmp;
Tanya Lattner081fbd12004-07-30 23:36:10 +00001970 newValLocation[tmp] = machineBB;
1971
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00001972 DEBUG(std::cerr << "Machine Instr Operands: " << *(mOp.getVRegValue()) << ", 0, " << *tmp << "\n");
Tanya Lattner081fbd12004-07-30 23:36:10 +00001973
1974 //Create machine instruction and put int machineBB
Tanya Lattner13417b52005-03-23 01:47:20 +00001975 MachineInstr *saveValue;
1976 if(mOp.getVRegValue()->getType() == Type::FloatTy)
1977 saveValue = BuildMI(machineBB, V9::FMOVS, 3).addReg(mOp.getVRegValue()).addRegDef(tmp);
1978 else if(mOp.getVRegValue()->getType() == Type::DoubleTy)
1979 saveValue = BuildMI(machineBB, V9::FMOVD, 3).addReg(mOp.getVRegValue()).addRegDef(tmp);
Misha Brukmanb4402432005-04-21 23:30:14 +00001980 else
Tanya Lattner13417b52005-03-23 01:47:20 +00001981 saveValue = BuildMI(machineBB, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
1982
1983
Tanya Lattner081fbd12004-07-30 23:36:10 +00001984 DEBUG(std::cerr << "Created new machine instr: " << *saveValue << "\n");
1985 }
1986 }
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00001987
1988 //We may also need to update the value that we use if its from an earlier prologue
1989 if(j != 0) {
1990 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse()) {
Tanya Lattner201e9722004-12-02 07:22:15 +00001991 if(newValues.count(mOp.getVRegValue())) {
1992 if(newValues[mOp.getVRegValue()].count(i-1)) {
1993 Value *oldV = mOp.getVRegValue();
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00001994 DEBUG(std::cerr << "Replaced this value: " << mOp.getVRegValue() << " With:" << (newValues[mOp.getVRegValue()][i-1]) << "\n");
1995 //Update the operand with the right value
Tanya Lattner201e9722004-12-02 07:22:15 +00001996 mOp.setValueReg(newValues[mOp.getVRegValue()][i-1]);
1997
1998 //Remove this value since we have consumed it
1999 //NOTE: Should this only be done if j != maxStage?
2000 consumedValues[oldV][i-1] = (newValues[oldV][i-1]);
2001 DEBUG(std::cerr << "Deleted value: " << consumedValues[oldV][i-1] << "\n");
2002 newValues[oldV].erase(i-1);
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002003 }
Tanya Lattner201e9722004-12-02 07:22:15 +00002004 }
2005 else
2006 if(consumedValues.count(mOp.getVRegValue()))
2007 assert(!consumedValues[mOp.getVRegValue()].count(i-1) && "Found a case where we need the value");
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002008 }
2009 }
Tanya Lattner081fbd12004-07-30 23:36:10 +00002010 }
2011 }
Tanya Lattner50cbb9a2004-05-28 20:14:12 +00002012 }
Tanya Lattnera066df62004-05-26 06:27:18 +00002013 }
2014
Tanya Lattner081fbd12004-07-30 23:36:10 +00002015
Tanya Lattner13417b52005-03-23 01:47:20 +00002016 /*for(std::vector<MSchedGraphNode*>::iterator BR = branches.begin(), BE = branches.end(); BR != BE; ++BR) {
Misha Brukmanb4402432005-04-21 23:30:14 +00002017
Tanya Lattner201e9722004-12-02 07:22:15 +00002018 //Stick in branch at the end
2019 machineBB->push_back((*BR)->getInst()->clone());
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00002020
Tanya Lattner201e9722004-12-02 07:22:15 +00002021 //Add nop
2022 BuildMI(machineBB, V9::NOP, 0);
Tanya Lattner13417b52005-03-23 01:47:20 +00002023 }*/
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00002024
Tanya Lattner081fbd12004-07-30 23:36:10 +00002025
Misha Brukmanb4402432005-04-21 23:30:14 +00002026 (((MachineBasicBlock*)origBB)->getParent())->getBasicBlockList().push_back(machineBB);
Tanya Lattnera066df62004-05-26 06:27:18 +00002027 prologues.push_back(machineBB);
2028 llvm_prologues.push_back(llvmBB);
2029 }
2030}
2031
Tanya Lattner13417b52005-03-23 01:47:20 +00002032void 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 +00002033
Tanya Lattner50cbb9a2004-05-28 20:14:12 +00002034 std::map<int, std::set<const MachineInstr*> > inKernel;
Misha Brukmanb4402432005-04-21 23:30:14 +00002035
Tanya Lattner50cbb9a2004-05-28 20:14:12 +00002036 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
Misha Brukmanb4402432005-04-21 23:30:14 +00002037
Tanya Lattner50cbb9a2004-05-28 20:14:12 +00002038 //Ignore the branch, we will handle this separately
Tanya Lattner13417b52005-03-23 01:47:20 +00002039 //if(I->first->isBranch())
2040 //continue;
Tanya Lattner50cbb9a2004-05-28 20:14:12 +00002041
2042 //Put int the map so we know what instructions in each stage are in the kernel
Tanya Lattner13417b52005-03-23 01:47:20 +00002043 inKernel[I->second].insert(I->first);
Tanya Lattner50cbb9a2004-05-28 20:14:12 +00002044 }
2045
Tanya Lattner081fbd12004-07-30 23:36:10 +00002046 std::map<Value*, Value*> valPHIs;
2047
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002048 //some debug stuff, will remove later
2049 DEBUG(for(std::map<Value*, std::map<int, Value*> >::iterator V = newValues.begin(), E = newValues.end(); V !=E; ++V) {
2050 std::cerr << "Old Value: " << *(V->first) << "\n";
2051 for(std::map<int, Value*>::iterator I = V->second.begin(), IE = V->second.end(); I != IE; ++I)
2052 std::cerr << "Stage: " << I->first << " Value: " << *(I->second) << "\n";
2053 });
2054
2055 //some debug stuff, will remove later
2056 DEBUG(for(std::map<Value*, std::map<int, Value*> >::iterator V = kernelPHIs.begin(), E = kernelPHIs.end(); V !=E; ++V) {
2057 std::cerr << "Old Value: " << *(V->first) << "\n";
2058 for(std::map<int, Value*>::iterator I = V->second.begin(), IE = V->second.end(); I != IE; ++I)
2059 std::cerr << "Stage: " << I->first << " Value: " << *(I->second) << "\n";
2060 });
2061
Tanya Lattner50cbb9a2004-05-28 20:14:12 +00002062 //Now write the epilogues
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002063 for(int i = schedule.getMaxStage()-1; i >= 0; --i) {
Tanya Lattner081fbd12004-07-30 23:36:10 +00002064 BasicBlock *llvmBB = new BasicBlock("EPILOGUE", (Function*) (origBB->getBasicBlock()->getParent()));
Tanya Lattner50cbb9a2004-05-28 20:14:12 +00002065 MachineBasicBlock *machineBB = new MachineBasicBlock(llvmBB);
Misha Brukmanb4402432005-04-21 23:30:14 +00002066
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002067 DEBUG(std::cerr << " Epilogue #: " << i << "\n");
Tanya Lattner081fbd12004-07-30 23:36:10 +00002068
Tanya Lattner081fbd12004-07-30 23:36:10 +00002069
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002070 std::map<Value*, int> inEpilogue;
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002071
2072 for(MachineBasicBlock::const_iterator MI = origBB->begin(), ME = origBB->end(); ME != MI; ++MI) {
2073 for(int j=schedule.getMaxStage(); j > i; --j) {
Tanya Lattner081fbd12004-07-30 23:36:10 +00002074 if(inKernel[j].count(&*MI)) {
2075 DEBUG(std::cerr << "Cloning instruction " << *MI << "\n");
2076 MachineInstr *clone = MI->clone();
Misha Brukmanb4402432005-04-21 23:30:14 +00002077
Tanya Lattner081fbd12004-07-30 23:36:10 +00002078 //Update operands that need to use the result from the phi
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002079 for(unsigned opNum=0; opNum < clone->getNumOperands(); ++opNum) {
Tanya Lattner081fbd12004-07-30 23:36:10 +00002080 //get machine operand
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002081 const MachineOperand &mOp = clone->getOperand(opNum);
Misha Brukmanb4402432005-04-21 23:30:14 +00002082
Tanya Lattner081fbd12004-07-30 23:36:10 +00002083 if((mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse())) {
Misha Brukmanb4402432005-04-21 23:30:14 +00002084
Tanya Lattner13417b52005-03-23 01:47:20 +00002085 DEBUG(std::cerr << "Writing PHI for " << (mOp.getVRegValue()) << "\n");
Misha Brukmanb4402432005-04-21 23:30:14 +00002086
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002087 //If this is the last instructions for the max iterations ago, don't update operands
2088 if(inEpilogue.count(mOp.getVRegValue()))
2089 if(inEpilogue[mOp.getVRegValue()] == i)
2090 continue;
Misha Brukmanb4402432005-04-21 23:30:14 +00002091
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002092 //Quickly write appropriate phis for this operand
2093 if(newValues.count(mOp.getVRegValue())) {
2094 if(newValues[mOp.getVRegValue()].count(i)) {
2095 Instruction *tmp = new TmpInstruction(newValues[mOp.getVRegValue()][i]);
Misha Brukmanb4402432005-04-21 23:30:14 +00002096
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002097 //Get machine code for this instruction
Tanya Lattner444be612004-11-02 21:04:56 +00002098 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002099 tempMvec.addTemp((Value*) tmp);
2100
Tanya Lattner13417b52005-03-23 01:47:20 +00002101 //assert of no kernelPHI for this value
2102 assert(kernelPHIs[mOp.getVRegValue()][i] !=0 && "Must have final kernel phi to construct epilogue phi");
2103
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002104 MachineInstr *saveValue = BuildMI(machineBB, V9::PHI, 3).addReg(newValues[mOp.getVRegValue()][i]).addReg(kernelPHIs[mOp.getVRegValue()][i]).addRegDef(tmp);
2105 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
2106 valPHIs[mOp.getVRegValue()] = tmp;
2107 }
2108 }
Misha Brukmanb4402432005-04-21 23:30:14 +00002109
Tanya Lattner081fbd12004-07-30 23:36:10 +00002110 if(valPHIs.count(mOp.getVRegValue())) {
2111 //Update the operand in the cloned instruction
Misha Brukmanb4402432005-04-21 23:30:14 +00002112 clone->getOperand(opNum).setValueReg(valPHIs[mOp.getVRegValue()]);
Tanya Lattner081fbd12004-07-30 23:36:10 +00002113 }
2114 }
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002115 else if((mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef())) {
2116 inEpilogue[mOp.getVRegValue()] = i;
2117 }
Tanya Lattner081fbd12004-07-30 23:36:10 +00002118 }
2119 machineBB->push_back(clone);
2120 }
2121 }
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002122 }
Tanya Lattner081fbd12004-07-30 23:36:10 +00002123
Tanya Lattner50cbb9a2004-05-28 20:14:12 +00002124 (((MachineBasicBlock*)origBB)->getParent())->getBasicBlockList().push_back(machineBB);
2125 epilogues.push_back(machineBB);
2126 llvm_epilogues.push_back(llvmBB);
Misha Brukmanb4402432005-04-21 23:30:14 +00002127
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002128 DEBUG(std::cerr << "EPILOGUE #" << i << "\n");
2129 DEBUG(machineBB->print(std::cerr));
Tanya Lattner50cbb9a2004-05-28 20:14:12 +00002130 }
Tanya Lattner081fbd12004-07-30 23:36:10 +00002131}
2132
Tanya Lattner13417b52005-03-23 01:47:20 +00002133void 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 +00002134
Tanya Lattner081fbd12004-07-30 23:36:10 +00002135 //Keep track of operands that are read and saved from a previous iteration. The new clone
2136 //instruction will use the result of the phi instead.
2137 std::map<Value*, Value*> finalPHIValue;
2138 std::map<Value*, Value*> kernelValue;
2139
Tanya Lattnerc0d9dcd2004-12-03 05:25:22 +00002140 //Branches are a special case
2141 std::vector<MachineInstr*> branches;
2142
Tanya Lattner13417b52005-03-23 01:47:20 +00002143 //Get target information to look at machine operands
2144 const TargetInstrInfo *mii = target.getInstrInfo();
Misha Brukmanb4402432005-04-21 23:30:14 +00002145
Tanya Lattner13417b52005-03-23 01:47:20 +00002146 //Create TmpInstructions for the final phis
2147 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
Tanya Lattner081fbd12004-07-30 23:36:10 +00002148
Tanya Lattner13417b52005-03-23 01:47:20 +00002149 DEBUG(std::cerr << "Stage: " << I->second << " Inst: " << *(I->first) << "\n";);
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002150
Tanya Lattner13417b52005-03-23 01:47:20 +00002151 /*if(I->first->isBranch()) {
Tanya Lattnerc0d9dcd2004-12-03 05:25:22 +00002152 //Clone instruction
2153 const MachineInstr *inst = I->first->getInst();
2154 MachineInstr *instClone = inst->clone();
2155 branches.push_back(instClone);
Tanya Lattnerc227ad22005-01-18 04:15:41 +00002156 continue;
Tanya Lattner13417b52005-03-23 01:47:20 +00002157 }*/
Misha Brukmanb4402432005-04-21 23:30:14 +00002158
Tanya Lattner081fbd12004-07-30 23:36:10 +00002159 //Clone instruction
Tanya Lattner13417b52005-03-23 01:47:20 +00002160 const MachineInstr *inst = I->first;
Tanya Lattner081fbd12004-07-30 23:36:10 +00002161 MachineInstr *instClone = inst->clone();
Tanya Lattner081fbd12004-07-30 23:36:10 +00002162
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002163 //Insert into machine basic block
2164 machineBB->push_back(instClone);
2165
Tanya Lattner13417b52005-03-23 01:47:20 +00002166 if(mii->isBranch(instClone->getOpcode()))
2167 BuildMI(machineBB, V9::NOP, 0);
2168
Tanya Lattner7beb51c2004-11-16 21:31:37 +00002169 DEBUG(std::cerr << "Cloned Inst: " << *instClone << "\n");
2170
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002171 //Loop over Machine Operands
2172 for(unsigned i=0; i < inst->getNumOperands(); ++i) {
2173 //get machine operand
2174 const MachineOperand &mOp = inst->getOperand(i);
Misha Brukmanb4402432005-04-21 23:30:14 +00002175
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002176 if(I->second != 0) {
Tanya Lattner081fbd12004-07-30 23:36:10 +00002177 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse()) {
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002178
2179 //Check to see where this operand is defined if this instruction is from max stage
2180 if(I->second == schedule.getMaxStage()) {
2181 DEBUG(std::cerr << "VREG: " << *(mOp.getVRegValue()) << "\n");
2182 }
2183
Tanya Lattner081fbd12004-07-30 23:36:10 +00002184 //If its in the value saved, we need to create a temp instruction and use that instead
2185 if(valuesToSave.count(mOp.getVRegValue())) {
Tanya Lattner7beb51c2004-11-16 21:31:37 +00002186
2187 //Check if we already have a final PHI value for this
2188 if(!finalPHIValue.count(mOp.getVRegValue())) {
2189 TmpInstruction *tmp = new TmpInstruction(mOp.getVRegValue());
Misha Brukmanb4402432005-04-21 23:30:14 +00002190
Tanya Lattner7beb51c2004-11-16 21:31:37 +00002191 //Get machine code for this instruction
2192 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
2193 tempMvec.addTemp((Value*) tmp);
Misha Brukmanb4402432005-04-21 23:30:14 +00002194
Tanya Lattner7beb51c2004-11-16 21:31:37 +00002195 //Update the operand in the cloned instruction
2196 instClone->getOperand(i).setValueReg(tmp);
Misha Brukmanb4402432005-04-21 23:30:14 +00002197
Tanya Lattner7beb51c2004-11-16 21:31:37 +00002198 //save this as our final phi
2199 finalPHIValue[mOp.getVRegValue()] = tmp;
2200 newValLocation[tmp] = machineBB;
2201 }
2202 else {
2203 //Use the previous final phi value
Misha Brukmanb4402432005-04-21 23:30:14 +00002204 instClone->getOperand(i).setValueReg(finalPHIValue[mOp.getVRegValue()]);
Tanya Lattner7beb51c2004-11-16 21:31:37 +00002205 }
Tanya Lattner081fbd12004-07-30 23:36:10 +00002206 }
2207 }
Tanya Lattner081fbd12004-07-30 23:36:10 +00002208 }
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002209 if(I->second != schedule.getMaxStage()) {
Tanya Lattner081fbd12004-07-30 23:36:10 +00002210 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isDef()) {
2211 if(valuesToSave.count(mOp.getVRegValue())) {
Misha Brukmanb4402432005-04-21 23:30:14 +00002212
Tanya Lattner081fbd12004-07-30 23:36:10 +00002213 TmpInstruction *tmp = new TmpInstruction(mOp.getVRegValue());
Misha Brukmanb4402432005-04-21 23:30:14 +00002214
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002215 //Get machine code for this instruction
Tanya Lattner444be612004-11-02 21:04:56 +00002216 MachineCodeForInstruction & tempVec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002217 tempVec.addTemp((Value*) tmp);
2218
Tanya Lattner081fbd12004-07-30 23:36:10 +00002219 //Create new machine instr and put in MBB
Tanya Lattner13417b52005-03-23 01:47:20 +00002220 MachineInstr *saveValue;
2221 if(mOp.getVRegValue()->getType() == Type::FloatTy)
2222 saveValue = BuildMI(machineBB, V9::FMOVS, 3).addReg(mOp.getVRegValue()).addRegDef(tmp);
2223 else if(mOp.getVRegValue()->getType() == Type::DoubleTy)
2224 saveValue = BuildMI(machineBB, V9::FMOVD, 3).addReg(mOp.getVRegValue()).addRegDef(tmp);
Misha Brukmanb4402432005-04-21 23:30:14 +00002225 else
Tanya Lattner13417b52005-03-23 01:47:20 +00002226 saveValue = BuildMI(machineBB, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
Misha Brukmanb4402432005-04-21 23:30:14 +00002227
2228
Tanya Lattner081fbd12004-07-30 23:36:10 +00002229 //Save for future cleanup
2230 kernelValue[mOp.getVRegValue()] = tmp;
2231 newValLocation[tmp] = machineBB;
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002232 kernelPHIs[mOp.getVRegValue()][schedule.getMaxStage()-1] = tmp;
Tanya Lattner081fbd12004-07-30 23:36:10 +00002233 }
2234 }
2235 }
2236 }
Misha Brukmanb4402432005-04-21 23:30:14 +00002237
Tanya Lattner081fbd12004-07-30 23:36:10 +00002238 }
2239
Tanya Lattnerc0d9dcd2004-12-03 05:25:22 +00002240 //Add branches
2241 for(std::vector<MachineInstr*>::iterator I = branches.begin(), E = branches.end(); I != E; ++I) {
2242 machineBB->push_back(*I);
2243 BuildMI(machineBB, V9::NOP, 0);
2244 }
2245
2246
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002247 DEBUG(std::cerr << "KERNEL before PHIs\n");
2248 DEBUG(machineBB->print(std::cerr));
2249
2250
2251 //Loop over each value we need to generate phis for
Misha Brukmanb4402432005-04-21 23:30:14 +00002252 for(std::map<Value*, std::map<int, Value*> >::iterator V = newValues.begin(),
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002253 E = newValues.end(); V != E; ++V) {
2254
Tanya Lattner081fbd12004-07-30 23:36:10 +00002255
2256 DEBUG(std::cerr << "Writing phi for" << *(V->first));
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002257 DEBUG(std::cerr << "\nMap of Value* for this phi\n");
Misha Brukmanb4402432005-04-21 23:30:14 +00002258 DEBUG(for(std::map<int, Value*>::iterator I = V->second.begin(),
2259 IE = V->second.end(); I != IE; ++I) {
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002260 std::cerr << "Stage: " << I->first;
2261 std::cerr << " Value: " << *(I->second) << "\n";
2262 });
Tanya Lattner081fbd12004-07-30 23:36:10 +00002263
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002264 //If we only have one current iteration live, its safe to set lastPhi = to kernel value
2265 if(V->second.size() == 1) {
2266 assert(kernelValue[V->first] != 0 && "Kernel value* must exist to create phi");
Misha Brukmanb4402432005-04-21 23:30:14 +00002267 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 +00002268 DEBUG(std::cerr << "Resulting PHI (one live): " << *saveValue << "\n");
2269 kernelPHIs[V->first][V->second.begin()->first] = kernelValue[V->first];
2270 DEBUG(std::cerr << "Put kernel phi in at stage: " << schedule.getMaxStage()-1 << " (map stage = " << V->second.begin()->first << ")\n");
2271 }
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002272 else {
2273
2274 //Keep track of last phi created.
2275 Instruction *lastPhi = 0;
Misha Brukmanb4402432005-04-21 23:30:14 +00002276
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002277 unsigned count = 1;
2278 //Loop over the the map backwards to generate phis
Misha Brukmanb4402432005-04-21 23:30:14 +00002279 for(std::map<int, Value*>::reverse_iterator I = V->second.rbegin(), IE = V->second.rend();
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002280 I != IE; ++I) {
2281
2282 if(count < (V->second).size()) {
2283 if(lastPhi == 0) {
2284 lastPhi = new TmpInstruction(I->second);
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002285
2286 //Get machine code for this instruction
Tanya Lattner444be612004-11-02 21:04:56 +00002287 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002288 tempMvec.addTemp((Value*) lastPhi);
2289
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002290 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(), V9::PHI, 3).addReg(kernelValue[V->first]).addReg(I->second).addRegDef(lastPhi);
2291 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
2292 newValLocation[lastPhi] = machineBB;
2293 }
2294 else {
2295 Instruction *tmp = new TmpInstruction(I->second);
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002296
2297 //Get machine code for this instruction
Tanya Lattner444be612004-11-02 21:04:56 +00002298 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002299 tempMvec.addTemp((Value*) tmp);
Misha Brukmanb4402432005-04-21 23:30:14 +00002300
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002301
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002302 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(), V9::PHI, 3).addReg(lastPhi).addReg(I->second).addRegDef(tmp);
2303 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
2304 lastPhi = tmp;
2305 kernelPHIs[V->first][I->first] = lastPhi;
2306 newValLocation[lastPhi] = machineBB;
2307 }
2308 }
2309 //Final phi value
2310 else {
2311 //The resulting value must be the Value* we created earlier
2312 assert(lastPhi != 0 && "Last phi is NULL!\n");
2313 MachineInstr *saveValue = BuildMI(*machineBB, machineBB->begin(), V9::PHI, 3).addReg(lastPhi).addReg(I->second).addRegDef(finalPHIValue[V->first]);
2314 DEBUG(std::cerr << "Resulting PHI: " << *saveValue << "\n");
2315 kernelPHIs[V->first][I->first] = finalPHIValue[V->first];
2316 }
2317
2318 ++count;
2319 }
2320
2321 }
Misha Brukmanb4402432005-04-21 23:30:14 +00002322 }
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002323
2324 DEBUG(std::cerr << "KERNEL after PHIs\n");
2325 DEBUG(machineBB->print(std::cerr));
Tanya Lattner081fbd12004-07-30 23:36:10 +00002326}
2327
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002328
Tanya Lattner081fbd12004-07-30 23:36:10 +00002329void ModuloSchedulingPass::removePHIs(const MachineBasicBlock *origBB, std::vector<MachineBasicBlock *> &prologues, std::vector<MachineBasicBlock *> &epilogues, MachineBasicBlock *kernelBB, std::map<Value*, MachineBasicBlock*> &newValLocation) {
2330
2331 //Worklist to delete things
2332 std::vector<std::pair<MachineBasicBlock*, MachineBasicBlock::iterator> > worklist;
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002333
2334 //Worklist of TmpInstructions that need to be added to a MCFI
2335 std::vector<Instruction*> addToMCFI;
Misha Brukmanb4402432005-04-21 23:30:14 +00002336
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002337 //Worklist to add OR instructions to end of kernel so not to invalidate the iterator
2338 //std::vector<std::pair<Instruction*, Value*> > newORs;
2339
Tanya Lattner081fbd12004-07-30 23:36:10 +00002340 const TargetInstrInfo *TMI = target.getInstrInfo();
2341
2342 //Start with the kernel and for each phi insert a copy for the phi def and for each arg
2343 for(MachineBasicBlock::iterator I = kernelBB->begin(), E = kernelBB->end(); I != E; ++I) {
Misha Brukmanb4402432005-04-21 23:30:14 +00002344
Tanya Lattner444be612004-11-02 21:04:56 +00002345 DEBUG(std::cerr << "Looking at Instr: " << *I << "\n");
Tanya Lattner081fbd12004-07-30 23:36:10 +00002346 //Get op code and check if its a phi
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002347 if(I->getOpcode() == V9::PHI) {
Misha Brukmanb4402432005-04-21 23:30:14 +00002348
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002349 DEBUG(std::cerr << "Replacing PHI: " << *I << "\n");
2350 Instruction *tmp = 0;
Tanya Lattner081fbd12004-07-30 23:36:10 +00002351
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002352 for(unsigned i = 0; i < I->getNumOperands(); ++i) {
2353 //Get Operand
2354 const MachineOperand &mOp = I->getOperand(i);
2355 assert(mOp.getType() == MachineOperand::MO_VirtualRegister && "Should be a Value*\n");
2356
2357 if(!tmp) {
2358 tmp = new TmpInstruction(mOp.getVRegValue());
2359 addToMCFI.push_back(tmp);
2360 }
Tanya Lattner081fbd12004-07-30 23:36:10 +00002361
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002362 //Now for all our arguments we read, OR to the new TmpInstruction that we created
2363 if(mOp.isUse()) {
2364 DEBUG(std::cerr << "Use: " << mOp << "\n");
2365 //Place a copy at the end of its BB but before the branches
2366 assert(newValLocation.count(mOp.getVRegValue()) && "We must know where this value is located\n");
2367 //Reverse iterate to find the branches, we can safely assume no instructions have been
2368 //put in the nop positions
2369 for(MachineBasicBlock::iterator inst = --(newValLocation[mOp.getVRegValue()])->end(), endBB = (newValLocation[mOp.getVRegValue()])->begin(); inst != endBB; --inst) {
2370 MachineOpCode opc = inst->getOpcode();
2371 if(TMI->isBranch(opc) || TMI->isNop(opc))
2372 continue;
2373 else {
Tanya Lattner13417b52005-03-23 01:47:20 +00002374 if(mOp.getVRegValue()->getType() == Type::FloatTy)
2375 BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::FMOVS, 3).addReg(mOp.getVRegValue()).addRegDef(tmp);
2376 else if(mOp.getVRegValue()->getType() == Type::DoubleTy)
2377 BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::FMOVD, 3).addReg(mOp.getVRegValue()).addRegDef(tmp);
Misha Brukmanb4402432005-04-21 23:30:14 +00002378 else
Tanya Lattner13417b52005-03-23 01:47:20 +00002379 BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
Misha Brukmanb4402432005-04-21 23:30:14 +00002380
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002381 break;
2382 }
Misha Brukmanb4402432005-04-21 23:30:14 +00002383
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002384 }
Tanya Lattner081fbd12004-07-30 23:36:10 +00002385
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002386 }
2387 else {
2388 //Remove the phi and replace it with an OR
2389 DEBUG(std::cerr << "Def: " << mOp << "\n");
2390 //newORs.push_back(std::make_pair(tmp, mOp.getVRegValue()));
Tanya Lattner13417b52005-03-23 01:47:20 +00002391 if(tmp->getType() == Type::FloatTy)
2392 BuildMI(*kernelBB, I, V9::FMOVS, 3).addReg(tmp).addRegDef(mOp.getVRegValue());
2393 else if(tmp->getType() == Type::DoubleTy)
2394 BuildMI(*kernelBB, I, V9::FMOVD, 3).addReg(tmp).addRegDef(mOp.getVRegValue());
Misha Brukmanb4402432005-04-21 23:30:14 +00002395 else
Tanya Lattner13417b52005-03-23 01:47:20 +00002396 BuildMI(*kernelBB, I, V9::ORr, 3).addReg(tmp).addImm(0).addRegDef(mOp.getVRegValue());
Misha Brukmanb4402432005-04-21 23:30:14 +00002397
2398
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002399 worklist.push_back(std::make_pair(kernelBB, I));
2400 }
2401
2402 }
Misha Brukmanb4402432005-04-21 23:30:14 +00002403
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002404 }
2405
Misha Brukmanb4402432005-04-21 23:30:14 +00002406
Tanya Lattner081fbd12004-07-30 23:36:10 +00002407 }
2408
Tanya Lattner444be612004-11-02 21:04:56 +00002409 //Add TmpInstructions to some MCFI
2410 if(addToMCFI.size() > 0) {
2411 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
2412 for(unsigned x = 0; x < addToMCFI.size(); ++x) {
2413 tempMvec.addTemp(addToMCFI[x]);
2414 }
2415 addToMCFI.clear();
2416 }
2417
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002418
Tanya Lattner081fbd12004-07-30 23:36:10 +00002419 //Remove phis from epilogue
2420 for(std::vector<MachineBasicBlock*>::iterator MB = epilogues.begin(), ME = epilogues.end(); MB != ME; ++MB) {
2421 for(MachineBasicBlock::iterator I = (*MB)->begin(), E = (*MB)->end(); I != E; ++I) {
Misha Brukmanb4402432005-04-21 23:30:14 +00002422
Tanya Lattner444be612004-11-02 21:04:56 +00002423 DEBUG(std::cerr << "Looking at Instr: " << *I << "\n");
Tanya Lattner081fbd12004-07-30 23:36:10 +00002424 //Get op code and check if its a phi
Brian Gaeke75935252004-08-18 20:04:24 +00002425 if(I->getOpcode() == V9::PHI) {
Tanya Lattner081fbd12004-07-30 23:36:10 +00002426 Instruction *tmp = 0;
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002427
Tanya Lattner081fbd12004-07-30 23:36:10 +00002428 for(unsigned i = 0; i < I->getNumOperands(); ++i) {
2429 //Get Operand
2430 const MachineOperand &mOp = I->getOperand(i);
2431 assert(mOp.getType() == MachineOperand::MO_VirtualRegister && "Should be a Value*\n");
Misha Brukmanb4402432005-04-21 23:30:14 +00002432
Tanya Lattner081fbd12004-07-30 23:36:10 +00002433 if(!tmp) {
2434 tmp = new TmpInstruction(mOp.getVRegValue());
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002435 addToMCFI.push_back(tmp);
Tanya Lattner081fbd12004-07-30 23:36:10 +00002436 }
Misha Brukmanb4402432005-04-21 23:30:14 +00002437
Tanya Lattner081fbd12004-07-30 23:36:10 +00002438 //Now for all our arguments we read, OR to the new TmpInstruction that we created
2439 if(mOp.isUse()) {
2440 DEBUG(std::cerr << "Use: " << mOp << "\n");
2441 //Place a copy at the end of its BB but before the branches
2442 assert(newValLocation.count(mOp.getVRegValue()) && "We must know where this value is located\n");
2443 //Reverse iterate to find the branches, we can safely assume no instructions have been
2444 //put in the nop positions
2445 for(MachineBasicBlock::iterator inst = --(newValLocation[mOp.getVRegValue()])->end(), endBB = (newValLocation[mOp.getVRegValue()])->begin(); inst != endBB; --inst) {
2446 MachineOpCode opc = inst->getOpcode();
2447 if(TMI->isBranch(opc) || TMI->isNop(opc))
2448 continue;
2449 else {
Tanya Lattner13417b52005-03-23 01:47:20 +00002450 if(mOp.getVRegValue()->getType() == Type::FloatTy)
2451 BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::FMOVS, 3).addReg(mOp.getVRegValue()).addRegDef(tmp);
2452 else if(mOp.getVRegValue()->getType() == Type::DoubleTy)
2453 BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::FMOVD, 3).addReg(mOp.getVRegValue()).addRegDef(tmp);
Misha Brukmanb4402432005-04-21 23:30:14 +00002454 else
Tanya Lattner13417b52005-03-23 01:47:20 +00002455 BuildMI(*(newValLocation[mOp.getVRegValue()]), ++inst, V9::ORr, 3).addReg(mOp.getVRegValue()).addImm(0).addRegDef(tmp);
2456
2457
Tanya Lattner081fbd12004-07-30 23:36:10 +00002458 break;
2459 }
Misha Brukmanb4402432005-04-21 23:30:14 +00002460
Tanya Lattner081fbd12004-07-30 23:36:10 +00002461 }
Misha Brukmanb4402432005-04-21 23:30:14 +00002462
Tanya Lattner081fbd12004-07-30 23:36:10 +00002463 }
2464 else {
2465 //Remove the phi and replace it with an OR
2466 DEBUG(std::cerr << "Def: " << mOp << "\n");
Tanya Lattner13417b52005-03-23 01:47:20 +00002467 if(tmp->getType() == Type::FloatTy)
2468 BuildMI(**MB, I, V9::FMOVS, 3).addReg(tmp).addRegDef(mOp.getVRegValue());
2469 else if(tmp->getType() == Type::DoubleTy)
2470 BuildMI(**MB, I, V9::FMOVD, 3).addReg(tmp).addRegDef(mOp.getVRegValue());
Misha Brukmanb4402432005-04-21 23:30:14 +00002471 else
Tanya Lattner13417b52005-03-23 01:47:20 +00002472 BuildMI(**MB, I, V9::ORr, 3).addReg(tmp).addImm(0).addRegDef(mOp.getVRegValue());
2473
Tanya Lattner081fbd12004-07-30 23:36:10 +00002474 worklist.push_back(std::make_pair(*MB,I));
2475 }
Misha Brukmanb4402432005-04-21 23:30:14 +00002476
Tanya Lattner081fbd12004-07-30 23:36:10 +00002477 }
2478 }
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002479
Misha Brukmanb4402432005-04-21 23:30:14 +00002480
Tanya Lattner081fbd12004-07-30 23:36:10 +00002481 }
2482 }
2483
Tanya Lattner444be612004-11-02 21:04:56 +00002484
2485 if(addToMCFI.size() > 0) {
2486 MachineCodeForInstruction & tempMvec = MachineCodeForInstruction::get(defaultInst);
2487 for(unsigned x = 0; x < addToMCFI.size(); ++x) {
2488 tempMvec.addTemp(addToMCFI[x]);
2489 }
2490 addToMCFI.clear();
2491 }
2492
Tanya Lattner081fbd12004-07-30 23:36:10 +00002493 //Delete the phis
2494 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 +00002495
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002496 DEBUG(std::cerr << "Deleting PHI " << *I->second << "\n");
Tanya Lattner081fbd12004-07-30 23:36:10 +00002497 I->first->erase(I->second);
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
2502 assert((addToMCFI.size() == 0) && "We should have added all TmpInstructions to some MachineCodeForInstruction");
Tanya Lattner50cbb9a2004-05-28 20:14:12 +00002503}
2504
2505
Tanya Lattner081fbd12004-07-30 23:36:10 +00002506void ModuloSchedulingPass::reconstructLoop(MachineBasicBlock *BB) {
Tanya Lattnera066df62004-05-26 06:27:18 +00002507
Tanya Lattner56807c62005-02-10 17:02:58 +00002508 TIME_REGION(X, "reconstructLoop");
2509
2510
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002511 DEBUG(std::cerr << "Reconstructing Loop\n");
2512
Tanya Lattner081fbd12004-07-30 23:36:10 +00002513 //First find the value *'s that we need to "save"
Tanya Lattner13417b52005-03-23 01:47:20 +00002514 std::map<const Value*, std::pair<const MachineInstr*, int> > valuesToSave;
Tanya Lattnera066df62004-05-26 06:27:18 +00002515
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002516 //Keep track of instructions we have already seen and their stage because
2517 //we don't want to "save" values if they are used in the kernel immediately
2518 std::map<const MachineInstr*, int> lastInstrs;
2519
Tanya Lattner081fbd12004-07-30 23:36:10 +00002520 //Loop over kernel and only look at instructions from a stage > 0
2521 //Look at its operands and save values *'s that are read
Tanya Lattnera066df62004-05-26 06:27:18 +00002522 for(MSSchedule::kernel_iterator I = schedule.kernel_begin(), E = schedule.kernel_end(); I != E; ++I) {
Tanya Lattnera066df62004-05-26 06:27:18 +00002523
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002524 if(I->second !=0) {
Tanya Lattnera066df62004-05-26 06:27:18 +00002525 //For this instruction, get the Value*'s that it reads and put them into the set.
2526 //Assert if there is an operand of another type that we need to save
Tanya Lattner13417b52005-03-23 01:47:20 +00002527 const MachineInstr *inst = I->first;
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002528 lastInstrs[inst] = I->second;
2529
Tanya Lattnera066df62004-05-26 06:27:18 +00002530 for(unsigned i=0; i < inst->getNumOperands(); ++i) {
2531 //get machine operand
2532 const MachineOperand &mOp = inst->getOperand(i);
Tanya Lattner081fbd12004-07-30 23:36:10 +00002533
Tanya Lattnera066df62004-05-26 06:27:18 +00002534 if(mOp.getType() == MachineOperand::MO_VirtualRegister && mOp.isUse()) {
2535 //find the value in the map
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002536 if (const Value* srcI = mOp.getVRegValue()) {
2537
Tanya Lattner7beb51c2004-11-16 21:31:37 +00002538 if(isa<Constant>(srcI) || isa<Argument>(srcI) || isa<PHINode>(srcI))
Tanya Lattner444be612004-11-02 21:04:56 +00002539 continue;
2540
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002541 //Before we declare this Value* one that we should save
2542 //make sure its def is not of the same stage as this instruction
2543 //because it will be consumed before its used
2544 Instruction *defInst = (Instruction*) srcI;
Misha Brukmanb4402432005-04-21 23:30:14 +00002545
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002546 //Should we save this value?
2547 bool save = true;
2548
Tanya Lattner7beb51c2004-11-16 21:31:37 +00002549 //Continue if not in the def map, loop invariant code does not need to be saved
2550 if(!defMap.count(srcI))
2551 continue;
2552
Tanya Lattner444be612004-11-02 21:04:56 +00002553 MachineInstr *defInstr = defMap[srcI];
Misha Brukmanb4402432005-04-21 23:30:14 +00002554
Tanya Lattner7beb51c2004-11-16 21:31:37 +00002555
Tanya Lattner444be612004-11-02 21:04:56 +00002556 if(lastInstrs.count(defInstr)) {
Tanya Lattner7beb51c2004-11-16 21:31:37 +00002557 if(lastInstrs[defInstr] == I->second) {
Tanya Lattner444be612004-11-02 21:04:56 +00002558 save = false;
Tanya Lattner7beb51c2004-11-16 21:31:37 +00002559
2560 }
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002561 }
Misha Brukmanb4402432005-04-21 23:30:14 +00002562
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002563 if(save)
2564 valuesToSave[srcI] = std::make_pair(I->first, i);
Misha Brukmanb4402432005-04-21 23:30:14 +00002565 }
Tanya Lattnera066df62004-05-26 06:27:18 +00002566 }
2567
2568 if(mOp.getType() != MachineOperand::MO_VirtualRegister && mOp.isUse()) {
2569 assert("Our assumption is wrong. We have another type of register that needs to be saved\n");
2570 }
2571 }
Tanya Lattnera066df62004-05-26 06:27:18 +00002572 }
2573 }
2574
Tanya Lattner081fbd12004-07-30 23:36:10 +00002575 //The new loop will consist of one or more prologues, the kernel, and one or more epilogues.
2576
2577 //Map to keep track of old to new values
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002578 std::map<Value*, std::map<int, Value*> > newValues;
Misha Brukmanb4402432005-04-21 23:30:14 +00002579
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002580 //Map to keep track of old to new values in kernel
2581 std::map<Value*, std::map<int, Value*> > kernelPHIs;
2582
Tanya Lattner081fbd12004-07-30 23:36:10 +00002583 //Another map to keep track of what machine basic blocks these new value*s are in since
2584 //they have no llvm instruction equivalent
2585 std::map<Value*, MachineBasicBlock*> newValLocation;
2586
2587 std::vector<MachineBasicBlock*> prologues;
2588 std::vector<BasicBlock*> llvm_prologues;
2589
2590
2591 //Write prologue
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00002592 if(schedule.getMaxStage() != 0)
2593 writePrologues(prologues, BB, llvm_prologues, valuesToSave, newValues, newValLocation);
Misha Brukmanb4402432005-04-21 23:30:14 +00002594
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002595 //Print out epilogues and prologue
Misha Brukmanb4402432005-04-21 23:30:14 +00002596 DEBUG(for(std::vector<MachineBasicBlock*>::iterator I = prologues.begin(), E = prologues.end();
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002597 I != E; ++I) {
2598 std::cerr << "PROLOGUE\n";
2599 (*I)->print(std::cerr);
2600 });
Tanya Lattner081fbd12004-07-30 23:36:10 +00002601
2602 BasicBlock *llvmKernelBB = new BasicBlock("Kernel", (Function*) (BB->getBasicBlock()->getParent()));
2603 MachineBasicBlock *machineKernelBB = new MachineBasicBlock(llvmKernelBB);
Tanya Lattner081fbd12004-07-30 23:36:10 +00002604 (((MachineBasicBlock*)BB)->getParent())->getBasicBlockList().push_back(machineKernelBB);
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002605 writeKernel(llvmKernelBB, machineKernelBB, valuesToSave, newValues, newValLocation, kernelPHIs);
Misha Brukmanb4402432005-04-21 23:30:14 +00002606
2607
Tanya Lattner081fbd12004-07-30 23:36:10 +00002608 std::vector<MachineBasicBlock*> epilogues;
2609 std::vector<BasicBlock*> llvm_epilogues;
2610
2611 //Write epilogues
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00002612 if(schedule.getMaxStage() != 0)
2613 writeEpilogues(epilogues, BB, llvm_epilogues, valuesToSave, newValues, newValLocation, kernelPHIs);
Tanya Lattner081fbd12004-07-30 23:36:10 +00002614
2615
Tanya Lattnerd8cc4fa2004-11-29 04:39:47 +00002616 //Fix our branches
2617 fixBranches(prologues, llvm_prologues, machineKernelBB, llvmKernelBB, epilogues, llvm_epilogues, BB);
2618
2619 //Remove phis
2620 removePHIs(BB, prologues, epilogues, machineKernelBB, newValLocation);
Misha Brukmanb4402432005-04-21 23:30:14 +00002621
Tanya Lattnerd8cc4fa2004-11-29 04:39:47 +00002622 //Print out epilogues and prologue
Misha Brukmanb4402432005-04-21 23:30:14 +00002623 DEBUG(for(std::vector<MachineBasicBlock*>::iterator I = prologues.begin(), E = prologues.end();
Tanya Lattnerd8cc4fa2004-11-29 04:39:47 +00002624 I != E; ++I) {
2625 std::cerr << "PROLOGUE\n";
2626 (*I)->print(std::cerr);
2627 });
Misha Brukmanb4402432005-04-21 23:30:14 +00002628
Tanya Lattnerd8cc4fa2004-11-29 04:39:47 +00002629 DEBUG(std::cerr << "KERNEL\n");
2630 DEBUG(machineKernelBB->print(std::cerr));
2631
Misha Brukmanb4402432005-04-21 23:30:14 +00002632 DEBUG(for(std::vector<MachineBasicBlock*>::iterator I = epilogues.begin(), E = epilogues.end();
Tanya Lattnerd8cc4fa2004-11-29 04:39:47 +00002633 I != E; ++I) {
2634 std::cerr << "EPILOGUE\n";
2635 (*I)->print(std::cerr);
2636 });
2637
2638
2639 DEBUG(std::cerr << "New Machine Function" << "\n");
2640 DEBUG(std::cerr << BB->getParent() << "\n");
2641
2642
2643}
2644
2645void 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) {
2646
Tanya Lattner081fbd12004-07-30 23:36:10 +00002647 const TargetInstrInfo *TMI = target.getInstrInfo();
2648
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00002649 if(schedule.getMaxStage() != 0) {
2650 //Fix prologue branches
2651 for(unsigned I = 0; I < prologues.size(); ++I) {
Misha Brukmanb4402432005-04-21 23:30:14 +00002652
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00002653 //Find terminator since getFirstTerminator does not work!
2654 for(MachineBasicBlock::reverse_iterator mInst = prologues[I]->rbegin(), mInstEnd = prologues[I]->rend(); mInst != mInstEnd; ++mInst) {
2655 MachineOpCode OC = mInst->getOpcode();
2656 //If its a branch update its branchto
2657 if(TMI->isBranch(OC)) {
2658 for(unsigned opNum = 0; opNum < mInst->getNumOperands(); ++opNum) {
2659 MachineOperand &mOp = mInst->getOperand(opNum);
2660 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2661 //Check if we are branching to the kernel, if not branch to epilogue
Misha Brukmanb4402432005-04-21 23:30:14 +00002662 if(mOp.getVRegValue() == BB->getBasicBlock()) {
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00002663 if(I == prologues.size()-1)
2664 mOp.setValueReg(llvmKernelBB);
2665 else
2666 mOp.setValueReg(llvm_prologues[I+1]);
2667 }
2668 else {
2669 mOp.setValueReg(llvm_epilogues[(llvm_epilogues.size()-1-I)]);
2670 }
Tanya Lattnerd8cc4fa2004-11-29 04:39:47 +00002671 }
2672 }
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00002673
2674 DEBUG(std::cerr << "New Prologue Branch: " << *mInst << "\n");
Tanya Lattnerd8cc4fa2004-11-29 04:39:47 +00002675 }
Tanya Lattner081fbd12004-07-30 23:36:10 +00002676 }
Tanya Lattner081fbd12004-07-30 23:36:10 +00002677
Tanya Lattner081fbd12004-07-30 23:36:10 +00002678
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00002679 //Update llvm basic block with our new branch instr
2680 DEBUG(std::cerr << BB->getBasicBlock()->getTerminator() << "\n");
2681 const BranchInst *branchVal = dyn_cast<BranchInst>(BB->getBasicBlock()->getTerminator());
Misha Brukmanb4402432005-04-21 23:30:14 +00002682
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00002683 if(I == prologues.size()-1) {
2684 TerminatorInst *newBranch = new BranchInst(llvmKernelBB,
Misha Brukmanb4402432005-04-21 23:30:14 +00002685 llvm_epilogues[(llvm_epilogues.size()-1-I)],
2686 branchVal->getCondition(),
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00002687 llvm_prologues[I]);
2688 }
2689 else
2690 TerminatorInst *newBranch = new BranchInst(llvm_prologues[I+1],
Misha Brukmanb4402432005-04-21 23:30:14 +00002691 llvm_epilogues[(llvm_epilogues.size()-1-I)],
2692 branchVal->getCondition(),
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00002693 llvm_prologues[I]);
Tanya Lattner081fbd12004-07-30 23:36:10 +00002694
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00002695 }
Tanya Lattner081fbd12004-07-30 23:36:10 +00002696 }
2697
Tanya Lattnerd8cc4fa2004-11-29 04:39:47 +00002698 Value *origBranchExit = 0;
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002699
Tanya Lattnerd8cc4fa2004-11-29 04:39:47 +00002700 //Fix up kernel machine branches
Tanya Lattner081fbd12004-07-30 23:36:10 +00002701 for(MachineBasicBlock::reverse_iterator mInst = machineKernelBB->rbegin(), mInstEnd = machineKernelBB->rend(); mInst != mInstEnd; ++mInst) {
2702 MachineOpCode OC = mInst->getOpcode();
2703 if(TMI->isBranch(OC)) {
Tanya Lattnerd8cc4fa2004-11-29 04:39:47 +00002704 for(unsigned opNum = 0; opNum < mInst->getNumOperands(); ++opNum) {
2705 MachineOperand &mOp = mInst->getOperand(opNum);
2706
2707 if(mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2708 if(mOp.getVRegValue() == BB->getBasicBlock())
2709 mOp.setValueReg(llvmKernelBB);
2710 else
2711 if(llvm_epilogues.size() > 0) {
2712 assert(origBranchExit == 0 && "There should only be one branch out of the loop");
Misha Brukmanb4402432005-04-21 23:30:14 +00002713
Tanya Lattnerd8cc4fa2004-11-29 04:39:47 +00002714 origBranchExit = mOp.getVRegValue();
2715 mOp.setValueReg(llvm_epilogues[0]);
2716 }
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00002717 else
2718 origBranchExit = mOp.getVRegValue();
Tanya Lattnerd8cc4fa2004-11-29 04:39:47 +00002719 }
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002720 }
Tanya Lattner081fbd12004-07-30 23:36:10 +00002721 }
2722 }
Misha Brukmanb4402432005-04-21 23:30:14 +00002723
Tanya Lattner081fbd12004-07-30 23:36:10 +00002724 //Update kernelLLVM branches
2725 const BranchInst *branchVal = dyn_cast<BranchInst>(BB->getBasicBlock()->getTerminator());
Misha Brukmanb4402432005-04-21 23:30:14 +00002726
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00002727 assert(origBranchExit != 0 && "We must have the original bb the kernel exits to!");
Misha Brukmanb4402432005-04-21 23:30:14 +00002728
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00002729 if(epilogues.size() > 0) {
2730 TerminatorInst *newBranch = new BranchInst(llvmKernelBB,
Misha Brukmanb4402432005-04-21 23:30:14 +00002731 llvm_epilogues[0],
2732 branchVal->getCondition(),
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00002733 llvmKernelBB);
2734 }
2735 else {
2736 BasicBlock *origBBExit = dyn_cast<BasicBlock>(origBranchExit);
2737 assert(origBBExit !=0 && "Original exit basic block must be set");
2738 TerminatorInst *newBranch = new BranchInst(llvmKernelBB,
2739 origBBExit,
Misha Brukmanb4402432005-04-21 23:30:14 +00002740 branchVal->getCondition(),
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00002741 llvmKernelBB);
2742 }
Tanya Lattner081fbd12004-07-30 23:36:10 +00002743
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00002744 if(schedule.getMaxStage() != 0) {
Tanya Lattner081fbd12004-07-30 23:36:10 +00002745 //Lastly add unconditional branches for the epilogues
2746 for(unsigned I = 0; I < epilogues.size(); ++I) {
Misha Brukmanb4402432005-04-21 23:30:14 +00002747
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002748 //Now since we don't have fall throughs, add a unconditional branch to the next prologue
Tanya Lattner081fbd12004-07-30 23:36:10 +00002749 if(I != epilogues.size()-1) {
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002750 BuildMI(epilogues[I], V9::BA, 1).addPCDisp(llvm_epilogues[I+1]);
Tanya Lattner081fbd12004-07-30 23:36:10 +00002751 //Add unconditional branch to end of epilogue
Misha Brukmanb4402432005-04-21 23:30:14 +00002752 TerminatorInst *newBranch = new BranchInst(llvm_epilogues[I+1],
Tanya Lattner081fbd12004-07-30 23:36:10 +00002753 llvm_epilogues[I]);
2754
Tanya Lattnera066df62004-05-26 06:27:18 +00002755 }
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002756 else {
Tanya Lattnerd8cc4fa2004-11-29 04:39:47 +00002757 BuildMI(epilogues[I], V9::BA, 1).addPCDisp(origBranchExit);
Misha Brukmanb4402432005-04-21 23:30:14 +00002758
2759
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002760 //Update last epilogue exit branch
2761 BranchInst *branchVal = (BranchInst*) dyn_cast<BranchInst>(BB->getBasicBlock()->getTerminator());
2762 //Find where we are supposed to branch to
2763 BasicBlock *nextBlock = 0;
2764 for(unsigned j=0; j <branchVal->getNumSuccessors(); ++j) {
2765 if(branchVal->getSuccessor(j) != BB->getBasicBlock())
2766 nextBlock = branchVal->getSuccessor(j);
2767 }
Misha Brukmanb4402432005-04-21 23:30:14 +00002768
Tanya Lattnerd38a7602004-10-14 06:04:28 +00002769 assert((nextBlock != 0) && "Next block should not be null!");
2770 TerminatorInst *newBranch = new BranchInst(nextBlock, llvm_epilogues[I]);
2771 }
2772 //Add one more nop!
2773 BuildMI(epilogues[I], V9::NOP, 0);
Misha Brukmanb4402432005-04-21 23:30:14 +00002774
Tanya Lattner081fbd12004-07-30 23:36:10 +00002775 }
Tanya Lattner8d64e9a2005-04-05 16:36:44 +00002776 }
Tanya Lattnera066df62004-05-26 06:27:18 +00002777
Tanya Lattner081fbd12004-07-30 23:36:10 +00002778 //FIX UP Machine BB entry!!
2779 //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 +00002780
Tanya Lattnera066df62004-05-26 06:27:18 +00002781
Tanya Lattner081fbd12004-07-30 23:36:10 +00002782 //Find all llvm basic blocks that branch to the loop entry and change to our first prologue.
2783 const BasicBlock *llvmBB = BB->getBasicBlock();
2784
Tanya Lattnerddebd1e2004-10-30 00:39:07 +00002785 std::vector<const BasicBlock*>Preds (pred_begin(llvmBB), pred_end(llvmBB));
2786
2787 //for(pred_const_iterator P = pred_begin(llvmBB), PE = pred_end(llvmBB); P != PE; ++PE) {
Misha Brukmanb4402432005-04-21 23:30:14 +00002788 for(std::vector<const BasicBlock*>::iterator P = Preds.begin(), PE = Preds.end(); P != PE; ++P) {
Tanya Lattner081fbd12004-07-30 23:36:10 +00002789 if(*P == llvmBB)
2790 continue;
2791 else {
2792 DEBUG(std::cerr << "Found our entry BB\n");
2793 //Get the Terminator instruction for this basic block and print it out
2794 DEBUG(std::cerr << *((*P)->getTerminator()) << "\n");
2795 //Update the terminator
2796 TerminatorInst *term = ((BasicBlock*)*P)->getTerminator();
2797 for(unsigned i=0; i < term->getNumSuccessors(); ++i) {
2798 if(term->getSuccessor(i) == llvmBB) {
2799 DEBUG(std::cerr << "Replacing successor bb\n");
2800 if(llvm_prologues.size() > 0) {
2801 term->setSuccessor(i, llvm_prologues[0]);
2802 //Also update its corresponding machine instruction
2803 MachineCodeForInstruction & tempMvec =
2804 MachineCodeForInstruction::get(term);
2805 for (unsigned j = 0; j < tempMvec.size(); j++) {
2806 MachineInstr *temp = tempMvec[j];
2807 MachineOpCode opc = temp->getOpcode();
2808 if(TMI->isBranch(opc)) {
2809 DEBUG(std::cerr << *temp << "\n");
2810 //Update branch
2811 for(unsigned opNum = 0; opNum < temp->getNumOperands(); ++opNum) {
2812 MachineOperand &mOp = temp->getOperand(opNum);
2813 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2814 mOp.setValueReg(llvm_prologues[0]);
2815 }
2816 }
2817 }
Misha Brukmanb4402432005-04-21 23:30:14 +00002818 }
Tanya Lattner081fbd12004-07-30 23:36:10 +00002819 }
2820 else {
2821 term->setSuccessor(i, llvmKernelBB);
2822 //Also update its corresponding machine instruction
2823 MachineCodeForInstruction & tempMvec =
2824 MachineCodeForInstruction::get(term);
2825 for (unsigned j = 0; j < tempMvec.size(); j++) {
2826 MachineInstr *temp = tempMvec[j];
2827 MachineOpCode opc = temp->getOpcode();
2828 if(TMI->isBranch(opc)) {
2829 DEBUG(std::cerr << *temp << "\n");
2830 //Update branch
2831 for(unsigned opNum = 0; opNum < temp->getNumOperands(); ++opNum) {
2832 MachineOperand &mOp = temp->getOperand(opNum);
2833 if (mOp.getType() == MachineOperand::MO_PCRelativeDisp) {
2834 mOp.setValueReg(llvmKernelBB);
2835 }
2836 }
2837 }
2838 }
2839 }
2840 }
2841 }
2842 break;
2843 }
2844 }
Misha Brukmanb4402432005-04-21 23:30:14 +00002845
Tanya Lattner081fbd12004-07-30 23:36:10 +00002846
Tanya Lattnerdbac0cb2004-10-10 22:44:35 +00002847 //BB->getParent()->getBasicBlockList().erase(BB);
Tanya Lattnera066df62004-05-26 06:27:18 +00002848
2849}
2850