* Update file header comment
[oota-llvm.git] / lib / Transforms / Utils / PromoteMemoryToRegister.cpp
1 //===- PromoteMemoryToRegister.cpp - Convert allocas to registers ---------===//
2 //
3 // This file promote memory references to be register references.  It promotes
4 // alloca instructions which only have loads and stores as uses.  An alloca is
5 // transformed by using dominator frontiers to place PHI nodes, then traversing
6 // the function in depth-first order to rewrite loads and stores as appropriate.
7 // This is just the standard SSA construction algorithm.
8 //
9 //===----------------------------------------------------------------------===//
10
11 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
12 #include "llvm/Analysis/Dominators.h"
13 #include "llvm/iMemory.h"
14 #include "llvm/iPHINode.h"
15 #include "llvm/Function.h"
16 #include "llvm/Constant.h"
17 #include "llvm/Support/CFG.h"
18 #include "Support/StringExtras.h"
19
20 /// isAllocaPromotable - Return true if this alloca is legal for promotion.
21 /// This is true if there are only loads and stores to the alloca...
22 ///
23 bool isAllocaPromotable(const AllocaInst *AI, const TargetData &TD) {
24   // FIXME: If the memory unit is of pointer or integer type, we can permit
25   // assignments to subsections of the memory unit.
26
27   // Only allow direct loads and stores...
28   for (Value::use_const_iterator UI = AI->use_begin(), UE = AI->use_end();
29        UI != UE; ++UI)     // Loop over all of the uses of the alloca
30     if (!isa<LoadInst>(*UI))
31       if (const StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
32         if (SI->getOperand(0) == AI)
33           return false;   // Don't allow a store of the AI, only INTO the AI.
34       } else {
35         return false;   // Not a load or store?
36       }
37   
38   return true;
39 }
40
41
42 namespace {
43   struct PromoteMem2Reg {
44     // Allocas - The alloca instructions being promoted
45     const std::vector<AllocaInst*> &Allocas;
46     DominanceFrontier &DF;
47     const TargetData &TD;
48
49     // AllocaLookup - Reverse mapping of Allocas
50     std::map<AllocaInst*, unsigned>  AllocaLookup;
51
52     // VersionNumbers - Current version counters for each alloca
53     std::vector<unsigned> VersionNumbers;
54     
55     // NewPhiNodes - The PhiNodes we're adding.
56     std::map<BasicBlock*, std::vector<PHINode*> > NewPhiNodes;
57
58     // Visited - The set of basic blocks the renamer has already visited.
59     std::set<BasicBlock*> Visited;
60
61   public:
62     PromoteMem2Reg(const std::vector<AllocaInst*> &A, DominanceFrontier &df,
63                    const TargetData &td) : Allocas(A), DF(df), TD(td) {}
64
65     void run();
66
67   private:
68     void RenamePass(BasicBlock *BB, BasicBlock *Pred,
69                     std::vector<Value*> &IncVals);
70     bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx);
71   };
72 }  // end of anonymous namespace
73
74 void PromoteMem2Reg::run() {
75   Function &F = *DF.getRoot()->getParent();
76
77   VersionNumbers.resize(Allocas.size());
78
79   for (unsigned i = 0; i != Allocas.size(); ++i) {
80     AllocaInst *AI = Allocas[i];
81
82     assert(isAllocaPromotable(AI, TD) &&
83            "Cannot promote non-promotable alloca!");
84     assert(Allocas[i]->getParent()->getParent() == &F &&
85            "All allocas should be in the same function, which is same as DF!");
86
87     // Calculate the set of write-locations for each alloca.  This is analogous
88     // to counting the number of 'redefinitions' of each variable.
89     std::vector<BasicBlock*> DefiningBlocks;
90     for (Value::use_iterator U =AI->use_begin(), E = AI->use_end(); U != E; ++U)
91       if (StoreInst *SI = dyn_cast<StoreInst>(cast<Instruction>(*U)))
92         // jot down the basic-block it came from
93         DefiningBlocks.push_back(SI->getParent());
94
95     AllocaLookup[Allocas[i]] = i;
96     
97     // PhiNodeBlocks - A list of blocks that phi nodes have been inserted for
98     // this alloca.
99     std::vector<BasicBlock*> PhiNodeBlocks;
100
101     // Compute the locations where PhiNodes need to be inserted.  Look at the
102     // dominance frontier of EACH basic-block we have a write in.
103     //
104     while (!DefiningBlocks.empty()) {
105       BasicBlock *BB = DefiningBlocks.back();
106       DefiningBlocks.pop_back();
107
108       // Look up the DF for this write, add it to PhiNodes
109       DominanceFrontier::const_iterator it = DF.find(BB);
110       if (it != DF.end()) {
111         const DominanceFrontier::DomSetType &S = it->second;
112         for (DominanceFrontier::DomSetType::iterator P = S.begin(),PE = S.end();
113              P != PE; ++P)
114           if (QueuePhiNode(*P, i))
115             DefiningBlocks.push_back(*P);
116       }
117     }
118   }
119
120   // Set the incoming values for the basic block to be null values for all of
121   // the alloca's.  We do this in case there is a load of a value that has not
122   // been stored yet.  In this case, it will get this null value.
123   //
124   std::vector<Value *> Values(Allocas.size());
125   for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
126     Values[i] = Constant::getNullValue(Allocas[i]->getAllocatedType());
127
128   // Walks all basic blocks in the function performing the SSA rename algorithm
129   // and inserting the phi nodes we marked as necessary
130   //
131   RenamePass(F.begin(), 0, Values);
132
133   // The renamer uses the Visited set to avoid infinite loops.  Clear it now.
134   Visited.clear();
135
136   // Remove the allocas themselves from the function...
137   for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
138     Instruction *A = Allocas[i];
139
140     // If there are any uses of the alloca instructions left, they must be in
141     // sections of dead code that were not processed on the dominance frontier.
142     // Just delete the users now.
143     //
144     if (!A->use_empty())
145       A->replaceAllUsesWith(Constant::getNullValue(A->getType()));
146     A->getParent()->getInstList().erase(A);
147   }
148
149   // At this point, the renamer has added entries to PHI nodes for all reachable
150   // code.  Unfortunately, there may be blocks which are not reachable, which
151   // the renamer hasn't traversed.  If this is the case, the PHI nodes may not
152   // have incoming values for all predecessors.  Loop over all PHI nodes we have
153   // created, inserting null constants if they are missing any incoming values.
154   //
155   for (std::map<BasicBlock*, std::vector<PHINode *> >::iterator I = 
156          NewPhiNodes.begin(), E = NewPhiNodes.end(); I != E; ++I) {
157
158     std::vector<BasicBlock*> Preds(pred_begin(I->first), pred_end(I->first));
159     std::vector<PHINode*> &PNs = I->second;
160     assert(!PNs.empty() && "Empty PHI node list??");
161
162     // Only do work here if there the PHI nodes are missing incoming values.  We
163     // know that all PHI nodes that were inserted in a block will have the same
164     // number of incoming values, so we can just check any PHI node.
165     PHINode *FirstPHI = PNs[0];
166     if (Preds.size() != FirstPHI->getNumIncomingValues()) {
167       // Ok, now we know that all of the PHI nodes are missing entries for some
168       // basic blocks.  Start by sorting the incoming predecessors for efficient
169       // access.
170       std::sort(Preds.begin(), Preds.end());
171
172       // Now we loop through all BB's which have entries in FirstPHI and remove
173       // them from the Preds list.
174       for (unsigned i = 0, e = FirstPHI->getNumIncomingValues(); i != e; ++i) {
175         // Do a log(n) search of teh Preds list for the entry we want.
176         std::vector<BasicBlock*>::iterator EntIt =
177           std::lower_bound(Preds.begin(), Preds.end(),
178                            FirstPHI->getIncomingBlock(i));
179         assert(EntIt != Preds.end() && *EntIt == FirstPHI->getIncomingBlock(i)&&
180                "PHI node has entry for a block which is not a predecessor!");
181
182         // Remove the entry
183         Preds.erase(EntIt);
184       }
185
186       // At this point, the blocks left in the preds list must have dummy
187       // entries inserted into every PHI nodes for the block.
188       for (unsigned i = 0, e = PNs.size(); i != e; ++i) {
189         PHINode *PN = PNs[i];
190         Value *NullVal = Constant::getNullValue(PN->getType());
191         for (unsigned pred = 0, e = Preds.size(); pred != e; ++pred)
192           PN->addIncoming(NullVal, Preds[pred]);
193       }
194     }
195   }
196 }
197
198
199 // QueuePhiNode - queues a phi-node to be added to a basic-block for a specific
200 // Alloca returns true if there wasn't already a phi-node for that variable
201 //
202 bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo) {
203   // Look up the basic-block in question
204   std::vector<PHINode*> &BBPNs = NewPhiNodes[BB];
205   if (BBPNs.empty()) BBPNs.resize(Allocas.size());
206
207   // If the BB already has a phi node added for the i'th alloca then we're done!
208   if (BBPNs[AllocaNo]) return false;
209
210   // Create a PhiNode using the dereferenced type... and add the phi-node to the
211   // BasicBlock.
212   BBPNs[AllocaNo] = new PHINode(Allocas[AllocaNo]->getAllocatedType(),
213                                 Allocas[AllocaNo]->getName() + "." +
214                                          utostr(VersionNumbers[AllocaNo]++),
215                                 BB->begin());
216   return true;
217 }
218
219 void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
220                                 std::vector<Value*> &IncomingVals) {
221
222   // If this BB needs a PHI node, update the PHI node for each variable we need
223   // PHI nodes for.
224   std::map<BasicBlock*, std::vector<PHINode *> >::iterator
225     BBPNI = NewPhiNodes.find(BB);
226   if (BBPNI != NewPhiNodes.end()) {
227     std::vector<PHINode *> &BBPNs = BBPNI->second;
228     for (unsigned k = 0; k != BBPNs.size(); ++k)
229       if (PHINode *PN = BBPNs[k]) {
230         // Add this incoming value to the PHI node.
231         PN->addIncoming(IncomingVals[k], Pred);
232
233         // The currently active variable for this block is now the PHI.
234         IncomingVals[k] = PN;
235       }
236   }
237
238   // don't revisit nodes
239   if (Visited.count(BB)) return;
240   
241   // mark as visited
242   Visited.insert(BB);
243
244   for (BasicBlock::iterator II = BB->begin(); !isa<TerminatorInst>(II); ) {
245     Instruction *I = II++; // get the instruction, increment iterator
246
247     if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
248       if (AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand())) {
249         std::map<AllocaInst*, unsigned>::iterator AI = AllocaLookup.find(Src);
250         if (AI != AllocaLookup.end()) {
251           Value *V = IncomingVals[AI->second];
252
253           // walk the use list of this load and replace all uses with r
254           LI->replaceAllUsesWith(V);
255           BB->getInstList().erase(LI);
256         }
257       }
258     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
259       // Delete this instruction and mark the name as the current holder of the
260       // value
261       if (AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand())) {
262         std::map<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest);
263         if (ai != AllocaLookup.end()) {
264           // what value were we writing?
265           IncomingVals[ai->second] = SI->getOperand(0);
266           BB->getInstList().erase(SI);
267         }
268       }
269     }
270   }
271
272   // Recurse to our successors
273   TerminatorInst *TI = BB->getTerminator();
274   for (unsigned i = 0; i != TI->getNumSuccessors(); i++) {
275     std::vector<Value*> OutgoingVals(IncomingVals);
276     RenamePass(TI->getSuccessor(i), BB, OutgoingVals);
277   }
278 }
279
280 /// PromoteMemToReg - Promote the specified list of alloca instructions into
281 /// scalar registers, inserting PHI nodes as appropriate.  This function makes
282 /// use of DominanceFrontier information.  This function does not modify the CFG
283 /// of the function at all.  All allocas must be from the same function.
284 ///
285 void PromoteMemToReg(const std::vector<AllocaInst*> &Allocas,
286                      DominanceFrontier &DF, const TargetData &TD) {
287   // If there is nothing to do, bail out...
288   if (Allocas.empty()) return;
289   PromoteMem2Reg(Allocas, DF, TD).run();
290 }