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