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