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