Finegrainify namespacification
[oota-llvm.git] / lib / Transforms / Utils / PromoteMemoryToRegister.cpp
1 //===- PromoteMemoryToRegister.cpp - Convert allocas to registers ---------===//
2 // 
3 //                     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.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file promote memory references to be register references.  It promotes
11 // alloca instructions which only have loads and stores as uses.  An alloca is
12 // transformed by using dominator frontiers to place PHI nodes, then traversing
13 // the function in depth-first order to rewrite loads and stores as appropriate.
14 // This is just the standard SSA construction algorithm to construct "pruned"
15 // SSA form.
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/Function.h"
24 #include "llvm/Constant.h"
25 #include "llvm/Support/CFG.h"
26 #include "Support/StringExtras.h"
27 using namespace llvm;
28
29 /// isAllocaPromotable - Return true if this alloca is legal for promotion.
30 /// This is true if there are only loads and stores to the alloca...
31 ///
32 bool llvm::isAllocaPromotable(const AllocaInst *AI, const TargetData &TD) {
33   // FIXME: If the memory unit is of pointer or integer type, we can permit
34   // assignments to subsections of the memory unit.
35
36   // Only allow direct loads and stores...
37   for (Value::use_const_iterator UI = AI->use_begin(), UE = AI->use_end();
38        UI != UE; ++UI)     // Loop over all of the uses of the alloca
39     if (!isa<LoadInst>(*UI))
40       if (const StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
41         if (SI->getOperand(0) == AI)
42           return false;   // Don't allow a store of the AI, only INTO the AI.
43       } else {
44         return false;   // Not a load or store?
45       }
46   
47   return true;
48 }
49
50 namespace {
51   struct PromoteMem2Reg {
52     // Allocas - The alloca instructions being promoted
53     std::vector<AllocaInst*> Allocas;
54     DominatorTree &DT;
55     DominanceFrontier &DF;
56     const TargetData &TD;
57
58     // AllocaLookup - Reverse mapping of Allocas
59     std::map<AllocaInst*, unsigned>  AllocaLookup;
60
61     // NewPhiNodes - The PhiNodes we're adding.
62     std::map<BasicBlock*, std::vector<PHINode*> > NewPhiNodes;
63
64     // Visited - The set of basic blocks the renamer has already visited.
65     std::set<BasicBlock*> Visited;
66
67   public:
68     PromoteMem2Reg(const std::vector<AllocaInst*> &A, DominatorTree &dt,
69                    DominanceFrontier &df, const TargetData &td)
70       : Allocas(A), DT(dt), DF(df), TD(td) {}
71
72     void run();
73
74   private:
75     void MarkDominatingPHILive(BasicBlock *BB, unsigned AllocaNum,
76                                std::set<PHINode*> &DeadPHINodes);
77     void PromoteLocallyUsedAlloca(AllocaInst *AI);
78
79     void RenamePass(BasicBlock *BB, BasicBlock *Pred,
80                     std::vector<Value*> &IncVals);
81     bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx, unsigned &Version,
82                       std::set<PHINode*> &InsertedPHINodes);
83   };
84 }  // end of anonymous namespace
85
86 void PromoteMem2Reg::run() {
87   Function &F = *DF.getRoot()->getParent();
88
89   for (unsigned AllocaNum = 0; AllocaNum != Allocas.size(); ++AllocaNum) {
90     AllocaInst *AI = Allocas[AllocaNum];
91
92     assert(isAllocaPromotable(AI, TD) &&
93            "Cannot promote non-promotable alloca!");
94     assert(AI->getParent()->getParent() == &F &&
95            "All allocas should be in the same function, which is same as DF!");
96
97     if (AI->use_empty()) {
98       // If there are no uses of the alloca, just delete it now.
99       AI->getParent()->getInstList().erase(AI);
100
101       // Remove the alloca from the Allocas list, since it has been processed
102       Allocas[AllocaNum] = Allocas.back();
103       Allocas.pop_back();
104       --AllocaNum;
105       continue;
106     }
107
108     // Calculate the set of read and write-locations for each alloca.  This is
109     // analogous to counting the number of 'uses' and 'definitions' of each
110     // variable.
111     std::vector<BasicBlock*> DefiningBlocks;
112     std::vector<BasicBlock*> UsingBlocks;
113
114     BasicBlock *OnlyBlock = 0;
115     bool OnlyUsedInOneBlock = true;
116
117     // As we scan the uses of the alloca instruction, keep track of stores, and
118     // decide whether all of the loads and stores to the alloca are within the
119     // same basic block.
120     for (Value::use_iterator U =AI->use_begin(), E = AI->use_end(); U != E;++U){
121       Instruction *User = cast<Instruction>(*U);
122       if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
123         // Remember the basic blocks which define new values for the alloca
124         DefiningBlocks.push_back(SI->getParent());
125       } else {
126         // Otherwise it must be a load instruction, keep track of variable reads
127         UsingBlocks.push_back(cast<LoadInst>(User)->getParent());
128       }
129
130       if (OnlyUsedInOneBlock) {
131         if (OnlyBlock == 0)
132           OnlyBlock = User->getParent();
133         else if (OnlyBlock != User->getParent())
134           OnlyUsedInOneBlock = false;
135       }
136     }
137
138     // If the alloca is only read and written in one basic block, just perform a
139     // linear sweep over the block to eliminate it.
140     if (OnlyUsedInOneBlock) {
141       PromoteLocallyUsedAlloca(AI);
142
143       // Remove the alloca from the Allocas list, since it has been processed
144       Allocas[AllocaNum] = Allocas.back();
145       Allocas.pop_back();
146       --AllocaNum;
147       continue;
148     }
149
150     // Compute the locations where PhiNodes need to be inserted.  Look at the
151     // dominance frontier of EACH basic-block we have a write in.
152     //
153     unsigned CurrentVersion = 0;
154     std::set<PHINode*> InsertedPHINodes;
155     while (!DefiningBlocks.empty()) {
156       BasicBlock *BB = DefiningBlocks.back();
157       DefiningBlocks.pop_back();
158
159       // Look up the DF for this write, add it to PhiNodes
160       DominanceFrontier::const_iterator it = DF.find(BB);
161       if (it != DF.end()) {
162         const DominanceFrontier::DomSetType &S = it->second;
163         for (DominanceFrontier::DomSetType::iterator P = S.begin(),PE = S.end();
164              P != PE; ++P)
165           if (QueuePhiNode(*P, AllocaNum, CurrentVersion, InsertedPHINodes))
166             DefiningBlocks.push_back(*P);
167       }
168     }
169
170     // Now that we have inserted PHI nodes along the Iterated Dominance Frontier
171     // of the writes to the variable, scan through the reads of the variable,
172     // marking PHI nodes which are actually necessary as alive (by removing them
173     // from the InsertedPHINodes set).  This is not perfect: there may PHI
174     // marked alive because of loads which are dominated by stores, but there
175     // will be no unmarked PHI nodes which are actually used.
176     //
177     for (unsigned i = 0, e = UsingBlocks.size(); i != e; ++i)
178       MarkDominatingPHILive(UsingBlocks[i], AllocaNum, InsertedPHINodes);
179     UsingBlocks.clear();
180
181     // If there are any PHI nodes which are now known to be dead, remove them!
182     for (std::set<PHINode*>::iterator I = InsertedPHINodes.begin(),
183            E = InsertedPHINodes.end(); I != E; ++I) {
184       PHINode *PN = *I;
185       std::vector<PHINode*> &BBPNs = NewPhiNodes[PN->getParent()];
186       BBPNs[AllocaNum] = 0;
187
188       // Check to see if we just removed the last inserted PHI node from this
189       // basic block.  If so, remove the entry for the basic block.
190       bool HasOtherPHIs = false;
191       for (unsigned i = 0, e = BBPNs.size(); i != e; ++i)
192         if (BBPNs[i]) {
193           HasOtherPHIs = true;
194           break;
195         }
196       if (!HasOtherPHIs)
197         NewPhiNodes.erase(PN->getParent());
198
199       PN->getParent()->getInstList().erase(PN);      
200     }
201
202     // Keep the reverse mapping of the 'Allocas' array. 
203     AllocaLookup[Allocas[AllocaNum]] = AllocaNum;
204   }
205   
206   if (Allocas.empty())
207     return; // All of the allocas must have been trivial!
208
209   // Set the incoming values for the basic block to be null values for all of
210   // the alloca's.  We do this in case there is a load of a value that has not
211   // been stored yet.  In this case, it will get this null value.
212   //
213   std::vector<Value *> Values(Allocas.size());
214   for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
215     Values[i] = Constant::getNullValue(Allocas[i]->getAllocatedType());
216
217   // Walks all basic blocks in the function performing the SSA rename algorithm
218   // and inserting the phi nodes we marked as necessary
219   //
220   RenamePass(F.begin(), 0, Values);
221
222   // The renamer uses the Visited set to avoid infinite loops.  Clear it now.
223   Visited.clear();
224
225   // Remove the allocas themselves from the function...
226   for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
227     Instruction *A = Allocas[i];
228
229     // If there are any uses of the alloca instructions left, they must be in
230     // sections of dead code that were not processed on the dominance frontier.
231     // Just delete the users now.
232     //
233     if (!A->use_empty())
234       A->replaceAllUsesWith(Constant::getNullValue(A->getType()));
235     A->getParent()->getInstList().erase(A);
236   }
237
238   // At this point, the renamer has added entries to PHI nodes for all reachable
239   // code.  Unfortunately, there may be blocks which are not reachable, which
240   // the renamer hasn't traversed.  If this is the case, the PHI nodes may not
241   // have incoming values for all predecessors.  Loop over all PHI nodes we have
242   // created, inserting null constants if they are missing any incoming values.
243   //
244   for (std::map<BasicBlock*, std::vector<PHINode *> >::iterator I = 
245          NewPhiNodes.begin(), E = NewPhiNodes.end(); I != E; ++I) {
246
247     std::vector<BasicBlock*> Preds(pred_begin(I->first), pred_end(I->first));
248     std::vector<PHINode*> &PNs = I->second;
249     assert(!PNs.empty() && "Empty PHI node list??");
250
251     // Only do work here if there the PHI nodes are missing incoming values.  We
252     // know that all PHI nodes that were inserted in a block will have the same
253     // number of incoming values, so we can just check any PHI node.
254     PHINode *FirstPHI;
255     for (unsigned i = 0; (FirstPHI = PNs[i]) == 0; ++i)
256       /*empty*/;
257
258     if (Preds.size() != FirstPHI->getNumIncomingValues()) {
259       // Ok, now we know that all of the PHI nodes are missing entries for some
260       // basic blocks.  Start by sorting the incoming predecessors for efficient
261       // access.
262       std::sort(Preds.begin(), Preds.end());
263
264       // Now we loop through all BB's which have entries in FirstPHI and remove
265       // them from the Preds list.
266       for (unsigned i = 0, e = FirstPHI->getNumIncomingValues(); i != e; ++i) {
267         // Do a log(n) search of the Preds list for the entry we want.
268         std::vector<BasicBlock*>::iterator EntIt =
269           std::lower_bound(Preds.begin(), Preds.end(),
270                            FirstPHI->getIncomingBlock(i));
271         assert(EntIt != Preds.end() && *EntIt == FirstPHI->getIncomingBlock(i)&&
272                "PHI node has entry for a block which is not a predecessor!");
273
274         // Remove the entry
275         Preds.erase(EntIt);
276       }
277
278       // At this point, the blocks left in the preds list must have dummy
279       // entries inserted into every PHI nodes for the block.
280       for (unsigned i = 0, e = PNs.size(); i != e; ++i)
281         if (PHINode *PN = PNs[i]) {
282           Value *NullVal = Constant::getNullValue(PN->getType());
283           for (unsigned pred = 0, e = Preds.size(); pred != e; ++pred)
284             PN->addIncoming(NullVal, Preds[pred]);
285         }
286     }
287   }
288 }
289
290 // MarkDominatingPHILive - Mem2Reg wants to construct "pruned" SSA form, not
291 // "minimal" SSA form.  To do this, it inserts all of the PHI nodes on the IDF
292 // as usual (inserting the PHI nodes in the DeadPHINodes set), then processes
293 // each read of the variable.  For each block that reads the variable, this
294 // function is called, which removes used PHI nodes from the DeadPHINodes set.
295 // After all of the reads have been processed, any PHI nodes left in the
296 // DeadPHINodes set are removed.
297 //
298 void PromoteMem2Reg::MarkDominatingPHILive(BasicBlock *BB, unsigned AllocaNum,
299                                            std::set<PHINode*> &DeadPHINodes) {
300   // Scan the immediate dominators of this block looking for a block which has a
301   // PHI node for Alloca num.  If we find it, mark the PHI node as being alive!
302   for (DominatorTree::Node *N = DT[BB]; N; N = N->getIDom()) {
303     BasicBlock *DomBB = N->getBlock();
304     std::map<BasicBlock*, std::vector<PHINode*> >::iterator
305       I = NewPhiNodes.find(DomBB);
306     if (I != NewPhiNodes.end() && I->second[AllocaNum]) {
307       // Ok, we found an inserted PHI node which dominates this value.
308       PHINode *DominatingPHI = I->second[AllocaNum];
309
310       // Find out if we previously thought it was dead.
311       std::set<PHINode*>::iterator DPNI = DeadPHINodes.find(DominatingPHI);
312       if (DPNI != DeadPHINodes.end()) {
313         // Ok, until now, we thought this PHI node was dead.  Mark it as being
314         // alive/needed.
315         DeadPHINodes.erase(DPNI);
316
317         // Now that we have marked the PHI node alive, also mark any PHI nodes
318         // which it might use as being alive as well.
319         for (pred_iterator PI = pred_begin(DomBB), PE = pred_end(DomBB);
320              PI != PE; ++PI)
321           MarkDominatingPHILive(*PI, AllocaNum, DeadPHINodes);
322       }
323     }
324   }
325 }
326
327 // PromoteLocallyUsedAlloca - Many allocas are only used within a single basic
328 // block.  If this is the case, avoid traversing the CFG and inserting a lot of
329 // potentially useless PHI nodes by just performing a single linear pass over
330 // the basic block using the Alloca.
331 //
332 void PromoteMem2Reg::PromoteLocallyUsedAlloca(AllocaInst *AI) {
333   assert(!AI->use_empty() && "There are no uses of the alloca!");
334
335   // Uses of the uninitialized memory location shall get zero...
336   Value *CurVal = Constant::getNullValue(AI->getAllocatedType());
337   
338   BasicBlock *BB = cast<Instruction>(AI->use_back())->getParent();
339
340   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
341     Instruction *Inst = I++;
342     if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
343       if (LI->getOperand(0) == AI) {
344         // Loads just return the "current value"...
345         LI->replaceAllUsesWith(CurVal);
346         BB->getInstList().erase(LI);
347       }
348     } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
349       if (SI->getOperand(1) == AI) {
350         // Loads just update the "current value"...
351         CurVal = SI->getOperand(0);
352         BB->getInstList().erase(SI);
353       }
354     }
355   }
356
357   // After traversing the basic block, there should be no more uses of the
358   // alloca, remove it now.
359   assert(AI->use_empty() && "Uses of alloca from more than one BB??");
360   AI->getParent()->getInstList().erase(AI);
361 }
362
363 // QueuePhiNode - queues a phi-node to be added to a basic-block for a specific
364 // Alloca returns true if there wasn't already a phi-node for that variable
365 //
366 bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo,
367                                   unsigned &Version,
368                                   std::set<PHINode*> &InsertedPHINodes) {
369   // Look up the basic-block in question
370   std::vector<PHINode*> &BBPNs = NewPhiNodes[BB];
371   if (BBPNs.empty()) BBPNs.resize(Allocas.size());
372
373   // If the BB already has a phi node added for the i'th alloca then we're done!
374   if (BBPNs[AllocaNo]) return false;
375
376   // Create a PhiNode using the dereferenced type... and add the phi-node to the
377   // BasicBlock.
378   BBPNs[AllocaNo] = new PHINode(Allocas[AllocaNo]->getAllocatedType(),
379                                 Allocas[AllocaNo]->getName() + "." +
380                                         utostr(Version++), BB->begin());
381   InsertedPHINodes.insert(BBPNs[AllocaNo]);
382   return true;
383 }
384
385
386 // RenamePass - Recursively traverse the CFG of the function, renaming loads and
387 // stores to the allocas which we are promoting.  IncomingVals indicates what
388 // value each Alloca contains on exit from the predecessor block Pred.
389 //
390 void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
391                                 std::vector<Value*> &IncomingVals) {
392
393   // If this BB needs a PHI node, update the PHI node for each variable we need
394   // PHI nodes for.
395   std::map<BasicBlock*, std::vector<PHINode *> >::iterator
396     BBPNI = NewPhiNodes.find(BB);
397   if (BBPNI != NewPhiNodes.end()) {
398     std::vector<PHINode *> &BBPNs = BBPNI->second;
399     for (unsigned k = 0; k != BBPNs.size(); ++k)
400       if (PHINode *PN = BBPNs[k]) {
401         // Add this incoming value to the PHI node.
402         PN->addIncoming(IncomingVals[k], Pred);
403
404         // The currently active variable for this block is now the PHI.
405         IncomingVals[k] = PN;
406       }
407   }
408
409   // don't revisit nodes
410   if (Visited.count(BB)) return;
411   
412   // mark as visited
413   Visited.insert(BB);
414
415   for (BasicBlock::iterator II = BB->begin(); !isa<TerminatorInst>(II); ) {
416     Instruction *I = II++; // get the instruction, increment iterator
417
418     if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
419       if (AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand())) {
420         std::map<AllocaInst*, unsigned>::iterator AI = AllocaLookup.find(Src);
421         if (AI != AllocaLookup.end()) {
422           Value *V = IncomingVals[AI->second];
423
424           // walk the use list of this load and replace all uses with r
425           LI->replaceAllUsesWith(V);
426           BB->getInstList().erase(LI);
427         }
428       }
429     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
430       // Delete this instruction and mark the name as the current holder of the
431       // value
432       if (AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand())) {
433         std::map<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest);
434         if (ai != AllocaLookup.end()) {
435           // what value were we writing?
436           IncomingVals[ai->second] = SI->getOperand(0);
437           BB->getInstList().erase(SI);
438         }
439       }
440     }
441   }
442
443   // Recurse to our successors.
444   TerminatorInst *TI = BB->getTerminator();
445   for (unsigned i = 0; i != TI->getNumSuccessors(); i++) {
446     std::vector<Value*> OutgoingVals(IncomingVals);
447     RenamePass(TI->getSuccessor(i), BB, OutgoingVals);
448   }
449 }
450
451 /// PromoteMemToReg - Promote the specified list of alloca instructions into
452 /// scalar registers, inserting PHI nodes as appropriate.  This function makes
453 /// use of DominanceFrontier information.  This function does not modify the CFG
454 /// of the function at all.  All allocas must be from the same function.
455 ///
456 void llvm::PromoteMemToReg(const std::vector<AllocaInst*> &Allocas,
457                            DominatorTree &DT, DominanceFrontier &DF,
458                            const TargetData &TD) {
459   // If there is nothing to do, bail out...
460   if (Allocas.empty()) return;
461   PromoteMem2Reg(Allocas, DT, DF, TD).run();
462 }