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