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