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