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