1efa8c2393f7c0f9edb67b8e8e9043c46a10c502
[oota-llvm.git] / lib / Transforms / Utils / PromoteMemoryToRegister.cpp
1 //===- PromoteMemoryToRegister.cpp - Convert memory refs to regs ----------===//
2 //
3 // This file is used to promote memory references to be register references.  A
4 // simple example of the transformation performed by this function 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 // The code is transformed by looping over all of the alloca instruction,
13 // calculating dominator frontiers, then inserting phi-nodes following the usual
14 // SSA construction algorithm.  This code does not modify the CFG of the
15 // function.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
20 #include "llvm/Analysis/Dominators.h"
21 #include "llvm/iMemory.h"
22 #include "llvm/iPHINode.h"
23 #include "llvm/iTerminators.h"
24 #include "llvm/Function.h"
25 #include "llvm/Constant.h"
26 #include "llvm/Type.h"
27
28 /// isAllocaPromotable - Return true if this alloca is legal for promotion.
29 /// This is true if there are only loads and stores to the alloca...
30 ///
31 bool isAllocaPromotable(const AllocaInst *AI) {
32   // Only allow direct loads and stores...
33   for (Value::use_const_iterator UI = AI->use_begin(), UE = AI->use_end();
34        UI != UE; ++UI)     // Loop over all of the uses of the alloca
35     if (!isa<LoadInst>(*UI))
36       if (const StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
37         if (SI->getOperand(0) == AI)
38           return false;   // Don't allow a store of the AI, only INTO the AI.
39       } else {
40         return false;   // Not a load or store?
41       }
42   
43   return true;
44 }
45
46
47 namespace {
48   struct PromoteMem2Reg {
49     const std::vector<AllocaInst*>   &Allocas;      // the alloca instructions..
50     DominanceFrontier &DF;
51
52     std::map<Instruction*, unsigned>  AllocaLookup; // reverse mapping of above
53     
54     std::vector<std::vector<BasicBlock*> > PhiNodes;// Idx corresponds 2 Allocas
55     
56     // List of instructions to remove at end of pass
57     std::vector<Instruction *>        KillList;
58     
59     std::map<BasicBlock*,
60              std::vector<PHINode*> >  NewPhiNodes; // the PhiNodes we're adding
61
62   public:
63     PromoteMem2Reg(const std::vector<AllocaInst*> &A, DominanceFrontier &df)
64       :Allocas(A), DF(df) {}
65
66     void run();
67
68   private:
69     void RenamePass(BasicBlock *BB, BasicBlock *Pred,
70                     std::vector<Value*> &IncVals,
71                     std::set<BasicBlock*> &Visited);
72     bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx);
73   };
74 }  // end of anonymous namespace
75
76
77 void PromoteMem2Reg::run() {
78   // If there is nothing to do, bail out...
79   if (Allocas.empty()) return;
80
81   Function &F = *DF.getRoot()->getParent();
82
83   for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
84     assert(isAllocaPromotable(Allocas[i]) &&
85            "Cannot promote non-promotable alloca!");
86     assert(Allocas[i]->getParent()->getParent() == &F &&
87            "All allocas should be in the same function, which is same as DF!");
88     AllocaLookup[Allocas[i]] = i;
89   }
90
91
92   // Add each alloca to the KillList.  Note: KillList is destroyed MOST recently
93   // added to least recently.
94   KillList.assign(Allocas.begin(), Allocas.end());
95
96   // Calculate the set of write-locations for each alloca.  This is analogous to
97   // counting the number of 'redefinitions' of each variable.
98   std::vector<std::vector<BasicBlock*> > WriteSets;// Idx corresponds to Allocas
99   WriteSets.resize(Allocas.size());
100   for (unsigned i = 0; i != Allocas.size(); ++i) {
101     AllocaInst *AI = Allocas[i];
102     for (Value::use_iterator U =AI->use_begin(), E = AI->use_end(); U != E; ++U)
103       if (StoreInst *SI = dyn_cast<StoreInst>(*U))
104         // jot down the basic-block it came from
105         WriteSets[i].push_back(SI->getParent());
106   }
107
108   // Compute the locations where PhiNodes need to be inserted.  Look at the
109   // dominance frontier of EACH basic-block we have a write in
110   //
111   PhiNodes.resize(Allocas.size());
112   for (unsigned i = 0; i != Allocas.size(); ++i) {
113     for (unsigned j = 0; j != WriteSets[i].size(); j++) {
114       // Look up the DF for this write, add it to PhiNodes
115       DominanceFrontier::const_iterator it = DF.find(WriteSets[i][j]);
116       DominanceFrontier::DomSetType     S = it->second;
117       for (DominanceFrontier::DomSetType::iterator P = S.begin(), PE = S.end();
118            P != PE; ++P)
119         QueuePhiNode(*P, i);
120     }
121     
122     // Perform iterative step
123     for (unsigned k = 0; k != PhiNodes[i].size(); k++) {
124       DominanceFrontier::const_iterator it = DF.find(PhiNodes[i][k]);
125       DominanceFrontier::DomSetType     S = it->second;
126       for (DominanceFrontier::DomSetType::iterator P = S.begin(), PE = S.end();
127            P != PE; ++P)
128         QueuePhiNode(*P, i);
129     }
130   }
131
132   // Set the incoming values for the basic block to be null values for all of
133   // the alloca's.  We do this in case there is a load of a value that has not
134   // been stored yet.  In this case, it will get this null value.
135   //
136   std::vector<Value *> Values(Allocas.size());
137   for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
138     Values[i] = Constant::getNullValue(Allocas[i]->getAllocatedType());
139
140   // Walks all basic blocks in the function performing the SSA rename algorithm
141   // and inserting the phi nodes we marked as necessary
142   //
143   std::set<BasicBlock*> Visited;      // The basic blocks we've already visited
144   RenamePass(F.begin(), 0, Values, Visited);
145
146   // Remove all instructions marked by being placed in the KillList...
147   //
148   while (!KillList.empty()) {
149     Instruction *I = KillList.back();
150     KillList.pop_back();
151
152     I->getParent()->getInstList().erase(I);
153   }
154 }
155
156
157 // QueuePhiNode - queues a phi-node to be added to a basic-block for a specific
158 // Alloca returns true if there wasn't already a phi-node for that variable
159 //
160 bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo) {
161   // Look up the basic-block in question
162   std::vector<PHINode*> &BBPNs = NewPhiNodes[BB];
163   if (BBPNs.empty()) BBPNs.resize(Allocas.size());
164
165   // If the BB already has a phi node added for the i'th alloca then we're done!
166   if (BBPNs[AllocaNo]) return false;
167
168   // Create a PhiNode using the dereferenced type... and add the phi-node to the
169   // BasicBlock
170   PHINode *PN = new PHINode(Allocas[AllocaNo]->getAllocatedType(),
171                             Allocas[AllocaNo]->getName()+".mem2reg",
172                             BB->begin());
173   BBPNs[AllocaNo] = PN;
174   PhiNodes[AllocaNo].push_back(BB);
175   return true;
176 }
177
178 void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
179                              std::vector<Value*> &IncomingVals,
180                              std::set<BasicBlock*> &Visited) {
181   // If this is a BB needing a phi node, lookup/create the phinode for each
182   // variable we need phinodes for.
183   std::vector<PHINode *> &BBPNs = NewPhiNodes[BB];
184   for (unsigned k = 0; k != BBPNs.size(); ++k)
185     if (PHINode *PN = BBPNs[k]) {
186       // at this point we can assume that the array has phi nodes.. let's add
187       // the incoming data
188       PN->addIncoming(IncomingVals[k], Pred);
189
190       // also note that the active variable IS designated by the phi node
191       IncomingVals[k] = PN;
192     }
193
194   // don't revisit nodes
195   if (Visited.count(BB)) return;
196   
197   // mark as visited
198   Visited.insert(BB);
199
200   // keep track of the value of each variable we're watching.. how?
201   for (BasicBlock::iterator II = BB->begin(); II != BB->end(); ++II) {
202     Instruction *I = II; // get the instruction
203
204     if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
205       if (AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand())) {
206         std::map<Instruction*, unsigned>::iterator AI = AllocaLookup.find(Src);
207         if (AI != AllocaLookup.end()) {
208           Value *V = IncomingVals[AI->second];
209
210           // walk the use list of this load and replace all uses with r
211           LI->replaceAllUsesWith(V);
212           KillList.push_back(LI); // Mark the load to be deleted
213         }
214       }
215     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
216       // Delete this instruction and mark the name as the current holder of the
217       // value
218       if (AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand())) {
219         std::map<Instruction *, unsigned>::iterator ai =AllocaLookup.find(Dest);
220         if (ai != AllocaLookup.end()) {
221           // what value were we writing?
222           IncomingVals[ai->second] = SI->getOperand(0);
223           KillList.push_back(SI);  // Mark the store to be deleted
224         }
225       }
226       
227     } else if (TerminatorInst *TI = dyn_cast<TerminatorInst>(I)) {
228       // Recurse across our successors
229       for (unsigned i = 0; i != TI->getNumSuccessors(); i++) {
230         std::vector<Value*> OutgoingVals(IncomingVals);
231         RenamePass(TI->getSuccessor(i), BB, OutgoingVals, Visited);
232       }
233     }
234   }
235 }
236
237 /// PromoteMemToReg - Promote the specified list of alloca instructions into
238 /// scalar registers, inserting PHI nodes as appropriate.  This function makes
239 /// use of DominanceFrontier information.  This function does not modify the CFG
240 /// of the function at all.  All allocas must be from the same function.
241 ///
242 void PromoteMemToReg(const std::vector<AllocaInst*> &Allocas,
243                      DominanceFrontier &DF) {
244   PromoteMem2Reg(Allocas, DF).run();
245 }