* Rename MethodPass class to FunctionPass
[oota-llvm.git] / lib / Transforms / Utils / PromoteMemoryToRegister.cpp
1 //===- PromoteMemoryToRegister.cpp - Convert memory refs to regs ----------===//
2 //
3 // This pass is used to promote memory references to be register references.  A
4 // simple example of the transformation performed by this pass is:
5 //
6 //        FROM CODE                           TO CODE
7 //   %X = alloca int, uint 1                 ret int 42
8 //   store int 42, int *%X
9 //   %Y = load int* %X
10 //   ret int %Y
11 //
12 // To do this transformation, a simple analysis is done to ensure it is safe.
13 // Currently this just loops over all alloca instructions, looking for
14 // instructions that are only used in simple load and stores.
15 //
16 // After this, the code is transformed by...something magical :)
17 //
18 //===----------------------------------------------------------------------===//
19
20 #include "llvm/Transforms/Scalar/PromoteMemoryToRegister.h"
21 #include "llvm/Analysis/Dominators.h"
22 #include "llvm/iMemory.h"
23 #include "llvm/iPHINode.h"
24 #include "llvm/iTerminators.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Function.h"
27 #include "llvm/BasicBlock.h"
28 #include "llvm/ConstantVals.h"
29
30 using namespace std;
31
32
33 using cfg::DominanceFrontier;
34
35 namespace {
36
37 //instance of the promoter -- to keep all the local function data.
38 // gets re-created for each function processed
39 class PromoteInstance
40 {
41         protected:
42         vector<AllocaInst*>                     Allocas;   // the alloca instruction..
43         map<Instruction *, int>                 AllocaLookup; //reverse mapping of above
44
45         vector<vector<BasicBlock *> >           WriteSets; // index corresponds to Allocas
46         vector<vector<BasicBlock *> >           PhiNodes;  // index corresponds to Allocas
47         vector<vector<Value *> >                CurrentValue; //the current value stack
48
49         //list of instructions to remove at end of pass :)
50         vector<Instruction *> killlist;
51
52         set<BasicBlock *>                       visited;        //the basic blocks we've already visited
53         map<BasicBlock *, vector<PHINode *> >   new_phinodes;   //the phinodes we're adding
54
55
56         void traverse(BasicBlock *f, BasicBlock * predecessor);
57         bool PromoteFunction(Function *F, DominanceFrontier &DF);
58         bool queuePhiNode(BasicBlock *bb, int alloca_index);
59         void findSafeAllocas(Function *M);
60         bool didchange;
61         public:
62         // I do this so that I can force the deconstruction of the local variables
63         PromoteInstance(Function *F, DominanceFrontier &DF)
64         {
65                 didchange=PromoteFunction(F, DF);
66         }
67         //This returns whether the pass changes anything
68         operator bool () { return didchange; }
69 };
70
71 }  // end of anonymous namespace
72
73 // findSafeAllocas - Find allocas that are safe to promote
74 //
75 void PromoteInstance::findSafeAllocas(Function *F)  
76 {
77   BasicBlock *BB = F->getEntryNode();  // Get the entry node for the function
78
79   // Look at all instructions in the entry node
80   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
81     if (AllocaInst *AI = dyn_cast<AllocaInst>(*I))       // Is it an alloca?
82       if (!AI->isArrayAllocation()) {
83         bool isSafe = true;
84         for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
85              UI != UE; ++UI) {   // Loop over all of the uses of the alloca
86
87           // Only allow nonindexed memory access instructions...
88           if (MemAccessInst *MAI = dyn_cast<MemAccessInst>(*UI)) {
89             if (MAI->hasIndices()) {  // indexed?
90               // Allow the access if there is only one index and the index is zero.
91               if (*MAI->idx_begin() != ConstantUInt::get(Type::UIntTy, 0) ||
92                   MAI->idx_begin()+1 != MAI->idx_end()) {
93                 isSafe = false; break;
94               }
95             }
96           } else {
97             isSafe = false; break;   // Not a load or store?
98           }
99         }
100         if (isSafe)              // If all checks pass, add alloca to safe list
101           {
102             AllocaLookup[AI]=Allocas.size();
103             Allocas.push_back(AI);
104           }
105       }
106 }
107
108
109
110 bool PromoteInstance::PromoteFunction(Function *F, DominanceFrontier & DF) {
111         // Calculate the set of safe allocas
112         findSafeAllocas(F);
113
114         // Add each alloca to the killlist
115         // note: killlist is destroyed MOST recently added to least recently.
116         killlist.assign(Allocas.begin(), Allocas.end());
117
118         // Calculate the set of write-locations for each alloca.
119         // this is analogous to counting the number of 'redefinitions' of each variable.
120         for (unsigned i = 0; i<Allocas.size(); ++i)
121         {
122                 AllocaInst * AI = Allocas[i];
123                 WriteSets.push_back(std::vector<BasicBlock *>()); //add a new set
124                 for (Value::use_iterator U = AI->use_begin();U!=AI->use_end();++U)
125                 {
126                         if (MemAccessInst *MAI = dyn_cast<StoreInst>(*U)) {
127                                 WriteSets[i].push_back(MAI->getParent()); // jot down the basic-block it came from
128                         }
129                 }
130         }
131
132         // Compute the locations where PhiNodes need to be inserted
133         // look at the dominance frontier of EACH basic-block we have a write in
134         PhiNodes.resize(Allocas.size());
135         for (unsigned i = 0; i<Allocas.size(); ++i)
136         {
137                 for (unsigned j = 0; j<WriteSets[i].size(); j++)
138                 {
139                         //look up the DF for this write, add it to PhiNodes
140                         DominanceFrontier::const_iterator it = DF.find(WriteSets[i][j]);
141                         DominanceFrontier::DomSetType     s = (*it).second;
142                         for (DominanceFrontier::DomSetType::iterator p = s.begin();p!=s.end(); ++p)
143                         {
144                                 if (queuePhiNode((BasicBlock *)*p, i))
145                                 PhiNodes[i].push_back((BasicBlock *)*p);
146                         }
147                 }
148                 // perform iterative step
149                 for (unsigned k = 0; k<PhiNodes[i].size(); k++)
150                 {
151                         DominanceFrontier::const_iterator it = DF.find(PhiNodes[i][k]);
152                         DominanceFrontier::DomSetType     s = it->second;
153                         for (DominanceFrontier::DomSetType::iterator p = s.begin(); p!=s.end(); ++p)
154                         {
155                                 if (queuePhiNode((BasicBlock *)*p,i))
156                                 PhiNodes[i].push_back((BasicBlock*)*p);
157                         }
158                 }
159         }
160
161         // Walks all basic blocks in the function
162         // performing the SSA rename algorithm
163         // and inserting the phi nodes we marked as necessary
164         BasicBlock * f = F->front(); //get root basic-block
165
166         CurrentValue.push_back(vector<Value *>(Allocas.size()));
167
168         traverse(f, NULL);  // there is no predecessor of the root node
169
170
171         // ** REMOVE EVERYTHING IN THE KILL-LIST **
172         // we need to kill 'uses' before root values
173         // so we should probably run through in reverse
174         for (vector<Instruction *>::reverse_iterator i = killlist.rbegin(); i!=killlist.rend(); ++i)
175         {
176                 Instruction * r = *i;
177                 BasicBlock * o = r->getParent();
178                 //now go find..
179
180                 BasicBlock::InstListType & l = o->getInstList();
181                 o->getInstList().remove(r);
182                 delete r;
183         }
184
185         return !Allocas.empty();
186 }
187
188
189
190 void PromoteInstance::traverse(BasicBlock *f, BasicBlock * predecessor)
191 {
192         vector<Value *> * tos = &CurrentValue.back(); //look at top-
193
194         //if this is a BB needing a phi node, lookup/create the phinode for
195         // each variable we need phinodes for.
196         map<BasicBlock *, vector<PHINode *> >::iterator nd = new_phinodes.find(f);
197         if (nd!=new_phinodes.end())
198         {
199                 for (unsigned k = 0; k!=nd->second.size(); ++k)
200                 if (nd->second[k])
201                 {
202                         //at this point we can assume that the array has phi nodes.. let's
203                         // add the incoming data
204                         if ((*tos)[k])
205                         nd->second[k]->addIncoming((*tos)[k],predecessor);
206                         //also note that the active variable IS designated by the phi node
207                         (*tos)[k] = nd->second[k];
208                 }
209         }
210
211         //don't revisit nodes
212         if (visited.find(f)!=visited.end())
213         return;
214         //mark as visited
215         visited.insert(f);
216
217         BasicBlock::iterator i = f->begin();
218         //keep track of the value of each variable we're watching.. how?
219         while(i!=f->end())
220         {
221                 Instruction * inst = *i; //get the instruction
222                 //is this a write/read?
223                 if (LoadInst * LI = dyn_cast<LoadInst>(inst))
224                 {
225                         // This is a bit weird...
226                         Value * ptr = LI->getPointerOperand(); //of type value
227                         if (AllocaInst * srcinstr = dyn_cast<AllocaInst>(ptr))
228                         {
229                                 map<Instruction *, int>::iterator ai = AllocaLookup.find(srcinstr);
230                                 if (ai!=AllocaLookup.end())
231                                 {
232                                         if (Value *r = (*tos)[ai->second])
233                                         {
234                                                 //walk the use list of this load and replace
235                                                 // all uses with r
236                                                 LI->replaceAllUsesWith(r);
237                                                 //now delete the instruction.. somehow..
238                                                 killlist.push_back((Instruction *)LI);
239                                         }
240                                 }
241                         }
242                 }
243                 else if (StoreInst * SI = dyn_cast<StoreInst>(inst))
244                 {
245                         // delete this instruction and mark the name as the
246                         // current holder of the value
247                         Value * ptr =  SI->getPointerOperand(); //of type value
248                         if (Instruction * srcinstr = dyn_cast<Instruction>(ptr))
249                         {
250                                 map<Instruction *, int>::iterator ai = AllocaLookup.find(srcinstr);
251                                 if (ai!=AllocaLookup.end())
252                                 {
253                                         //what value were we writing?
254                                         Value * writeval = SI->getOperand(0);
255                                         //write down...
256                                         (*tos)[ai->second] = writeval;
257                                         //now delete it.. somehow?
258                                         killlist.push_back((Instruction *)SI);
259                                 }
260                         }
261
262                 }
263                 else if (TerminatorInst * TI = dyn_cast<TerminatorInst>(inst))
264                 {
265                         // Recurse across our sucessors
266                         for (unsigned i = 0; i!=TI->getNumSuccessors(); i++)
267                         {
268                                 CurrentValue.push_back(CurrentValue.back());
269                                 traverse(TI->getSuccessor(i),f); //this node IS the predecessor
270                                 CurrentValue.pop_back();
271                         }
272                 }
273                 i++;
274         }
275 }
276
277 // queues a phi-node to be added to a basic-block for a specific Alloca
278 // returns true  if there wasn't already a phi-node for that variable
279
280
281 bool PromoteInstance::queuePhiNode(BasicBlock *bb, int i /*the alloca*/)
282 {
283         map<BasicBlock *, vector<PHINode *> >::iterator nd;
284         //look up the basic-block in question
285         nd = new_phinodes.find(bb);
286         //if the basic-block has no phi-nodes added, or at least none
287         //for the i'th alloca. then add.
288         if (nd==new_phinodes.end() || nd->second[i]==NULL)
289         {
290                 //we're not added any phi nodes to this basicblock yet
291                 // create the phi-node array.
292                 if (nd==new_phinodes.end())
293                 {
294                         new_phinodes[bb] = vector<PHINode *>(Allocas.size());
295                         nd = new_phinodes.find(bb);
296                 }
297
298                 //find the type the alloca returns
299                 const PointerType * pt = Allocas[i]->getType();
300                 //create a phi-node using the DEREFERENCED type
301                 PHINode * ph = new PHINode(pt->getElementType(), Allocas[i]->getName()+".mem2reg");
302                 nd->second[i] = ph;
303                 //add the phi-node to the basic-block
304                 bb->getInstList().push_front(ph);
305                 return true;
306         }
307         return false;
308 }
309
310
311 namespace {
312   struct PromotePass : public FunctionPass {
313
314     // runOnFunction - To run this pass, first we calculate the alloca
315     // instructions that are safe for promotion, then we promote each one.
316     //
317     virtual bool runOnFunction(Function *F) {
318       return (bool)PromoteInstance(F, getAnalysis<DominanceFrontier>());
319     }
320     
321
322     // getAnalysisUsage - We need dominance frontiers
323     //
324     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
325       AU.addRequired(DominanceFrontier::ID);
326     }
327   };
328 }
329   
330
331 // createPromoteMemoryToRegister - Provide an entry point to create this pass.
332 //
333 Pass *createPromoteMemoryToRegister() {
334         return new PromotePass();
335 }
336
337