Handle (delete) dbg intrinsics while promoting alloca.
[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 is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file promotes 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/IntrinsicInst.h"
26 #include "llvm/Analysis/Dominators.h"
27 #include "llvm/Analysis/AliasSetTracker.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/ADT/StringExtras.h"
33 #include "llvm/Support/CFG.h"
34 #include "llvm/Support/Compiler.h"
35 #include <algorithm>
36 using namespace llvm;
37
38 STATISTIC(NumLocalPromoted, "Number of alloca's promoted within one block");
39 STATISTIC(NumSingleStore,   "Number of alloca's promoted with a single store");
40 STATISTIC(NumDeadAlloca,    "Number of dead alloca's removed");
41 STATISTIC(NumPHIInsert,     "Number of PHI nodes inserted");
42
43 // Provide DenseMapInfo for all pointers.
44 namespace llvm {
45 template<>
46 struct DenseMapInfo<std::pair<BasicBlock*, unsigned> > {
47   typedef std::pair<BasicBlock*, unsigned> EltTy;
48   static inline EltTy getEmptyKey() {
49     return EltTy(reinterpret_cast<BasicBlock*>(-1), ~0U);
50   }
51   static inline EltTy getTombstoneKey() {
52     return EltTy(reinterpret_cast<BasicBlock*>(-2), 0U);
53   }
54   static unsigned getHashValue(const std::pair<BasicBlock*, unsigned> &Val) {
55     return DenseMapInfo<void*>::getHashValue(Val.first) + Val.second*2;
56   }
57   static bool isEqual(const EltTy &LHS, const EltTy &RHS) {
58     return LHS == RHS;
59   }
60   static bool isPod() { return true; }
61 };
62 }
63
64 /// isAllocaPromotable - Return true if this alloca is legal for promotion.
65 /// This is true if there are only loads and stores to the alloca.
66 ///
67 bool llvm::isAllocaPromotable(const AllocaInst *AI) {
68   // FIXME: If the memory unit is of pointer or integer type, we can permit
69   // assignments to subsections of the memory unit.
70
71   // Only allow direct and non-volatile loads and stores...
72   for (Value::use_const_iterator UI = AI->use_begin(), UE = AI->use_end();
73        UI != UE; ++UI)     // Loop over all of the uses of the alloca
74     if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
75       if (LI->isVolatile())
76         return false;
77     } else if (const StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
78       if (SI->getOperand(0) == AI)
79         return false;   // Don't allow a store OF the AI, only INTO the AI.
80       if (SI->isVolatile())
81         return false;
82     } else {
83       const BitCastInst *BC = dyn_cast<BitCastInst>(*UI);
84       if (!BC) 
85         return false;   // Not a load or store or dbg intrinsic.
86       Value::use_const_iterator BCUI = BC->use_begin(), BCUE = BC->use_end();
87       if (BCUI == BCUE) 
88         return false; // Not a dbg intrinsic.
89       const DbgInfoIntrinsic *DI = dyn_cast<DbgInfoIntrinsic>(*BCUI);
90       if (!DI) 
91         return false; // Not a dbg intrinsic.
92       BCUI++; 
93       if (BCUI != BCUE) 
94         return false; // Not a dbg intrinsic use.
95     }
96
97   return true;
98 }
99
100 namespace {
101   struct AllocaInfo;
102
103   // Data package used by RenamePass()
104   class VISIBILITY_HIDDEN RenamePassData {
105   public:
106     typedef std::vector<Value *> ValVector;
107     
108     RenamePassData() {}
109     RenamePassData(BasicBlock *B, BasicBlock *P,
110                    const ValVector &V) : BB(B), Pred(P), Values(V) {}
111     BasicBlock *BB;
112     BasicBlock *Pred;
113     ValVector Values;
114     
115     void swap(RenamePassData &RHS) {
116       std::swap(BB, RHS.BB);
117       std::swap(Pred, RHS.Pred);
118       Values.swap(RHS.Values);
119     }
120   };
121   
122   /// LargeBlockInfo - This assigns and keeps a per-bb relative ordering of
123   /// load/store instructions in the block that directly load or store an alloca.
124   ///
125   /// This functionality is important because it avoids scanning large basic
126   /// blocks multiple times when promoting many allocas in the same block.
127   class VISIBILITY_HIDDEN LargeBlockInfo {
128     /// InstNumbers - For each instruction that we track, keep the index of the
129     /// instruction.  The index starts out as the number of the instruction from
130     /// the start of the block.
131     DenseMap<const Instruction *, unsigned> InstNumbers;
132   public:
133     
134     /// isInterestingInstruction - This code only looks at accesses to allocas.
135     static bool isInterestingInstruction(const Instruction *I) {
136       return (isa<LoadInst>(I) && isa<AllocaInst>(I->getOperand(0))) ||
137              (isa<StoreInst>(I) && isa<AllocaInst>(I->getOperand(1)));
138     }
139     
140     /// getInstructionIndex - Get or calculate the index of the specified
141     /// instruction.
142     unsigned getInstructionIndex(const Instruction *I) {
143       assert(isInterestingInstruction(I) &&
144              "Not a load/store to/from an alloca?");
145       
146       // If we already have this instruction number, return it.
147       DenseMap<const Instruction *, unsigned>::iterator It = InstNumbers.find(I);
148       if (It != InstNumbers.end()) return It->second;
149       
150       // Scan the whole block to get the instruction.  This accumulates
151       // information for every interesting instruction in the block, in order to
152       // avoid gratuitus rescans.
153       const BasicBlock *BB = I->getParent();
154       unsigned InstNo = 0;
155       for (BasicBlock::const_iterator BBI = BB->begin(), E = BB->end();
156            BBI != E; ++BBI)
157         if (isInterestingInstruction(BBI))
158           InstNumbers[BBI] = InstNo++;
159       It = InstNumbers.find(I);
160       
161       assert(It != InstNumbers.end() && "Didn't insert instruction?");
162       return It->second;
163     }
164     
165     void deleteValue(const Instruction *I) {
166       InstNumbers.erase(I);
167     }
168     
169     void clear() {
170       InstNumbers.clear();
171     }
172   };
173
174   struct VISIBILITY_HIDDEN PromoteMem2Reg {
175     /// Allocas - The alloca instructions being promoted.
176     ///
177     std::vector<AllocaInst*> Allocas;
178     DominatorTree &DT;
179     DominanceFrontier &DF;
180
181     /// AST - An AliasSetTracker object to update.  If null, don't update it.
182     ///
183     AliasSetTracker *AST;
184
185     /// AllocaLookup - Reverse mapping of Allocas.
186     ///
187     std::map<AllocaInst*, unsigned>  AllocaLookup;
188
189     /// NewPhiNodes - The PhiNodes we're adding.
190     ///
191     DenseMap<std::pair<BasicBlock*, unsigned>, PHINode*> NewPhiNodes;
192     
193     /// PhiToAllocaMap - For each PHI node, keep track of which entry in Allocas
194     /// it corresponds to.
195     DenseMap<PHINode*, unsigned> PhiToAllocaMap;
196     
197     /// PointerAllocaValues - If we are updating an AliasSetTracker, then for
198     /// each alloca that is of pointer type, we keep track of what to copyValue
199     /// to the inserted PHI nodes here.
200     ///
201     std::vector<Value*> PointerAllocaValues;
202
203     /// Visited - The set of basic blocks the renamer has already visited.
204     ///
205     SmallPtrSet<BasicBlock*, 16> Visited;
206
207     /// BBNumbers - Contains a stable numbering of basic blocks to avoid
208     /// non-determinstic behavior.
209     DenseMap<BasicBlock*, unsigned> BBNumbers;
210
211     /// BBNumPreds - Lazily compute the number of predecessors a block has.
212     DenseMap<const BasicBlock*, unsigned> BBNumPreds;
213   public:
214     PromoteMem2Reg(const std::vector<AllocaInst*> &A, DominatorTree &dt,
215                    DominanceFrontier &df, AliasSetTracker *ast)
216       : Allocas(A), DT(dt), DF(df), AST(ast) {}
217
218     void run();
219
220     /// properlyDominates - Return true if I1 properly dominates I2.
221     ///
222     bool properlyDominates(Instruction *I1, Instruction *I2) const {
223       if (InvokeInst *II = dyn_cast<InvokeInst>(I1))
224         I1 = II->getNormalDest()->begin();
225       return DT.properlyDominates(I1->getParent(), I2->getParent());
226     }
227     
228     /// dominates - Return true if BB1 dominates BB2 using the DominatorTree.
229     ///
230     bool dominates(BasicBlock *BB1, BasicBlock *BB2) const {
231       return DT.dominates(BB1, BB2);
232     }
233
234   private:
235     void RemoveFromAllocasList(unsigned &AllocaIdx) {
236       Allocas[AllocaIdx] = Allocas.back();
237       Allocas.pop_back();
238       --AllocaIdx;
239     }
240
241     unsigned getNumPreds(const BasicBlock *BB) {
242       unsigned &NP = BBNumPreds[BB];
243       if (NP == 0)
244         NP = std::distance(pred_begin(BB), pred_end(BB))+1;
245       return NP-1;
246     }
247
248     void DetermineInsertionPoint(AllocaInst *AI, unsigned AllocaNum,
249                                  AllocaInfo &Info);
250     void ComputeLiveInBlocks(AllocaInst *AI, AllocaInfo &Info, 
251                              const SmallPtrSet<BasicBlock*, 32> &DefBlocks,
252                              SmallPtrSet<BasicBlock*, 32> &LiveInBlocks);
253     
254     void RewriteSingleStoreAlloca(AllocaInst *AI, AllocaInfo &Info,
255                                   LargeBlockInfo &LBI);
256     void PromoteSingleBlockAlloca(AllocaInst *AI, AllocaInfo &Info,
257                                   LargeBlockInfo &LBI);
258
259     
260     void RenamePass(BasicBlock *BB, BasicBlock *Pred,
261                     RenamePassData::ValVector &IncVals,
262                     std::vector<RenamePassData> &Worklist);
263     bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx, unsigned &Version,
264                       SmallPtrSet<PHINode*, 16> &InsertedPHINodes);
265   };
266   
267   struct AllocaInfo {
268     std::vector<BasicBlock*> DefiningBlocks;
269     std::vector<BasicBlock*> UsingBlocks;
270     
271     StoreInst  *OnlyStore;
272     BasicBlock *OnlyBlock;
273     bool OnlyUsedInOneBlock;
274     
275     Value *AllocaPointerVal;
276     
277     void clear() {
278       DefiningBlocks.clear();
279       UsingBlocks.clear();
280       OnlyStore = 0;
281       OnlyBlock = 0;
282       OnlyUsedInOneBlock = true;
283       AllocaPointerVal = 0;
284     }
285     
286     /// AnalyzeAlloca - Scan the uses of the specified alloca, filling in our
287     /// ivars.
288     void AnalyzeAlloca(AllocaInst *AI) {
289       clear();
290
291       // As we scan the uses of the alloca instruction, keep track of stores,
292       // and decide whether all of the loads and stores to the alloca are within
293       // the same basic block.
294       for (Value::use_iterator U = AI->use_begin(), E = AI->use_end();
295            U != E; ++U) {
296         Instruction *User = cast<Instruction>(*U);
297         if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
298           // Remove dbg intrinsic uses now.
299           Value::use_iterator BCUI = BC->use_begin();
300           DbgInfoIntrinsic *DI = cast<DbgInfoIntrinsic>(*BCUI);
301           assert (BCUI + 1 == BC->use_end() && "Unexpected alloca uses!");
302           DI->eraseFromParent();
303           BC->eraseFromParent();
304         } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
305           // Remember the basic blocks which define new values for the alloca
306           DefiningBlocks.push_back(SI->getParent());
307           AllocaPointerVal = SI->getOperand(0);
308           OnlyStore = SI;
309         } else {
310           LoadInst *LI = cast<LoadInst>(User);
311           // Otherwise it must be a load instruction, keep track of variable
312           // reads.
313           UsingBlocks.push_back(LI->getParent());
314           AllocaPointerVal = LI;
315         }
316         
317         if (OnlyUsedInOneBlock) {
318           if (OnlyBlock == 0)
319             OnlyBlock = User->getParent();
320           else if (OnlyBlock != User->getParent())
321             OnlyUsedInOneBlock = false;
322         }
323       }
324     }
325   };
326 }  // end of anonymous namespace
327
328
329 void PromoteMem2Reg::run() {
330   Function &F = *DF.getRoot()->getParent();
331
332   if (AST) PointerAllocaValues.resize(Allocas.size());
333
334   AllocaInfo Info;
335   LargeBlockInfo LBI;
336
337   for (unsigned AllocaNum = 0; AllocaNum != Allocas.size(); ++AllocaNum) {
338     AllocaInst *AI = Allocas[AllocaNum];
339
340     assert(isAllocaPromotable(AI) &&
341            "Cannot promote non-promotable alloca!");
342     assert(AI->getParent()->getParent() == &F &&
343            "All allocas should be in the same function, which is same as DF!");
344
345     if (AI->use_empty()) {
346       // If there are no uses of the alloca, just delete it now.
347       if (AST) AST->deleteValue(AI);
348       AI->eraseFromParent();
349
350       // Remove the alloca from the Allocas list, since it has been processed
351       RemoveFromAllocasList(AllocaNum);
352       ++NumDeadAlloca;
353       continue;
354     }
355     
356     // Calculate the set of read and write-locations for each alloca.  This is
357     // analogous to finding the 'uses' and 'definitions' of each variable.
358     Info.AnalyzeAlloca(AI);
359
360     // If there is only a single store to this value, replace any loads of
361     // it that are directly dominated by the definition with the value stored.
362     if (Info.DefiningBlocks.size() == 1) {
363       RewriteSingleStoreAlloca(AI, Info, LBI);
364
365       // Finally, after the scan, check to see if the store is all that is left.
366       if (Info.UsingBlocks.empty()) {
367         // Remove the (now dead) store and alloca.
368         Info.OnlyStore->eraseFromParent();
369         LBI.deleteValue(Info.OnlyStore);
370
371         if (AST) AST->deleteValue(AI);
372         AI->eraseFromParent();
373         LBI.deleteValue(AI);
374         
375         // The alloca has been processed, move on.
376         RemoveFromAllocasList(AllocaNum);
377         
378         ++NumSingleStore;
379         continue;
380       }
381     }
382     
383     // If the alloca is only read and written in one basic block, just perform a
384     // linear sweep over the block to eliminate it.
385     if (Info.OnlyUsedInOneBlock) {
386       PromoteSingleBlockAlloca(AI, Info, LBI);
387       
388       // Finally, after the scan, check to see if the stores are all that is
389       // left.
390       if (Info.UsingBlocks.empty()) {
391         
392         // Remove the (now dead) stores and alloca.
393         while (!AI->use_empty()) {
394           StoreInst *SI = cast<StoreInst>(AI->use_back());
395           SI->eraseFromParent();
396           LBI.deleteValue(SI);
397         }
398         
399         if (AST) AST->deleteValue(AI);
400         AI->eraseFromParent();
401         LBI.deleteValue(AI);
402         
403         // The alloca has been processed, move on.
404         RemoveFromAllocasList(AllocaNum);
405         
406         ++NumLocalPromoted;
407         continue;
408       }
409     }
410     
411     // If we haven't computed a numbering for the BB's in the function, do so
412     // now.
413     if (BBNumbers.empty()) {
414       unsigned ID = 0;
415       for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
416         BBNumbers[I] = ID++;
417     }
418
419     // If we have an AST to keep updated, remember some pointer value that is
420     // stored into the alloca.
421     if (AST)
422       PointerAllocaValues[AllocaNum] = Info.AllocaPointerVal;
423     
424     // Keep the reverse mapping of the 'Allocas' array for the rename pass.
425     AllocaLookup[Allocas[AllocaNum]] = AllocaNum;
426
427     // At this point, we're committed to promoting the alloca using IDF's, and
428     // the standard SSA construction algorithm.  Determine which blocks need PHI
429     // nodes and see if we can optimize out some work by avoiding insertion of
430     // dead phi nodes.
431     DetermineInsertionPoint(AI, AllocaNum, Info);
432   }
433
434   if (Allocas.empty())
435     return; // All of the allocas must have been trivial!
436
437   LBI.clear();
438   
439   
440   // Set the incoming values for the basic block to be null values for all of
441   // the alloca's.  We do this in case there is a load of a value that has not
442   // been stored yet.  In this case, it will get this null value.
443   //
444   RenamePassData::ValVector Values(Allocas.size());
445   for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
446     Values[i] = UndefValue::get(Allocas[i]->getAllocatedType());
447
448   // Walks all basic blocks in the function performing the SSA rename algorithm
449   // and inserting the phi nodes we marked as necessary
450   //
451   std::vector<RenamePassData> RenamePassWorkList;
452   RenamePassWorkList.push_back(RenamePassData(F.begin(), 0, Values));
453   while (!RenamePassWorkList.empty()) {
454     RenamePassData RPD;
455     RPD.swap(RenamePassWorkList.back());
456     RenamePassWorkList.pop_back();
457     // RenamePass may add new worklist entries.
458     RenamePass(RPD.BB, RPD.Pred, RPD.Values, RenamePassWorkList);
459   }
460   
461   // The renamer uses the Visited set to avoid infinite loops.  Clear it now.
462   Visited.clear();
463
464   // Remove the allocas themselves from the function.
465   for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
466     Instruction *A = Allocas[i];
467
468     // If there are any uses of the alloca instructions left, they must be in
469     // sections of dead code that were not processed on the dominance frontier.
470     // Just delete the users now.
471     //
472     if (!A->use_empty())
473       A->replaceAllUsesWith(UndefValue::get(A->getType()));
474     if (AST) AST->deleteValue(A);
475     A->eraseFromParent();
476   }
477
478   
479   // Loop over all of the PHI nodes and see if there are any that we can get
480   // rid of because they merge all of the same incoming values.  This can
481   // happen due to undef values coming into the PHI nodes.  This process is
482   // iterative, because eliminating one PHI node can cause others to be removed.
483   bool EliminatedAPHI = true;
484   while (EliminatedAPHI) {
485     EliminatedAPHI = false;
486     
487     for (DenseMap<std::pair<BasicBlock*, unsigned>, PHINode*>::iterator I =
488            NewPhiNodes.begin(), E = NewPhiNodes.end(); I != E;) {
489       PHINode *PN = I->second;
490       
491       // If this PHI node merges one value and/or undefs, get the value.
492       if (Value *V = PN->hasConstantValue(true)) {
493         if (!isa<Instruction>(V) ||
494             properlyDominates(cast<Instruction>(V), PN)) {
495           if (AST && isa<PointerType>(PN->getType()))
496             AST->deleteValue(PN);
497           PN->replaceAllUsesWith(V);
498           PN->eraseFromParent();
499           NewPhiNodes.erase(I++);
500           EliminatedAPHI = true;
501           continue;
502         }
503       }
504       ++I;
505     }
506   }
507   
508   // At this point, the renamer has added entries to PHI nodes for all reachable
509   // code.  Unfortunately, there may be unreachable blocks which the renamer
510   // hasn't traversed.  If this is the case, the PHI nodes may not
511   // have incoming values for all predecessors.  Loop over all PHI nodes we have
512   // created, inserting undef values if they are missing any incoming values.
513   //
514   for (DenseMap<std::pair<BasicBlock*, unsigned>, PHINode*>::iterator I =
515          NewPhiNodes.begin(), E = NewPhiNodes.end(); I != E; ++I) {
516     // We want to do this once per basic block.  As such, only process a block
517     // when we find the PHI that is the first entry in the block.
518     PHINode *SomePHI = I->second;
519     BasicBlock *BB = SomePHI->getParent();
520     if (&BB->front() != SomePHI)
521       continue;
522
523     // Only do work here if there the PHI nodes are missing incoming values.  We
524     // know that all PHI nodes that were inserted in a block will have the same
525     // number of incoming values, so we can just check any of them.
526     if (SomePHI->getNumIncomingValues() == getNumPreds(BB))
527       continue;
528
529     // Get the preds for BB.
530     SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
531     
532     // Ok, now we know that all of the PHI nodes are missing entries for some
533     // basic blocks.  Start by sorting the incoming predecessors for efficient
534     // access.
535     std::sort(Preds.begin(), Preds.end());
536     
537     // Now we loop through all BB's which have entries in SomePHI and remove
538     // them from the Preds list.
539     for (unsigned i = 0, e = SomePHI->getNumIncomingValues(); i != e; ++i) {
540       // Do a log(n) search of the Preds list for the entry we want.
541       SmallVector<BasicBlock*, 16>::iterator EntIt =
542         std::lower_bound(Preds.begin(), Preds.end(),
543                          SomePHI->getIncomingBlock(i));
544       assert(EntIt != Preds.end() && *EntIt == SomePHI->getIncomingBlock(i)&&
545              "PHI node has entry for a block which is not a predecessor!");
546
547       // Remove the entry
548       Preds.erase(EntIt);
549     }
550
551     // At this point, the blocks left in the preds list must have dummy
552     // entries inserted into every PHI nodes for the block.  Update all the phi
553     // nodes in this block that we are inserting (there could be phis before
554     // mem2reg runs).
555     unsigned NumBadPreds = SomePHI->getNumIncomingValues();
556     BasicBlock::iterator BBI = BB->begin();
557     while ((SomePHI = dyn_cast<PHINode>(BBI++)) &&
558            SomePHI->getNumIncomingValues() == NumBadPreds) {
559       Value *UndefVal = UndefValue::get(SomePHI->getType());
560       for (unsigned pred = 0, e = Preds.size(); pred != e; ++pred)
561         SomePHI->addIncoming(UndefVal, Preds[pred]);
562     }
563   }
564         
565   NewPhiNodes.clear();
566 }
567
568
569 /// ComputeLiveInBlocks - Determine which blocks the value is live in.  These
570 /// are blocks which lead to uses.  Knowing this allows us to avoid inserting
571 /// PHI nodes into blocks which don't lead to uses (thus, the inserted phi nodes
572 /// would be dead).
573 void PromoteMem2Reg::
574 ComputeLiveInBlocks(AllocaInst *AI, AllocaInfo &Info, 
575                     const SmallPtrSet<BasicBlock*, 32> &DefBlocks,
576                     SmallPtrSet<BasicBlock*, 32> &LiveInBlocks) {
577   
578   // To determine liveness, we must iterate through the predecessors of blocks
579   // where the def is live.  Blocks are added to the worklist if we need to
580   // check their predecessors.  Start with all the using blocks.
581   SmallVector<BasicBlock*, 64> LiveInBlockWorklist;
582   LiveInBlockWorklist.insert(LiveInBlockWorklist.end(), 
583                              Info.UsingBlocks.begin(), Info.UsingBlocks.end());
584   
585   // If any of the using blocks is also a definition block, check to see if the
586   // definition occurs before or after the use.  If it happens before the use,
587   // the value isn't really live-in.
588   for (unsigned i = 0, e = LiveInBlockWorklist.size(); i != e; ++i) {
589     BasicBlock *BB = LiveInBlockWorklist[i];
590     if (!DefBlocks.count(BB)) continue;
591     
592     // Okay, this is a block that both uses and defines the value.  If the first
593     // reference to the alloca is a def (store), then we know it isn't live-in.
594     for (BasicBlock::iterator I = BB->begin(); ; ++I) {
595       if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
596         if (SI->getOperand(1) != AI) continue;
597         
598         // We found a store to the alloca before a load.  The alloca is not
599         // actually live-in here.
600         LiveInBlockWorklist[i] = LiveInBlockWorklist.back();
601         LiveInBlockWorklist.pop_back();
602         --i, --e;
603         break;
604       } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
605         if (LI->getOperand(0) != AI) continue;
606         
607         // Okay, we found a load before a store to the alloca.  It is actually
608         // live into this block.
609         break;
610       }
611     }
612   }
613   
614   // Now that we have a set of blocks where the phi is live-in, recursively add
615   // their predecessors until we find the full region the value is live.
616   while (!LiveInBlockWorklist.empty()) {
617     BasicBlock *BB = LiveInBlockWorklist.back();
618     LiveInBlockWorklist.pop_back();
619     
620     // The block really is live in here, insert it into the set.  If already in
621     // the set, then it has already been processed.
622     if (!LiveInBlocks.insert(BB))
623       continue;
624     
625     // Since the value is live into BB, it is either defined in a predecessor or
626     // live into it to.  Add the preds to the worklist unless they are a
627     // defining block.
628     for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
629       BasicBlock *P = *PI;
630       
631       // The value is not live into a predecessor if it defines the value.
632       if (DefBlocks.count(P))
633         continue;
634       
635       // Otherwise it is, add to the worklist.
636       LiveInBlockWorklist.push_back(P);
637     }
638   }
639 }
640
641 /// DetermineInsertionPoint - At this point, we're committed to promoting the
642 /// alloca using IDF's, and the standard SSA construction algorithm.  Determine
643 /// which blocks need phi nodes and see if we can optimize out some work by
644 /// avoiding insertion of dead phi nodes.
645 void PromoteMem2Reg::DetermineInsertionPoint(AllocaInst *AI, unsigned AllocaNum,
646                                              AllocaInfo &Info) {
647
648   // Unique the set of defining blocks for efficient lookup.
649   SmallPtrSet<BasicBlock*, 32> DefBlocks;
650   DefBlocks.insert(Info.DefiningBlocks.begin(), Info.DefiningBlocks.end());
651
652   // Determine which blocks the value is live in.  These are blocks which lead
653   // to uses.
654   SmallPtrSet<BasicBlock*, 32> LiveInBlocks;
655   ComputeLiveInBlocks(AI, Info, DefBlocks, LiveInBlocks);
656
657   // Compute the locations where PhiNodes need to be inserted.  Look at the
658   // dominance frontier of EACH basic-block we have a write in.
659   unsigned CurrentVersion = 0;
660   SmallPtrSet<PHINode*, 16> InsertedPHINodes;
661   std::vector<std::pair<unsigned, BasicBlock*> > DFBlocks;
662   while (!Info.DefiningBlocks.empty()) {
663     BasicBlock *BB = Info.DefiningBlocks.back();
664     Info.DefiningBlocks.pop_back();
665     
666     // Look up the DF for this write, add it to defining blocks.
667     DominanceFrontier::const_iterator it = DF.find(BB);
668     if (it == DF.end()) continue;
669     
670     const DominanceFrontier::DomSetType &S = it->second;
671     
672     // In theory we don't need the indirection through the DFBlocks vector.
673     // In practice, the order of calling QueuePhiNode would depend on the
674     // (unspecified) ordering of basic blocks in the dominance frontier,
675     // which would give PHI nodes non-determinstic subscripts.  Fix this by
676     // processing blocks in order of the occurance in the function.
677     for (DominanceFrontier::DomSetType::const_iterator P = S.begin(),
678          PE = S.end(); P != PE; ++P) {
679       // If the frontier block is not in the live-in set for the alloca, don't
680       // bother processing it.
681       if (!LiveInBlocks.count(*P))
682         continue;
683       
684       DFBlocks.push_back(std::make_pair(BBNumbers[*P], *P));
685     }
686     
687     // Sort by which the block ordering in the function.
688     if (DFBlocks.size() > 1)
689       std::sort(DFBlocks.begin(), DFBlocks.end());
690     
691     for (unsigned i = 0, e = DFBlocks.size(); i != e; ++i) {
692       BasicBlock *BB = DFBlocks[i].second;
693       if (QueuePhiNode(BB, AllocaNum, CurrentVersion, InsertedPHINodes))
694         Info.DefiningBlocks.push_back(BB);
695     }
696     DFBlocks.clear();
697   }
698 }
699
700 /// RewriteSingleStoreAlloca - If there is only a single store to this value,
701 /// replace any loads of it that are directly dominated by the definition with
702 /// the value stored.
703 void PromoteMem2Reg::RewriteSingleStoreAlloca(AllocaInst *AI,
704                                               AllocaInfo &Info,
705                                               LargeBlockInfo &LBI) {
706   StoreInst *OnlyStore = Info.OnlyStore;
707   bool StoringGlobalVal = !isa<Instruction>(OnlyStore->getOperand(0));
708   BasicBlock *StoreBB = OnlyStore->getParent();
709   int StoreIndex = -1;
710
711   // Clear out UsingBlocks.  We will reconstruct it here if needed.
712   Info.UsingBlocks.clear();
713   
714   for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end(); UI != E; ) {
715     Instruction *UserInst = cast<Instruction>(*UI++);
716     if (!isa<LoadInst>(UserInst)) {
717       assert(UserInst == OnlyStore && "Should only have load/stores");
718       continue;
719     }
720     LoadInst *LI = cast<LoadInst>(UserInst);
721     
722     // Okay, if we have a load from the alloca, we want to replace it with the
723     // only value stored to the alloca.  We can do this if the value is
724     // dominated by the store.  If not, we use the rest of the mem2reg machinery
725     // to insert the phi nodes as needed.
726     if (!StoringGlobalVal) {  // Non-instructions are always dominated.
727       if (LI->getParent() == StoreBB) {
728         // If we have a use that is in the same block as the store, compare the
729         // indices of the two instructions to see which one came first.  If the
730         // load came before the store, we can't handle it.
731         if (StoreIndex == -1)
732           StoreIndex = LBI.getInstructionIndex(OnlyStore);
733
734         if (unsigned(StoreIndex) > LBI.getInstructionIndex(LI)) {
735           // Can't handle this load, bail out.
736           Info.UsingBlocks.push_back(StoreBB);
737           continue;
738         }
739         
740       } else if (LI->getParent() != StoreBB &&
741                  !dominates(StoreBB, LI->getParent())) {
742         // If the load and store are in different blocks, use BB dominance to
743         // check their relationships.  If the store doesn't dom the use, bail
744         // out.
745         Info.UsingBlocks.push_back(LI->getParent());
746         continue;
747       }
748     }
749     
750     // Otherwise, we *can* safely rewrite this load.
751     LI->replaceAllUsesWith(OnlyStore->getOperand(0));
752     if (AST && isa<PointerType>(LI->getType()))
753       AST->deleteValue(LI);
754     LI->eraseFromParent();
755     LBI.deleteValue(LI);
756   }
757 }
758
759
760 /// StoreIndexSearchPredicate - This is a helper predicate used to search by the
761 /// first element of a pair.
762 struct StoreIndexSearchPredicate {
763   bool operator()(const std::pair<unsigned, StoreInst*> &LHS,
764                   const std::pair<unsigned, StoreInst*> &RHS) {
765     return LHS.first < RHS.first;
766   }
767 };
768
769 /// PromoteSingleBlockAlloca - Many allocas are only used within a single basic
770 /// block.  If this is the case, avoid traversing the CFG and inserting a lot of
771 /// potentially useless PHI nodes by just performing a single linear pass over
772 /// the basic block using the Alloca.
773 ///
774 /// If we cannot promote this alloca (because it is read before it is written),
775 /// return true.  This is necessary in cases where, due to control flow, the
776 /// alloca is potentially undefined on some control flow paths.  e.g. code like
777 /// this is potentially correct:
778 ///
779 ///   for (...) { if (c) { A = undef; undef = B; } }
780 ///
781 /// ... so long as A is not used before undef is set.
782 ///
783 void PromoteMem2Reg::PromoteSingleBlockAlloca(AllocaInst *AI, AllocaInfo &Info,
784                                               LargeBlockInfo &LBI) {
785   // The trickiest case to handle is when we have large blocks. Because of this,
786   // this code is optimized assuming that large blocks happen.  This does not
787   // significantly pessimize the small block case.  This uses LargeBlockInfo to
788   // make it efficient to get the index of various operations in the block.
789   
790   // Clear out UsingBlocks.  We will reconstruct it here if needed.
791   Info.UsingBlocks.clear();
792   
793   // Walk the use-def list of the alloca, getting the locations of all stores.
794   typedef SmallVector<std::pair<unsigned, StoreInst*>, 64> StoresByIndexTy;
795   StoresByIndexTy StoresByIndex;
796   
797   for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
798        UI != E; ++UI) 
799     if (StoreInst *SI = dyn_cast<StoreInst>(*UI))
800       StoresByIndex.push_back(std::make_pair(LBI.getInstructionIndex(SI), SI));
801
802   // If there are no stores to the alloca, just replace any loads with undef.
803   if (StoresByIndex.empty()) {
804     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end(); UI != E;) 
805       if (LoadInst *LI = dyn_cast<LoadInst>(*UI++)) {
806         LI->replaceAllUsesWith(UndefValue::get(LI->getType()));
807         if (AST && isa<PointerType>(LI->getType()))
808           AST->deleteValue(LI);
809         LBI.deleteValue(LI);
810         LI->eraseFromParent();
811       }
812     return;
813   }
814   
815   // Sort the stores by their index, making it efficient to do a lookup with a
816   // binary search.
817   std::sort(StoresByIndex.begin(), StoresByIndex.end());
818   
819   // Walk all of the loads from this alloca, replacing them with the nearest
820   // store above them, if any.
821   for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end(); UI != E;) {
822     LoadInst *LI = dyn_cast<LoadInst>(*UI++);
823     if (!LI) continue;
824     
825     unsigned LoadIdx = LBI.getInstructionIndex(LI);
826     
827     // Find the nearest store that has a lower than this load. 
828     StoresByIndexTy::iterator I = 
829       std::lower_bound(StoresByIndex.begin(), StoresByIndex.end(),
830                        std::pair<unsigned, StoreInst*>(LoadIdx, 0),
831                        StoreIndexSearchPredicate());
832     
833     // If there is no store before this load, then we can't promote this load.
834     if (I == StoresByIndex.begin()) {
835       // Can't handle this load, bail out.
836       Info.UsingBlocks.push_back(LI->getParent());
837       continue;
838     }
839       
840     // Otherwise, there was a store before this load, the load takes its value.
841     --I;
842     LI->replaceAllUsesWith(I->second->getOperand(0));
843     if (AST && isa<PointerType>(LI->getType()))
844       AST->deleteValue(LI);
845     LI->eraseFromParent();
846     LBI.deleteValue(LI);
847   }
848 }
849
850
851 // QueuePhiNode - queues a phi-node to be added to a basic-block for a specific
852 // Alloca returns true if there wasn't already a phi-node for that variable
853 //
854 bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo,
855                                   unsigned &Version,
856                                   SmallPtrSet<PHINode*, 16> &InsertedPHINodes) {
857   // Look up the basic-block in question.
858   PHINode *&PN = NewPhiNodes[std::make_pair(BB, AllocaNo)];
859
860   // If the BB already has a phi node added for the i'th alloca then we're done!
861   if (PN) return false;
862
863   // Create a PhiNode using the dereferenced type... and add the phi-node to the
864   // BasicBlock.
865   PN = PHINode::Create(Allocas[AllocaNo]->getAllocatedType(),
866                        Allocas[AllocaNo]->getName() + "." +
867                        utostr(Version++), BB->begin());
868   ++NumPHIInsert;
869   PhiToAllocaMap[PN] = AllocaNo;
870   PN->reserveOperandSpace(getNumPreds(BB));
871   
872   InsertedPHINodes.insert(PN);
873
874   if (AST && isa<PointerType>(PN->getType()))
875     AST->copyValue(PointerAllocaValues[AllocaNo], PN);
876
877   return true;
878 }
879
880 // RenamePass - Recursively traverse the CFG of the function, renaming loads and
881 // stores to the allocas which we are promoting.  IncomingVals indicates what
882 // value each Alloca contains on exit from the predecessor block Pred.
883 //
884 void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
885                                 RenamePassData::ValVector &IncomingVals,
886                                 std::vector<RenamePassData> &Worklist) {
887 NextIteration:
888   // If we are inserting any phi nodes into this BB, they will already be in the
889   // block.
890   if (PHINode *APN = dyn_cast<PHINode>(BB->begin())) {
891     // Pred may have multiple edges to BB.  If so, we want to add N incoming
892     // values to each PHI we are inserting on the first time we see the edge.
893     // Check to see if APN already has incoming values from Pred.  This also
894     // prevents us from modifying PHI nodes that are not currently being
895     // inserted.
896     bool HasPredEntries = false;
897     for (unsigned i = 0, e = APN->getNumIncomingValues(); i != e; ++i) {
898       if (APN->getIncomingBlock(i) == Pred) {
899         HasPredEntries = true;
900         break;
901       }
902     }
903     
904     // If we have PHI nodes to update, compute the number of edges from Pred to
905     // BB.
906     if (!HasPredEntries) {
907       // We want to be able to distinguish between PHI nodes being inserted by
908       // this invocation of mem2reg from those phi nodes that already existed in
909       // the IR before mem2reg was run.  We determine that APN is being inserted
910       // because it is missing incoming edges.  All other PHI nodes being
911       // inserted by this pass of mem2reg will have the same number of incoming
912       // operands so far.  Remember this count.
913       unsigned NewPHINumOperands = APN->getNumOperands();
914       
915       unsigned NumEdges = 0;
916       for (succ_iterator I = succ_begin(Pred), E = succ_end(Pred); I != E; ++I)
917         if (*I == BB)
918           ++NumEdges;
919       assert(NumEdges && "Must be at least one edge from Pred to BB!");
920       
921       // Add entries for all the phis.
922       BasicBlock::iterator PNI = BB->begin();
923       do {
924         unsigned AllocaNo = PhiToAllocaMap[APN];
925         
926         // Add N incoming values to the PHI node.
927         for (unsigned i = 0; i != NumEdges; ++i)
928           APN->addIncoming(IncomingVals[AllocaNo], Pred);
929         
930         // The currently active variable for this block is now the PHI.
931         IncomingVals[AllocaNo] = APN;
932         
933         // Get the next phi node.
934         ++PNI;
935         APN = dyn_cast<PHINode>(PNI);
936         if (APN == 0) break;
937         
938         // Verify that it is missing entries.  If not, it is not being inserted
939         // by this mem2reg invocation so we want to ignore it.
940       } while (APN->getNumOperands() == NewPHINumOperands);
941     }
942   }
943   
944   // Don't revisit blocks.
945   if (!Visited.insert(BB)) return;
946
947   for (BasicBlock::iterator II = BB->begin(); !isa<TerminatorInst>(II); ) {
948     Instruction *I = II++; // get the instruction, increment iterator
949
950     if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
951       AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand());
952       if (!Src) continue;
953   
954       std::map<AllocaInst*, unsigned>::iterator AI = AllocaLookup.find(Src);
955       if (AI == AllocaLookup.end()) continue;
956
957       Value *V = IncomingVals[AI->second];
958
959       // Anything using the load now uses the current value.
960       LI->replaceAllUsesWith(V);
961       if (AST && isa<PointerType>(LI->getType()))
962         AST->deleteValue(LI);
963       BB->getInstList().erase(LI);
964     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
965       // Delete this instruction and mark the name as the current holder of the
966       // value
967       AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand());
968       if (!Dest) continue;
969       
970       std::map<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest);
971       if (ai == AllocaLookup.end())
972         continue;
973       
974       // what value were we writing?
975       IncomingVals[ai->second] = SI->getOperand(0);
976       BB->getInstList().erase(SI);
977     }
978   }
979
980   // 'Recurse' to our successors.
981   succ_iterator I = succ_begin(BB), E = succ_end(BB);
982   if (I == E) return;
983
984   // Handle the last successor without using the worklist.  This allows us to
985   // handle unconditional branches directly, for example.
986   --E;
987   for (; I != E; ++I)
988     Worklist.push_back(RenamePassData(*I, BB, IncomingVals));
989
990   Pred = BB;
991   BB = *I;
992   goto NextIteration;
993 }
994
995 /// PromoteMemToReg - Promote the specified list of alloca instructions into
996 /// scalar registers, inserting PHI nodes as appropriate.  This function makes
997 /// use of DominanceFrontier information.  This function does not modify the CFG
998 /// of the function at all.  All allocas must be from the same function.
999 ///
1000 /// If AST is specified, the specified tracker is updated to reflect changes
1001 /// made to the IR.
1002 ///
1003 void llvm::PromoteMemToReg(const std::vector<AllocaInst*> &Allocas,
1004                            DominatorTree &DT, DominanceFrontier &DF,
1005                            AliasSetTracker *AST) {
1006   // If there is nothing to do, bail out...
1007   if (Allocas.empty()) return;
1008
1009   PromoteMem2Reg(Allocas, DT, DF, AST).run();
1010 }