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