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