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