Bunch up all locally used allocas by the block they are allocated in, and
[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 (or that have
12 // PHI nodes which are only loaded from).  An alloca is transformed by using
13 // dominator frontiers to place PHI nodes, then traversing the function in
14 // depth-first order to rewrite loads and stores as appropriate.  This is just
15 // the standard SSA construction algorithm to construct "pruned" 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/iOther.h"
24 #include "llvm/Function.h"
25 #include "llvm/Constant.h"
26 #include "llvm/Support/CFG.h"
27 #include "Support/StringExtras.h"
28 using namespace llvm;
29
30 /// isAllocaPromotable - Return true if this alloca is legal for promotion.
31 /// This is true if there are only loads and stores to the alloca... of if there
32 /// is a PHI node using the address which can be trivially transformed.
33 ///
34 bool llvm::isAllocaPromotable(const AllocaInst *AI, const TargetData &TD) {
35   // FIXME: If the memory unit is of pointer or integer type, we can permit
36   // assignments to subsections of the memory unit.
37
38   // Only allow direct loads and stores...
39   for (Value::use_const_iterator UI = AI->use_begin(), UE = AI->use_end();
40        UI != UE; ++UI)     // Loop over all of the uses of the alloca
41     if (isa<LoadInst>(*UI)) {
42       // noop
43     } else if (const StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
44       if (SI->getOperand(0) == AI)
45         return false;   // Don't allow a store OF the AI, only INTO the AI.
46     } else if (const PHINode *PN = dyn_cast<PHINode>(*UI)) {
47       // We only support PHI nodes in a few simple cases.  The PHI node is only
48       // allowed to have one use, which must be a load instruction, and can only
49       // use alloca instructions (no random pointers).  Also, there cannot be
50       // any accesses to AI between the PHI node and the use of the PHI.
51       if (!PN->hasOneUse()) return false;
52
53       // Our transformation causes the unconditional loading of all pointer
54       // operands to the PHI node.  Because this could cause a fault if there is
55       // a critical edge in the CFG and if one of the pointers is illegal, we
56       // refuse to promote PHI nodes unless they are obviously safe.  For now,
57       // obviously safe means that all of the operands are allocas.
58       //
59       // If we wanted to extend this code to break critical edges, this
60       // restriction could be relaxed, and we could even handle uses of the PHI
61       // node that are volatile loads or stores.
62       //
63       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
64         if (!isa<AllocaInst>(PN->getIncomingValue(i)))
65           return false;
66       
67       // Now make sure the one user instruction is in the same basic block as
68       // the PHI, and that there are no loads or stores between the PHI node and
69       // the access.
70       BasicBlock::const_iterator UI = cast<Instruction>(PN->use_back());
71       if (!isa<LoadInst>(UI) || cast<LoadInst>(UI)->isVolatile()) return false;
72       
73       // Scan looking for memory accesses.
74       for (--UI; !isa<PHINode>(UI); --UI)
75         if (isa<LoadInst>(UI) || isa<StoreInst>(UI) || isa<CallInst>(UI))
76           return false;
77
78       // If we got this far, we can promote the PHI use.
79     } else {
80       return false;   // Not a load, store, or promotable PHI?
81     }
82   
83   return true;
84 }
85
86 namespace {
87   struct PromoteMem2Reg {
88     // Allocas - The alloca instructions being promoted
89     std::vector<AllocaInst*> Allocas;
90     DominatorTree &DT;
91     DominanceFrontier &DF;
92     const TargetData &TD;
93
94     // AllocaLookup - Reverse mapping of Allocas
95     std::map<AllocaInst*, unsigned>  AllocaLookup;
96
97     // NewPhiNodes - The PhiNodes we're adding.
98     std::map<BasicBlock*, std::vector<PHINode*> > NewPhiNodes;
99
100     // Visited - The set of basic blocks the renamer has already visited.
101     std::set<BasicBlock*> Visited;
102
103   public:
104     PromoteMem2Reg(const std::vector<AllocaInst*> &A, DominatorTree &dt,
105                    DominanceFrontier &df, const TargetData &td)
106       : Allocas(A), DT(dt), DF(df), TD(td) {}
107
108     void run();
109
110   private:
111     void MarkDominatingPHILive(BasicBlock *BB, unsigned AllocaNum,
112                                std::set<PHINode*> &DeadPHINodes);
113     void PromoteLocallyUsedAlloca(BasicBlock *BB, AllocaInst *AI);
114     void PromoteLocallyUsedAllocas(BasicBlock *BB, 
115                                    const std::vector<AllocaInst*> &AIs);
116
117     void RenamePass(BasicBlock *BB, BasicBlock *Pred,
118                     std::vector<Value*> &IncVals);
119     bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx, unsigned &Version,
120                       std::set<PHINode*> &InsertedPHINodes);
121   };
122 }  // end of anonymous namespace
123
124 void PromoteMem2Reg::run() {
125   Function &F = *DF.getRoot()->getParent();
126
127   // LocallyUsedAllocas - Keep track of all of the alloca instructions which are
128   // only used in a single basic block.  These instructions can be efficiently
129   // promoted by performing a single linear scan over that one block.  Since
130   // individual basic blocks are sometimes large, we group together all allocas
131   // that are live in a single basic block by the basic block they are live in.
132   std::map<BasicBlock*, std::vector<AllocaInst*> > LocallyUsedAllocas;
133
134   for (unsigned AllocaNum = 0; AllocaNum != Allocas.size(); ++AllocaNum) {
135     AllocaInst *AI = Allocas[AllocaNum];
136
137     assert(isAllocaPromotable(AI, TD) &&
138            "Cannot promote non-promotable alloca!");
139     assert(AI->getParent()->getParent() == &F &&
140            "All allocas should be in the same function, which is same as DF!");
141
142     if (AI->use_empty()) {
143       // If there are no uses of the alloca, just delete it now.
144       AI->getParent()->getInstList().erase(AI);
145
146       // Remove the alloca from the Allocas list, since it has been processed
147       Allocas[AllocaNum] = Allocas.back();
148       Allocas.pop_back();
149       --AllocaNum;
150       continue;
151     }
152
153     // Calculate the set of read and write-locations for each alloca.  This is
154     // analogous to finding the 'uses' and 'definitions' of each variable.
155     std::vector<BasicBlock*> DefiningBlocks;
156     std::vector<BasicBlock*> UsingBlocks;
157
158     BasicBlock *OnlyBlock = 0;
159     bool OnlyUsedInOneBlock = true;
160
161     // As we scan the uses of the alloca instruction, keep track of stores, and
162     // decide whether all of the loads and stores to the alloca are within the
163     // same basic block.
164   RestartUseScan:
165     for (Value::use_iterator U =AI->use_begin(), E = AI->use_end(); U != E;++U){
166       Instruction *User = cast<Instruction>(*U);
167       if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
168         // Remember the basic blocks which define new values for the alloca
169         DefiningBlocks.push_back(SI->getParent());
170       } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
171         // Otherwise it must be a load instruction, keep track of variable reads
172         UsingBlocks.push_back(LI->getParent());
173       } else {
174         // Because of the restrictions we placed on PHI node uses above, the PHI
175         // node reads the block in any using predecessors.  Transform the PHI of
176         // addresses into a PHI of loaded values.
177         PHINode *PN = cast<PHINode>(User);
178         assert(PN->hasOneUse() && "Cannot handle PHI Node with != 1 use!");
179         LoadInst *PNUser = cast<LoadInst>(PN->use_back());
180         std::string PNUserName = PNUser->getName(); PNUser->setName("");
181
182         // Create the new PHI node and insert load instructions as appropriate.
183         PHINode *NewPN = new PHINode(AI->getAllocatedType(), PNUserName, PN);
184         std::map<BasicBlock*, LoadInst*> NewLoads;
185         for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
186           BasicBlock *Pred = PN->getIncomingBlock(i);
187           LoadInst *&NewLoad = NewLoads[Pred];
188           if (NewLoad == 0)  // Insert the new load in the predecessor
189             NewLoad = new LoadInst(PN->getIncomingValue(i),
190                                    PN->getIncomingValue(i)->getName()+".val",
191                                    Pred->getTerminator());
192           NewPN->addIncoming(NewLoad, Pred);
193         }
194
195         // Remove the old load.
196         PNUser->replaceAllUsesWith(NewPN);
197         PNUser->getParent()->getInstList().erase(PNUser);
198
199         // Remove the old PHI node.
200         PN->getParent()->getInstList().erase(PN);
201
202         // Restart our scan of uses...
203         DefiningBlocks.clear();
204         UsingBlocks.clear();
205         goto RestartUseScan;
206       }
207
208       if (OnlyUsedInOneBlock) {
209         if (OnlyBlock == 0)
210           OnlyBlock = User->getParent();
211         else if (OnlyBlock != User->getParent())
212           OnlyUsedInOneBlock = false;
213       }
214     }
215
216     // If the alloca is only read and written in one basic block, just perform a
217     // linear sweep over the block to eliminate it.
218     if (OnlyUsedInOneBlock) {
219       LocallyUsedAllocas[OnlyBlock].push_back(AI);
220
221       // Remove the alloca from the Allocas list, since it will be processed.
222       Allocas[AllocaNum] = Allocas.back();
223       Allocas.pop_back();
224       --AllocaNum;
225       continue;
226     }
227
228     // Compute the locations where PhiNodes need to be inserted.  Look at the
229     // dominance frontier of EACH basic-block we have a write in.
230     //
231     unsigned CurrentVersion = 0;
232     std::set<PHINode*> InsertedPHINodes;
233     while (!DefiningBlocks.empty()) {
234       BasicBlock *BB = DefiningBlocks.back();
235       DefiningBlocks.pop_back();
236
237       // Look up the DF for this write, add it to PhiNodes
238       DominanceFrontier::const_iterator it = DF.find(BB);
239       if (it != DF.end()) {
240         const DominanceFrontier::DomSetType &S = it->second;
241         for (DominanceFrontier::DomSetType::iterator P = S.begin(),PE = S.end();
242              P != PE; ++P)
243           if (QueuePhiNode(*P, AllocaNum, CurrentVersion, InsertedPHINodes))
244             DefiningBlocks.push_back(*P);
245       }
246     }
247
248     // Now that we have inserted PHI nodes along the Iterated Dominance Frontier
249     // of the writes to the variable, scan through the reads of the variable,
250     // marking PHI nodes which are actually necessary as alive (by removing them
251     // from the InsertedPHINodes set).  This is not perfect: there may PHI
252     // marked alive because of loads which are dominated by stores, but there
253     // will be no unmarked PHI nodes which are actually used.
254     //
255     for (unsigned i = 0, e = UsingBlocks.size(); i != e; ++i)
256       MarkDominatingPHILive(UsingBlocks[i], AllocaNum, InsertedPHINodes);
257     UsingBlocks.clear();
258
259     // If there are any PHI nodes which are now known to be dead, remove them!
260     for (std::set<PHINode*>::iterator I = InsertedPHINodes.begin(),
261            E = InsertedPHINodes.end(); I != E; ++I) {
262       PHINode *PN = *I;
263       std::vector<PHINode*> &BBPNs = NewPhiNodes[PN->getParent()];
264       BBPNs[AllocaNum] = 0;
265
266       // Check to see if we just removed the last inserted PHI node from this
267       // basic block.  If so, remove the entry for the basic block.
268       bool HasOtherPHIs = false;
269       for (unsigned i = 0, e = BBPNs.size(); i != e; ++i)
270         if (BBPNs[i]) {
271           HasOtherPHIs = true;
272           break;
273         }
274       if (!HasOtherPHIs)
275         NewPhiNodes.erase(PN->getParent());
276
277       PN->getParent()->getInstList().erase(PN);      
278     }
279
280     // Keep the reverse mapping of the 'Allocas' array. 
281     AllocaLookup[Allocas[AllocaNum]] = AllocaNum;
282   }
283   
284   // Process all allocas which are only used in a single basic block.
285   for (std::map<BasicBlock*, std::vector<AllocaInst*> >::iterator I =
286          LocallyUsedAllocas.begin(), E = LocallyUsedAllocas.end(); I != E; ++I){
287     const std::vector<AllocaInst*> &Allocas = I->second;
288     assert(!Allocas.empty() && "empty alloca list??");
289
290     // It's common for there to only be one alloca in the list.  Handle it
291     // efficiently.
292     if (Allocas.size() == 1)
293       PromoteLocallyUsedAlloca(I->first, Allocas[0]);
294     else
295       PromoteLocallyUsedAllocas(I->first, Allocas);
296   }
297
298   if (Allocas.empty())
299     return; // All of the allocas must have been trivial!
300
301   // Set the incoming values for the basic block to be null values for all of
302   // the alloca's.  We do this in case there is a load of a value that has not
303   // been stored yet.  In this case, it will get this null value.
304   //
305   std::vector<Value *> Values(Allocas.size());
306   for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
307     Values[i] = Constant::getNullValue(Allocas[i]->getAllocatedType());
308
309   // Walks all basic blocks in the function performing the SSA rename algorithm
310   // and inserting the phi nodes we marked as necessary
311   //
312   RenamePass(F.begin(), 0, Values);
313
314   // The renamer uses the Visited set to avoid infinite loops.  Clear it now.
315   Visited.clear();
316
317   // Remove the allocas themselves from the function...
318   for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
319     Instruction *A = Allocas[i];
320
321     // If there are any uses of the alloca instructions left, they must be in
322     // sections of dead code that were not processed on the dominance frontier.
323     // Just delete the users now.
324     //
325     if (!A->use_empty())
326       A->replaceAllUsesWith(Constant::getNullValue(A->getType()));
327     A->getParent()->getInstList().erase(A);
328   }
329
330   // At this point, the renamer has added entries to PHI nodes for all reachable
331   // code.  Unfortunately, there may be blocks which are not reachable, which
332   // the renamer hasn't traversed.  If this is the case, the PHI nodes may not
333   // have incoming values for all predecessors.  Loop over all PHI nodes we have
334   // created, inserting null constants if they are missing any incoming values.
335   //
336   for (std::map<BasicBlock*, std::vector<PHINode *> >::iterator I = 
337          NewPhiNodes.begin(), E = NewPhiNodes.end(); I != E; ++I) {
338
339     std::vector<BasicBlock*> Preds(pred_begin(I->first), pred_end(I->first));
340     std::vector<PHINode*> &PNs = I->second;
341     assert(!PNs.empty() && "Empty PHI node list??");
342
343     // Only do work here if there the PHI nodes are missing incoming values.  We
344     // know that all PHI nodes that were inserted in a block will have the same
345     // number of incoming values, so we can just check any PHI node.
346     PHINode *FirstPHI;
347     for (unsigned i = 0; (FirstPHI = PNs[i]) == 0; ++i)
348       /*empty*/;
349
350     if (Preds.size() != FirstPHI->getNumIncomingValues()) {
351       // Ok, now we know that all of the PHI nodes are missing entries for some
352       // basic blocks.  Start by sorting the incoming predecessors for efficient
353       // access.
354       std::sort(Preds.begin(), Preds.end());
355
356       // Now we loop through all BB's which have entries in FirstPHI and remove
357       // them from the Preds list.
358       for (unsigned i = 0, e = FirstPHI->getNumIncomingValues(); i != e; ++i) {
359         // Do a log(n) search of the Preds list for the entry we want.
360         std::vector<BasicBlock*>::iterator EntIt =
361           std::lower_bound(Preds.begin(), Preds.end(),
362                            FirstPHI->getIncomingBlock(i));
363         assert(EntIt != Preds.end() && *EntIt == FirstPHI->getIncomingBlock(i)&&
364                "PHI node has entry for a block which is not a predecessor!");
365
366         // Remove the entry
367         Preds.erase(EntIt);
368       }
369
370       // At this point, the blocks left in the preds list must have dummy
371       // entries inserted into every PHI nodes for the block.
372       for (unsigned i = 0, e = PNs.size(); i != e; ++i)
373         if (PHINode *PN = PNs[i]) {
374           Value *NullVal = Constant::getNullValue(PN->getType());
375           for (unsigned pred = 0, e = Preds.size(); pred != e; ++pred)
376             PN->addIncoming(NullVal, Preds[pred]);
377         }
378     }
379   }
380 }
381
382 // MarkDominatingPHILive - Mem2Reg wants to construct "pruned" SSA form, not
383 // "minimal" SSA form.  To do this, it inserts all of the PHI nodes on the IDF
384 // as usual (inserting the PHI nodes in the DeadPHINodes set), then processes
385 // each read of the variable.  For each block that reads the variable, this
386 // function is called, which removes used PHI nodes from the DeadPHINodes set.
387 // After all of the reads have been processed, any PHI nodes left in the
388 // DeadPHINodes set are removed.
389 //
390 void PromoteMem2Reg::MarkDominatingPHILive(BasicBlock *BB, unsigned AllocaNum,
391                                            std::set<PHINode*> &DeadPHINodes) {
392   // Scan the immediate dominators of this block looking for a block which has a
393   // PHI node for Alloca num.  If we find it, mark the PHI node as being alive!
394   for (DominatorTree::Node *N = DT[BB]; N; N = N->getIDom()) {
395     BasicBlock *DomBB = N->getBlock();
396     std::map<BasicBlock*, std::vector<PHINode*> >::iterator
397       I = NewPhiNodes.find(DomBB);
398     if (I != NewPhiNodes.end() && I->second[AllocaNum]) {
399       // Ok, we found an inserted PHI node which dominates this value.
400       PHINode *DominatingPHI = I->second[AllocaNum];
401
402       // Find out if we previously thought it was dead.
403       std::set<PHINode*>::iterator DPNI = DeadPHINodes.find(DominatingPHI);
404       if (DPNI != DeadPHINodes.end()) {
405         // Ok, until now, we thought this PHI node was dead.  Mark it as being
406         // alive/needed.
407         DeadPHINodes.erase(DPNI);
408
409         // Now that we have marked the PHI node alive, also mark any PHI nodes
410         // which it might use as being alive as well.
411         for (pred_iterator PI = pred_begin(DomBB), PE = pred_end(DomBB);
412              PI != PE; ++PI)
413           MarkDominatingPHILive(*PI, AllocaNum, DeadPHINodes);
414       }
415     }
416   }
417 }
418
419 /// PromoteLocallyUsedAlloca - Many allocas are only used within a single basic
420 /// block.  If this is the case, avoid traversing the CFG and inserting a lot of
421 /// potentially useless PHI nodes by just performing a single linear pass over
422 /// the basic block using the Alloca.
423 ///
424 void PromoteMem2Reg::PromoteLocallyUsedAlloca(BasicBlock *BB, AllocaInst *AI) {
425   assert(!AI->use_empty() && "There are no uses of the alloca!");
426
427   // Handle degenerate cases quickly.
428   if (AI->hasOneUse()) {
429     Instruction *U = cast<Instruction>(AI->use_back());
430     if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
431       // Must be a load of uninitialized value.
432       LI->replaceAllUsesWith(Constant::getNullValue(AI->getAllocatedType()));
433     } else {
434       // Otherwise it must be a store which is never read.
435       assert(isa<StoreInst>(U));
436     }
437     BB->getInstList().erase(U);
438   } else {
439     // Uses of the uninitialized memory location shall get zero...
440     Value *CurVal = Constant::getNullValue(AI->getAllocatedType());
441   
442     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
443       Instruction *Inst = I++;
444       if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
445         if (LI->getOperand(0) == AI) {
446           // Loads just returns the "current value"...
447           LI->replaceAllUsesWith(CurVal);
448           BB->getInstList().erase(LI);
449         }
450       } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
451         if (SI->getOperand(1) == AI) {
452           // Store updates the "current value"...
453           CurVal = SI->getOperand(0);
454           BB->getInstList().erase(SI);
455         }
456       }
457     }
458   }
459
460   // After traversing the basic block, there should be no more uses of the
461   // alloca, remove it now.
462   assert(AI->use_empty() && "Uses of alloca from more than one BB??");
463   AI->getParent()->getInstList().erase(AI);
464 }
465
466 /// PromoteLocallyUsedAllocas - This method is just like
467 /// PromoteLocallyUsedAlloca, except that it processes multiple alloca
468 /// instructions in parallel.  This is important in cases where we have large
469 /// basic blocks, as we don't want to rescan the entire basic block for each
470 /// alloca which is locally used in it (which might be a lot).
471 void PromoteMem2Reg::
472 PromoteLocallyUsedAllocas(BasicBlock *BB, const std::vector<AllocaInst*> &AIs) {
473   std::map<AllocaInst*, Value*> CurValues;
474   for (unsigned i = 0, e = AIs.size(); i != e; ++i)
475     CurValues[AIs[i]] = 0; // Insert with null value
476
477   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
478     Instruction *Inst = I++;
479     if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
480       // Is this a load of an alloca we are tracking?
481       if (AllocaInst *AI = dyn_cast<AllocaInst>(LI->getOperand(0))) {
482         std::map<AllocaInst*, Value*>::iterator AIt = CurValues.find(AI);
483         if (AIt != CurValues.end()) {
484           // Loads just returns the "current value"...
485           if (AIt->second == 0)   // Uninitialized value??
486             AIt->second =Constant::getNullValue(AIt->first->getAllocatedType());
487           LI->replaceAllUsesWith(AIt->second);
488           BB->getInstList().erase(LI);
489         }
490       }
491     } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
492       if (AllocaInst *AI = dyn_cast<AllocaInst>(SI->getOperand(1))) {
493         std::map<AllocaInst*, Value*>::iterator AIt = CurValues.find(AI);
494         if (AIt != CurValues.end()) {
495           // Store updates the "current value"...
496           AIt->second = SI->getOperand(0);
497           BB->getInstList().erase(SI);
498         }
499       }
500     }
501   }
502 }
503
504
505
506 // QueuePhiNode - queues a phi-node to be added to a basic-block for a specific
507 // Alloca returns true if there wasn't already a phi-node for that variable
508 //
509 bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo,
510                                   unsigned &Version,
511                                   std::set<PHINode*> &InsertedPHINodes) {
512   // Look up the basic-block in question
513   std::vector<PHINode*> &BBPNs = NewPhiNodes[BB];
514   if (BBPNs.empty()) BBPNs.resize(Allocas.size());
515
516   // If the BB already has a phi node added for the i'th alloca then we're done!
517   if (BBPNs[AllocaNo]) return false;
518
519   // Create a PhiNode using the dereferenced type... and add the phi-node to the
520   // BasicBlock.
521   BBPNs[AllocaNo] = new PHINode(Allocas[AllocaNo]->getAllocatedType(),
522                                 Allocas[AllocaNo]->getName() + "." +
523                                         utostr(Version++), BB->begin());
524   InsertedPHINodes.insert(BBPNs[AllocaNo]);
525   return true;
526 }
527
528
529 // RenamePass - Recursively traverse the CFG of the function, renaming loads and
530 // stores to the allocas which we are promoting.  IncomingVals indicates what
531 // value each Alloca contains on exit from the predecessor block Pred.
532 //
533 void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
534                                 std::vector<Value*> &IncomingVals) {
535
536   // If this BB needs a PHI node, update the PHI node for each variable we need
537   // PHI nodes for.
538   std::map<BasicBlock*, std::vector<PHINode *> >::iterator
539     BBPNI = NewPhiNodes.find(BB);
540   if (BBPNI != NewPhiNodes.end()) {
541     std::vector<PHINode *> &BBPNs = BBPNI->second;
542     for (unsigned k = 0; k != BBPNs.size(); ++k)
543       if (PHINode *PN = BBPNs[k]) {
544         // Add this incoming value to the PHI node.
545         PN->addIncoming(IncomingVals[k], Pred);
546
547         // The currently active variable for this block is now the PHI.
548         IncomingVals[k] = PN;
549       }
550   }
551
552   // don't revisit nodes
553   if (Visited.count(BB)) return;
554   
555   // mark as visited
556   Visited.insert(BB);
557
558   for (BasicBlock::iterator II = BB->begin(); !isa<TerminatorInst>(II); ) {
559     Instruction *I = II++; // get the instruction, increment iterator
560
561     if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
562       if (AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand())) {
563         std::map<AllocaInst*, unsigned>::iterator AI = AllocaLookup.find(Src);
564         if (AI != AllocaLookup.end()) {
565           Value *V = IncomingVals[AI->second];
566
567           // walk the use list of this load and replace all uses with r
568           LI->replaceAllUsesWith(V);
569           BB->getInstList().erase(LI);
570         }
571       }
572     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
573       // Delete this instruction and mark the name as the current holder of the
574       // value
575       if (AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand())) {
576         std::map<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest);
577         if (ai != AllocaLookup.end()) {
578           // what value were we writing?
579           IncomingVals[ai->second] = SI->getOperand(0);
580           BB->getInstList().erase(SI);
581         }
582       }
583     }
584   }
585
586   // Recurse to our successors.
587   TerminatorInst *TI = BB->getTerminator();
588   for (unsigned i = 0; i != TI->getNumSuccessors(); i++) {
589     std::vector<Value*> OutgoingVals(IncomingVals);
590     RenamePass(TI->getSuccessor(i), BB, OutgoingVals);
591   }
592 }
593
594 /// PromoteMemToReg - Promote the specified list of alloca instructions into
595 /// scalar registers, inserting PHI nodes as appropriate.  This function makes
596 /// use of DominanceFrontier information.  This function does not modify the CFG
597 /// of the function at all.  All allocas must be from the same function.
598 ///
599 void llvm::PromoteMemToReg(const std::vector<AllocaInst*> &Allocas,
600                            DominatorTree &DT, DominanceFrontier &DF,
601                            const TargetData &TD) {
602   // If there is nothing to do, bail out...
603   if (Allocas.empty()) return;
604   PromoteMem2Reg(Allocas, DT, DF, TD).run();
605 }