LLVM API Documentation

PromoteMemoryToRegister.cpp
Go to the documentation of this file.
00001 //===- PromoteMemoryToRegister.cpp - Convert allocas to registers ---------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file promotes memory references to be register references.  It promotes
00011 // alloca instructions which only have loads and stores as uses.  An alloca is
00012 // transformed by using iterated dominator frontiers to place PHI nodes, then
00013 // traversing the function in depth-first order to rewrite loads and stores as
00014 // appropriate.
00015 //
00016 // The algorithm used here is based on:
00017 //
00018 //   Sreedhar and Gao. A linear time algorithm for placing phi-nodes.
00019 //   In Proceedings of the 22nd ACM SIGPLAN-SIGACT Symposium on Principles of
00020 //   Programming Languages
00021 //   POPL '95. ACM, New York, NY, 62-73.
00022 //
00023 // It has been modified to not explicitly use the DJ graph data structure and to
00024 // directly compute pruned SSA using per-variable liveness information.
00025 //
00026 //===----------------------------------------------------------------------===//
00027 
00028 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
00029 #include "llvm/ADT/ArrayRef.h"
00030 #include "llvm/ADT/DenseMap.h"
00031 #include "llvm/ADT/STLExtras.h"
00032 #include "llvm/ADT/SmallPtrSet.h"
00033 #include "llvm/ADT/SmallVector.h"
00034 #include "llvm/ADT/Statistic.h"
00035 #include "llvm/Analysis/AliasSetTracker.h"
00036 #include "llvm/Analysis/InstructionSimplify.h"
00037 #include "llvm/Analysis/ValueTracking.h"
00038 #include "llvm/IR/CFG.h"
00039 #include "llvm/IR/Constants.h"
00040 #include "llvm/IR/DIBuilder.h"
00041 #include "llvm/IR/DebugInfo.h"
00042 #include "llvm/IR/DerivedTypes.h"
00043 #include "llvm/IR/Dominators.h"
00044 #include "llvm/IR/Function.h"
00045 #include "llvm/IR/Instructions.h"
00046 #include "llvm/IR/IntrinsicInst.h"
00047 #include "llvm/IR/Metadata.h"
00048 #include "llvm/Transforms/Utils/Local.h"
00049 #include <algorithm>
00050 #include <queue>
00051 using namespace llvm;
00052 
00053 #define DEBUG_TYPE "mem2reg"
00054 
00055 STATISTIC(NumLocalPromoted, "Number of alloca's promoted within one block");
00056 STATISTIC(NumSingleStore,   "Number of alloca's promoted with a single store");
00057 STATISTIC(NumDeadAlloca,    "Number of dead alloca's removed");
00058 STATISTIC(NumPHIInsert,     "Number of PHI nodes inserted");
00059 
00060 bool llvm::isAllocaPromotable(const AllocaInst *AI) {
00061   // FIXME: If the memory unit is of pointer or integer type, we can permit
00062   // assignments to subsections of the memory unit.
00063   unsigned AS = AI->getType()->getAddressSpace();
00064 
00065   // Only allow direct and non-volatile loads and stores...
00066   for (const User *U : AI->users()) {
00067     if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
00068       // Note that atomic loads can be transformed; atomic semantics do
00069       // not have any meaning for a local alloca.
00070       if (LI->isVolatile())
00071         return false;
00072     } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
00073       if (SI->getOperand(0) == AI)
00074         return false; // Don't allow a store OF the AI, only INTO the AI.
00075       // Note that atomic stores can be transformed; atomic semantics do
00076       // not have any meaning for a local alloca.
00077       if (SI->isVolatile())
00078         return false;
00079     } else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
00080       if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
00081           II->getIntrinsicID() != Intrinsic::lifetime_end)
00082         return false;
00083     } else if (const BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
00084       if (BCI->getType() != Type::getInt8PtrTy(U->getContext(), AS))
00085         return false;
00086       if (!onlyUsedByLifetimeMarkers(BCI))
00087         return false;
00088     } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
00089       if (GEPI->getType() != Type::getInt8PtrTy(U->getContext(), AS))
00090         return false;
00091       if (!GEPI->hasAllZeroIndices())
00092         return false;
00093       if (!onlyUsedByLifetimeMarkers(GEPI))
00094         return false;
00095     } else {
00096       return false;
00097     }
00098   }
00099 
00100   return true;
00101 }
00102 
00103 namespace {
00104 
00105 struct AllocaInfo {
00106   SmallVector<BasicBlock *, 32> DefiningBlocks;
00107   SmallVector<BasicBlock *, 32> UsingBlocks;
00108 
00109   StoreInst *OnlyStore;
00110   BasicBlock *OnlyBlock;
00111   bool OnlyUsedInOneBlock;
00112 
00113   Value *AllocaPointerVal;
00114   DbgDeclareInst *DbgDeclare;
00115 
00116   void clear() {
00117     DefiningBlocks.clear();
00118     UsingBlocks.clear();
00119     OnlyStore = nullptr;
00120     OnlyBlock = nullptr;
00121     OnlyUsedInOneBlock = true;
00122     AllocaPointerVal = nullptr;
00123     DbgDeclare = nullptr;
00124   }
00125 
00126   /// Scan the uses of the specified alloca, filling in the AllocaInfo used
00127   /// by the rest of the pass to reason about the uses of this alloca.
00128   void AnalyzeAlloca(AllocaInst *AI) {
00129     clear();
00130 
00131     // As we scan the uses of the alloca instruction, keep track of stores,
00132     // and decide whether all of the loads and stores to the alloca are within
00133     // the same basic block.
00134     for (auto UI = AI->user_begin(), E = AI->user_end(); UI != E;) {
00135       Instruction *User = cast<Instruction>(*UI++);
00136 
00137       if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
00138         // Remember the basic blocks which define new values for the alloca
00139         DefiningBlocks.push_back(SI->getParent());
00140         AllocaPointerVal = SI->getOperand(0);
00141         OnlyStore = SI;
00142       } else {
00143         LoadInst *LI = cast<LoadInst>(User);
00144         // Otherwise it must be a load instruction, keep track of variable
00145         // reads.
00146         UsingBlocks.push_back(LI->getParent());
00147         AllocaPointerVal = LI;
00148       }
00149 
00150       if (OnlyUsedInOneBlock) {
00151         if (!OnlyBlock)
00152           OnlyBlock = User->getParent();
00153         else if (OnlyBlock != User->getParent())
00154           OnlyUsedInOneBlock = false;
00155       }
00156     }
00157 
00158     DbgDeclare = FindAllocaDbgDeclare(AI);
00159   }
00160 };
00161 
00162 // Data package used by RenamePass()
00163 class RenamePassData {
00164 public:
00165   typedef std::vector<Value *> ValVector;
00166 
00167   RenamePassData() : BB(nullptr), Pred(nullptr), Values() {}
00168   RenamePassData(BasicBlock *B, BasicBlock *P, const ValVector &V)
00169       : BB(B), Pred(P), Values(V) {}
00170   BasicBlock *BB;
00171   BasicBlock *Pred;
00172   ValVector Values;
00173 
00174   void swap(RenamePassData &RHS) {
00175     std::swap(BB, RHS.BB);
00176     std::swap(Pred, RHS.Pred);
00177     Values.swap(RHS.Values);
00178   }
00179 };
00180 
00181 /// \brief This assigns and keeps a per-bb relative ordering of load/store
00182 /// instructions in the block that directly load or store an alloca.
00183 ///
00184 /// This functionality is important because it avoids scanning large basic
00185 /// blocks multiple times when promoting many allocas in the same block.
00186 class LargeBlockInfo {
00187   /// \brief For each instruction that we track, keep the index of the
00188   /// instruction.
00189   ///
00190   /// The index starts out as the number of the instruction from the start of
00191   /// the block.
00192   DenseMap<const Instruction *, unsigned> InstNumbers;
00193 
00194 public:
00195 
00196   /// This code only looks at accesses to allocas.
00197   static bool isInterestingInstruction(const Instruction *I) {
00198     return (isa<LoadInst>(I) && isa<AllocaInst>(I->getOperand(0))) ||
00199            (isa<StoreInst>(I) && isa<AllocaInst>(I->getOperand(1)));
00200   }
00201 
00202   /// Get or calculate the index of the specified instruction.
00203   unsigned getInstructionIndex(const Instruction *I) {
00204     assert(isInterestingInstruction(I) &&
00205            "Not a load/store to/from an alloca?");
00206 
00207     // If we already have this instruction number, return it.
00208     DenseMap<const Instruction *, unsigned>::iterator It = InstNumbers.find(I);
00209     if (It != InstNumbers.end())
00210       return It->second;
00211 
00212     // Scan the whole block to get the instruction.  This accumulates
00213     // information for every interesting instruction in the block, in order to
00214     // avoid gratuitus rescans.
00215     const BasicBlock *BB = I->getParent();
00216     unsigned InstNo = 0;
00217     for (BasicBlock::const_iterator BBI = BB->begin(), E = BB->end(); BBI != E;
00218          ++BBI)
00219       if (isInterestingInstruction(BBI))
00220         InstNumbers[BBI] = InstNo++;
00221     It = InstNumbers.find(I);
00222 
00223     assert(It != InstNumbers.end() && "Didn't insert instruction?");
00224     return It->second;
00225   }
00226 
00227   void deleteValue(const Instruction *I) { InstNumbers.erase(I); }
00228 
00229   void clear() { InstNumbers.clear(); }
00230 };
00231 
00232 struct PromoteMem2Reg {
00233   /// The alloca instructions being promoted.
00234   std::vector<AllocaInst *> Allocas;
00235   DominatorTree &DT;
00236   DIBuilder DIB;
00237 
00238   /// An AliasSetTracker object to update.  If null, don't update it.
00239   AliasSetTracker *AST;
00240 
00241   /// Reverse mapping of Allocas.
00242   DenseMap<AllocaInst *, unsigned> AllocaLookup;
00243 
00244   /// \brief The PhiNodes we're adding.
00245   ///
00246   /// That map is used to simplify some Phi nodes as we iterate over it, so
00247   /// it should have deterministic iterators.  We could use a MapVector, but
00248   /// since we already maintain a map from BasicBlock* to a stable numbering
00249   /// (BBNumbers), the DenseMap is more efficient (also supports removal).
00250   DenseMap<std::pair<unsigned, unsigned>, PHINode *> NewPhiNodes;
00251 
00252   /// For each PHI node, keep track of which entry in Allocas it corresponds
00253   /// to.
00254   DenseMap<PHINode *, unsigned> PhiToAllocaMap;
00255 
00256   /// If we are updating an AliasSetTracker, then for each alloca that is of
00257   /// pointer type, we keep track of what to copyValue to the inserted PHI
00258   /// nodes here.
00259   std::vector<Value *> PointerAllocaValues;
00260 
00261   /// For each alloca, we keep track of the dbg.declare intrinsic that
00262   /// describes it, if any, so that we can convert it to a dbg.value
00263   /// intrinsic if the alloca gets promoted.
00264   SmallVector<DbgDeclareInst *, 8> AllocaDbgDeclares;
00265 
00266   /// The set of basic blocks the renamer has already visited.
00267   ///
00268   SmallPtrSet<BasicBlock *, 16> Visited;
00269 
00270   /// Contains a stable numbering of basic blocks to avoid non-determinstic
00271   /// behavior.
00272   DenseMap<BasicBlock *, unsigned> BBNumbers;
00273 
00274   /// Maps DomTreeNodes to their level in the dominator tree.
00275   DenseMap<DomTreeNode *, unsigned> DomLevels;
00276 
00277   /// Lazily compute the number of predecessors a block has.
00278   DenseMap<const BasicBlock *, unsigned> BBNumPreds;
00279 
00280 public:
00281   PromoteMem2Reg(ArrayRef<AllocaInst *> Allocas, DominatorTree &DT,
00282                  AliasSetTracker *AST)
00283       : Allocas(Allocas.begin(), Allocas.end()), DT(DT),
00284         DIB(*DT.getRoot()->getParent()->getParent()), AST(AST) {}
00285 
00286   void run();
00287 
00288 private:
00289   void RemoveFromAllocasList(unsigned &AllocaIdx) {
00290     Allocas[AllocaIdx] = Allocas.back();
00291     Allocas.pop_back();
00292     --AllocaIdx;
00293   }
00294 
00295   unsigned getNumPreds(const BasicBlock *BB) {
00296     unsigned &NP = BBNumPreds[BB];
00297     if (NP == 0)
00298       NP = std::distance(pred_begin(BB), pred_end(BB)) + 1;
00299     return NP - 1;
00300   }
00301 
00302   void DetermineInsertionPoint(AllocaInst *AI, unsigned AllocaNum,
00303                                AllocaInfo &Info);
00304   void ComputeLiveInBlocks(AllocaInst *AI, AllocaInfo &Info,
00305                            const SmallPtrSet<BasicBlock *, 32> &DefBlocks,
00306                            SmallPtrSet<BasicBlock *, 32> &LiveInBlocks);
00307   void RenamePass(BasicBlock *BB, BasicBlock *Pred,
00308                   RenamePassData::ValVector &IncVals,
00309                   std::vector<RenamePassData> &Worklist);
00310   bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx, unsigned &Version);
00311 };
00312 
00313 } // end of anonymous namespace
00314 
00315 static void removeLifetimeIntrinsicUsers(AllocaInst *AI) {
00316   // Knowing that this alloca is promotable, we know that it's safe to kill all
00317   // instructions except for load and store.
00318 
00319   for (auto UI = AI->user_begin(), UE = AI->user_end(); UI != UE;) {
00320     Instruction *I = cast<Instruction>(*UI);
00321     ++UI;
00322     if (isa<LoadInst>(I) || isa<StoreInst>(I))
00323       continue;
00324 
00325     if (!I->getType()->isVoidTy()) {
00326       // The only users of this bitcast/GEP instruction are lifetime intrinsics.
00327       // Follow the use/def chain to erase them now instead of leaving it for
00328       // dead code elimination later.
00329       for (auto UUI = I->user_begin(), UUE = I->user_end(); UUI != UUE;) {
00330         Instruction *Inst = cast<Instruction>(*UUI);
00331         ++UUI;
00332         Inst->eraseFromParent();
00333       }
00334     }
00335     I->eraseFromParent();
00336   }
00337 }
00338 
00339 /// \brief Rewrite as many loads as possible given a single store.
00340 ///
00341 /// When there is only a single store, we can use the domtree to trivially
00342 /// replace all of the dominated loads with the stored value. Do so, and return
00343 /// true if this has successfully promoted the alloca entirely. If this returns
00344 /// false there were some loads which were not dominated by the single store
00345 /// and thus must be phi-ed with undef. We fall back to the standard alloca
00346 /// promotion algorithm in that case.
00347 static bool rewriteSingleStoreAlloca(AllocaInst *AI, AllocaInfo &Info,
00348                                      LargeBlockInfo &LBI,
00349                                      DominatorTree &DT,
00350                                      AliasSetTracker *AST) {
00351   StoreInst *OnlyStore = Info.OnlyStore;
00352   bool StoringGlobalVal = !isa<Instruction>(OnlyStore->getOperand(0));
00353   BasicBlock *StoreBB = OnlyStore->getParent();
00354   int StoreIndex = -1;
00355 
00356   // Clear out UsingBlocks.  We will reconstruct it here if needed.
00357   Info.UsingBlocks.clear();
00358 
00359   for (auto UI = AI->user_begin(), E = AI->user_end(); UI != E;) {
00360     Instruction *UserInst = cast<Instruction>(*UI++);
00361     if (!isa<LoadInst>(UserInst)) {
00362       assert(UserInst == OnlyStore && "Should only have load/stores");
00363       continue;
00364     }
00365     LoadInst *LI = cast<LoadInst>(UserInst);
00366 
00367     // Okay, if we have a load from the alloca, we want to replace it with the
00368     // only value stored to the alloca.  We can do this if the value is
00369     // dominated by the store.  If not, we use the rest of the mem2reg machinery
00370     // to insert the phi nodes as needed.
00371     if (!StoringGlobalVal) { // Non-instructions are always dominated.
00372       if (LI->getParent() == StoreBB) {
00373         // If we have a use that is in the same block as the store, compare the
00374         // indices of the two instructions to see which one came first.  If the
00375         // load came before the store, we can't handle it.
00376         if (StoreIndex == -1)
00377           StoreIndex = LBI.getInstructionIndex(OnlyStore);
00378 
00379         if (unsigned(StoreIndex) > LBI.getInstructionIndex(LI)) {
00380           // Can't handle this load, bail out.
00381           Info.UsingBlocks.push_back(StoreBB);
00382           continue;
00383         }
00384 
00385       } else if (LI->getParent() != StoreBB &&
00386                  !DT.dominates(StoreBB, LI->getParent())) {
00387         // If the load and store are in different blocks, use BB dominance to
00388         // check their relationships.  If the store doesn't dom the use, bail
00389         // out.
00390         Info.UsingBlocks.push_back(LI->getParent());
00391         continue;
00392       }
00393     }
00394 
00395     // Otherwise, we *can* safely rewrite this load.
00396     Value *ReplVal = OnlyStore->getOperand(0);
00397     // If the replacement value is the load, this must occur in unreachable
00398     // code.
00399     if (ReplVal == LI)
00400       ReplVal = UndefValue::get(LI->getType());
00401     LI->replaceAllUsesWith(ReplVal);
00402     if (AST && LI->getType()->isPointerTy())
00403       AST->deleteValue(LI);
00404     LI->eraseFromParent();
00405     LBI.deleteValue(LI);
00406   }
00407 
00408   // Finally, after the scan, check to see if the store is all that is left.
00409   if (!Info.UsingBlocks.empty())
00410     return false; // If not, we'll have to fall back for the remainder.
00411 
00412   // Record debuginfo for the store and remove the declaration's
00413   // debuginfo.
00414   if (DbgDeclareInst *DDI = Info.DbgDeclare) {
00415     DIBuilder DIB(*AI->getParent()->getParent()->getParent());
00416     ConvertDebugDeclareToDebugValue(DDI, Info.OnlyStore, DIB);
00417     DDI->eraseFromParent();
00418     LBI.deleteValue(DDI);
00419   }
00420   // Remove the (now dead) store and alloca.
00421   Info.OnlyStore->eraseFromParent();
00422   LBI.deleteValue(Info.OnlyStore);
00423 
00424   if (AST)
00425     AST->deleteValue(AI);
00426   AI->eraseFromParent();
00427   LBI.deleteValue(AI);
00428   return true;
00429 }
00430 
00431 /// Many allocas are only used within a single basic block.  If this is the
00432 /// case, avoid traversing the CFG and inserting a lot of potentially useless
00433 /// PHI nodes by just performing a single linear pass over the basic block
00434 /// using the Alloca.
00435 ///
00436 /// If we cannot promote this alloca (because it is read before it is written),
00437 /// return true.  This is necessary in cases where, due to control flow, the
00438 /// alloca is potentially undefined on some control flow paths.  e.g. code like
00439 /// this is potentially correct:
00440 ///
00441 ///   for (...) { if (c) { A = undef; undef = B; } }
00442 ///
00443 /// ... so long as A is not used before undef is set.
00444 static void promoteSingleBlockAlloca(AllocaInst *AI, const AllocaInfo &Info,
00445                                      LargeBlockInfo &LBI,
00446                                      AliasSetTracker *AST) {
00447   // The trickiest case to handle is when we have large blocks. Because of this,
00448   // this code is optimized assuming that large blocks happen.  This does not
00449   // significantly pessimize the small block case.  This uses LargeBlockInfo to
00450   // make it efficient to get the index of various operations in the block.
00451 
00452   // Walk the use-def list of the alloca, getting the locations of all stores.
00453   typedef SmallVector<std::pair<unsigned, StoreInst *>, 64> StoresByIndexTy;
00454   StoresByIndexTy StoresByIndex;
00455 
00456   for (User *U : AI->users())
00457     if (StoreInst *SI = dyn_cast<StoreInst>(U))
00458       StoresByIndex.push_back(std::make_pair(LBI.getInstructionIndex(SI), SI));
00459 
00460   // Sort the stores by their index, making it efficient to do a lookup with a
00461   // binary search.
00462   std::sort(StoresByIndex.begin(), StoresByIndex.end(), less_first());
00463 
00464   // Walk all of the loads from this alloca, replacing them with the nearest
00465   // store above them, if any.
00466   for (auto UI = AI->user_begin(), E = AI->user_end(); UI != E;) {
00467     LoadInst *LI = dyn_cast<LoadInst>(*UI++);
00468     if (!LI)
00469       continue;
00470 
00471     unsigned LoadIdx = LBI.getInstructionIndex(LI);
00472 
00473     // Find the nearest store that has a lower index than this load.
00474     StoresByIndexTy::iterator I =
00475         std::lower_bound(StoresByIndex.begin(), StoresByIndex.end(),
00476                          std::make_pair(LoadIdx,
00477                                         static_cast<StoreInst *>(nullptr)),
00478                          less_first());
00479 
00480     if (I == StoresByIndex.begin())
00481       // If there is no store before this load, the load takes the undef value.
00482       LI->replaceAllUsesWith(UndefValue::get(LI->getType()));
00483     else
00484       // Otherwise, there was a store before this load, the load takes its value.
00485       LI->replaceAllUsesWith(std::prev(I)->second->getOperand(0));
00486 
00487     if (AST && LI->getType()->isPointerTy())
00488       AST->deleteValue(LI);
00489     LI->eraseFromParent();
00490     LBI.deleteValue(LI);
00491   }
00492 
00493   // Remove the (now dead) stores and alloca.
00494   while (!AI->use_empty()) {
00495     StoreInst *SI = cast<StoreInst>(AI->user_back());
00496     // Record debuginfo for the store before removing it.
00497     if (DbgDeclareInst *DDI = Info.DbgDeclare) {
00498       DIBuilder DIB(*AI->getParent()->getParent()->getParent());
00499       ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
00500     }
00501     SI->eraseFromParent();
00502     LBI.deleteValue(SI);
00503   }
00504 
00505   if (AST)
00506     AST->deleteValue(AI);
00507   AI->eraseFromParent();
00508   LBI.deleteValue(AI);
00509 
00510   // The alloca's debuginfo can be removed as well.
00511   if (DbgDeclareInst *DDI = Info.DbgDeclare) {
00512     DDI->eraseFromParent();
00513     LBI.deleteValue(DDI);
00514   }
00515 
00516   ++NumLocalPromoted;
00517 }
00518 
00519 void PromoteMem2Reg::run() {
00520   Function &F = *DT.getRoot()->getParent();
00521 
00522   if (AST)
00523     PointerAllocaValues.resize(Allocas.size());
00524   AllocaDbgDeclares.resize(Allocas.size());
00525 
00526   AllocaInfo Info;
00527   LargeBlockInfo LBI;
00528 
00529   for (unsigned AllocaNum = 0; AllocaNum != Allocas.size(); ++AllocaNum) {
00530     AllocaInst *AI = Allocas[AllocaNum];
00531 
00532     assert(isAllocaPromotable(AI) && "Cannot promote non-promotable alloca!");
00533     assert(AI->getParent()->getParent() == &F &&
00534            "All allocas should be in the same function, which is same as DF!");
00535 
00536     removeLifetimeIntrinsicUsers(AI);
00537 
00538     if (AI->use_empty()) {
00539       // If there are no uses of the alloca, just delete it now.
00540       if (AST)
00541         AST->deleteValue(AI);
00542       AI->eraseFromParent();
00543 
00544       // Remove the alloca from the Allocas list, since it has been processed
00545       RemoveFromAllocasList(AllocaNum);
00546       ++NumDeadAlloca;
00547       continue;
00548     }
00549 
00550     // Calculate the set of read and write-locations for each alloca.  This is
00551     // analogous to finding the 'uses' and 'definitions' of each variable.
00552     Info.AnalyzeAlloca(AI);
00553 
00554     // If there is only a single store to this value, replace any loads of
00555     // it that are directly dominated by the definition with the value stored.
00556     if (Info.DefiningBlocks.size() == 1) {
00557       if (rewriteSingleStoreAlloca(AI, Info, LBI, DT, AST)) {
00558         // The alloca has been processed, move on.
00559         RemoveFromAllocasList(AllocaNum);
00560         ++NumSingleStore;
00561         continue;
00562       }
00563     }
00564 
00565     // If the alloca is only read and written in one basic block, just perform a
00566     // linear sweep over the block to eliminate it.
00567     if (Info.OnlyUsedInOneBlock) {
00568       promoteSingleBlockAlloca(AI, Info, LBI, AST);
00569 
00570       // The alloca has been processed, move on.
00571       RemoveFromAllocasList(AllocaNum);
00572       continue;
00573     }
00574 
00575     // If we haven't computed dominator tree levels, do so now.
00576     if (DomLevels.empty()) {
00577       SmallVector<DomTreeNode *, 32> Worklist;
00578 
00579       DomTreeNode *Root = DT.getRootNode();
00580       DomLevels[Root] = 0;
00581       Worklist.push_back(Root);
00582 
00583       while (!Worklist.empty()) {
00584         DomTreeNode *Node = Worklist.pop_back_val();
00585         unsigned ChildLevel = DomLevels[Node] + 1;
00586         for (DomTreeNode::iterator CI = Node->begin(), CE = Node->end();
00587              CI != CE; ++CI) {
00588           DomLevels[*CI] = ChildLevel;
00589           Worklist.push_back(*CI);
00590         }
00591       }
00592     }
00593 
00594     // If we haven't computed a numbering for the BB's in the function, do so
00595     // now.
00596     if (BBNumbers.empty()) {
00597       unsigned ID = 0;
00598       for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
00599         BBNumbers[I] = ID++;
00600     }
00601 
00602     // If we have an AST to keep updated, remember some pointer value that is
00603     // stored into the alloca.
00604     if (AST)
00605       PointerAllocaValues[AllocaNum] = Info.AllocaPointerVal;
00606 
00607     // Remember the dbg.declare intrinsic describing this alloca, if any.
00608     if (Info.DbgDeclare)
00609       AllocaDbgDeclares[AllocaNum] = Info.DbgDeclare;
00610 
00611     // Keep the reverse mapping of the 'Allocas' array for the rename pass.
00612     AllocaLookup[Allocas[AllocaNum]] = AllocaNum;
00613 
00614     // At this point, we're committed to promoting the alloca using IDF's, and
00615     // the standard SSA construction algorithm.  Determine which blocks need PHI
00616     // nodes and see if we can optimize out some work by avoiding insertion of
00617     // dead phi nodes.
00618     DetermineInsertionPoint(AI, AllocaNum, Info);
00619   }
00620 
00621   if (Allocas.empty())
00622     return; // All of the allocas must have been trivial!
00623 
00624   LBI.clear();
00625 
00626   // Set the incoming values for the basic block to be null values for all of
00627   // the alloca's.  We do this in case there is a load of a value that has not
00628   // been stored yet.  In this case, it will get this null value.
00629   //
00630   RenamePassData::ValVector Values(Allocas.size());
00631   for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
00632     Values[i] = UndefValue::get(Allocas[i]->getAllocatedType());
00633 
00634   // Walks all basic blocks in the function performing the SSA rename algorithm
00635   // and inserting the phi nodes we marked as necessary
00636   //
00637   std::vector<RenamePassData> RenamePassWorkList;
00638   RenamePassWorkList.push_back(RenamePassData(F.begin(), nullptr, Values));
00639   do {
00640     RenamePassData RPD;
00641     RPD.swap(RenamePassWorkList.back());
00642     RenamePassWorkList.pop_back();
00643     // RenamePass may add new worklist entries.
00644     RenamePass(RPD.BB, RPD.Pred, RPD.Values, RenamePassWorkList);
00645   } while (!RenamePassWorkList.empty());
00646 
00647   // The renamer uses the Visited set to avoid infinite loops.  Clear it now.
00648   Visited.clear();
00649 
00650   // Remove the allocas themselves from the function.
00651   for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
00652     Instruction *A = Allocas[i];
00653 
00654     // If there are any uses of the alloca instructions left, they must be in
00655     // unreachable basic blocks that were not processed by walking the dominator
00656     // tree. Just delete the users now.
00657     if (!A->use_empty())
00658       A->replaceAllUsesWith(UndefValue::get(A->getType()));
00659     if (AST)
00660       AST->deleteValue(A);
00661     A->eraseFromParent();
00662   }
00663 
00664   // Remove alloca's dbg.declare instrinsics from the function.
00665   for (unsigned i = 0, e = AllocaDbgDeclares.size(); i != e; ++i)
00666     if (DbgDeclareInst *DDI = AllocaDbgDeclares[i])
00667       DDI->eraseFromParent();
00668 
00669   // Loop over all of the PHI nodes and see if there are any that we can get
00670   // rid of because they merge all of the same incoming values.  This can
00671   // happen due to undef values coming into the PHI nodes.  This process is
00672   // iterative, because eliminating one PHI node can cause others to be removed.
00673   bool EliminatedAPHI = true;
00674   while (EliminatedAPHI) {
00675     EliminatedAPHI = false;
00676 
00677     // Iterating over NewPhiNodes is deterministic, so it is safe to try to
00678     // simplify and RAUW them as we go.  If it was not, we could add uses to
00679     // the values we replace with in a non-deterministic order, thus creating
00680     // non-deterministic def->use chains.
00681     for (DenseMap<std::pair<unsigned, unsigned>, PHINode *>::iterator
00682              I = NewPhiNodes.begin(),
00683              E = NewPhiNodes.end();
00684          I != E;) {
00685       PHINode *PN = I->second;
00686 
00687       // If this PHI node merges one value and/or undefs, get the value.
00688       if (Value *V = SimplifyInstruction(PN, nullptr, nullptr, &DT)) {
00689         if (AST && PN->getType()->isPointerTy())
00690           AST->deleteValue(PN);
00691         PN->replaceAllUsesWith(V);
00692         PN->eraseFromParent();
00693         NewPhiNodes.erase(I++);
00694         EliminatedAPHI = true;
00695         continue;
00696       }
00697       ++I;
00698     }
00699   }
00700 
00701   // At this point, the renamer has added entries to PHI nodes for all reachable
00702   // code.  Unfortunately, there may be unreachable blocks which the renamer
00703   // hasn't traversed.  If this is the case, the PHI nodes may not
00704   // have incoming values for all predecessors.  Loop over all PHI nodes we have
00705   // created, inserting undef values if they are missing any incoming values.
00706   //
00707   for (DenseMap<std::pair<unsigned, unsigned>, PHINode *>::iterator
00708            I = NewPhiNodes.begin(),
00709            E = NewPhiNodes.end();
00710        I != E; ++I) {
00711     // We want to do this once per basic block.  As such, only process a block
00712     // when we find the PHI that is the first entry in the block.
00713     PHINode *SomePHI = I->second;
00714     BasicBlock *BB = SomePHI->getParent();
00715     if (&BB->front() != SomePHI)
00716       continue;
00717 
00718     // Only do work here if there the PHI nodes are missing incoming values.  We
00719     // know that all PHI nodes that were inserted in a block will have the same
00720     // number of incoming values, so we can just check any of them.
00721     if (SomePHI->getNumIncomingValues() == getNumPreds(BB))
00722       continue;
00723 
00724     // Get the preds for BB.
00725     SmallVector<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB));
00726 
00727     // Ok, now we know that all of the PHI nodes are missing entries for some
00728     // basic blocks.  Start by sorting the incoming predecessors for efficient
00729     // access.
00730     std::sort(Preds.begin(), Preds.end());
00731 
00732     // Now we loop through all BB's which have entries in SomePHI and remove
00733     // them from the Preds list.
00734     for (unsigned i = 0, e = SomePHI->getNumIncomingValues(); i != e; ++i) {
00735       // Do a log(n) search of the Preds list for the entry we want.
00736       SmallVectorImpl<BasicBlock *>::iterator EntIt = std::lower_bound(
00737           Preds.begin(), Preds.end(), SomePHI->getIncomingBlock(i));
00738       assert(EntIt != Preds.end() && *EntIt == SomePHI->getIncomingBlock(i) &&
00739              "PHI node has entry for a block which is not a predecessor!");
00740 
00741       // Remove the entry
00742       Preds.erase(EntIt);
00743     }
00744 
00745     // At this point, the blocks left in the preds list must have dummy
00746     // entries inserted into every PHI nodes for the block.  Update all the phi
00747     // nodes in this block that we are inserting (there could be phis before
00748     // mem2reg runs).
00749     unsigned NumBadPreds = SomePHI->getNumIncomingValues();
00750     BasicBlock::iterator BBI = BB->begin();
00751     while ((SomePHI = dyn_cast<PHINode>(BBI++)) &&
00752            SomePHI->getNumIncomingValues() == NumBadPreds) {
00753       Value *UndefVal = UndefValue::get(SomePHI->getType());
00754       for (unsigned pred = 0, e = Preds.size(); pred != e; ++pred)
00755         SomePHI->addIncoming(UndefVal, Preds[pred]);
00756     }
00757   }
00758 
00759   NewPhiNodes.clear();
00760 }
00761 
00762 /// \brief Determine which blocks the value is live in.
00763 ///
00764 /// These are blocks which lead to uses.  Knowing this allows us to avoid
00765 /// inserting PHI nodes into blocks which don't lead to uses (thus, the
00766 /// inserted phi nodes would be dead).
00767 void PromoteMem2Reg::ComputeLiveInBlocks(
00768     AllocaInst *AI, AllocaInfo &Info,
00769     const SmallPtrSet<BasicBlock *, 32> &DefBlocks,
00770     SmallPtrSet<BasicBlock *, 32> &LiveInBlocks) {
00771 
00772   // To determine liveness, we must iterate through the predecessors of blocks
00773   // where the def is live.  Blocks are added to the worklist if we need to
00774   // check their predecessors.  Start with all the using blocks.
00775   SmallVector<BasicBlock *, 64> LiveInBlockWorklist(Info.UsingBlocks.begin(),
00776                                                     Info.UsingBlocks.end());
00777 
00778   // If any of the using blocks is also a definition block, check to see if the
00779   // definition occurs before or after the use.  If it happens before the use,
00780   // the value isn't really live-in.
00781   for (unsigned i = 0, e = LiveInBlockWorklist.size(); i != e; ++i) {
00782     BasicBlock *BB = LiveInBlockWorklist[i];
00783     if (!DefBlocks.count(BB))
00784       continue;
00785 
00786     // Okay, this is a block that both uses and defines the value.  If the first
00787     // reference to the alloca is a def (store), then we know it isn't live-in.
00788     for (BasicBlock::iterator I = BB->begin();; ++I) {
00789       if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
00790         if (SI->getOperand(1) != AI)
00791           continue;
00792 
00793         // We found a store to the alloca before a load.  The alloca is not
00794         // actually live-in here.
00795         LiveInBlockWorklist[i] = LiveInBlockWorklist.back();
00796         LiveInBlockWorklist.pop_back();
00797         --i, --e;
00798         break;
00799       }
00800 
00801       if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
00802         if (LI->getOperand(0) != AI)
00803           continue;
00804 
00805         // Okay, we found a load before a store to the alloca.  It is actually
00806         // live into this block.
00807         break;
00808       }
00809     }
00810   }
00811 
00812   // Now that we have a set of blocks where the phi is live-in, recursively add
00813   // their predecessors until we find the full region the value is live.
00814   while (!LiveInBlockWorklist.empty()) {
00815     BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
00816 
00817     // The block really is live in here, insert it into the set.  If already in
00818     // the set, then it has already been processed.
00819     if (!LiveInBlocks.insert(BB))
00820       continue;
00821 
00822     // Since the value is live into BB, it is either defined in a predecessor or
00823     // live into it to.  Add the preds to the worklist unless they are a
00824     // defining block.
00825     for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
00826       BasicBlock *P = *PI;
00827 
00828       // The value is not live into a predecessor if it defines the value.
00829       if (DefBlocks.count(P))
00830         continue;
00831 
00832       // Otherwise it is, add to the worklist.
00833       LiveInBlockWorklist.push_back(P);
00834     }
00835   }
00836 }
00837 
00838 /// At this point, we're committed to promoting the alloca using IDF's, and the
00839 /// standard SSA construction algorithm.  Determine which blocks need phi nodes
00840 /// and see if we can optimize out some work by avoiding insertion of dead phi
00841 /// nodes.
00842 void PromoteMem2Reg::DetermineInsertionPoint(AllocaInst *AI, unsigned AllocaNum,
00843                                              AllocaInfo &Info) {
00844   // Unique the set of defining blocks for efficient lookup.
00845   SmallPtrSet<BasicBlock *, 32> DefBlocks;
00846   DefBlocks.insert(Info.DefiningBlocks.begin(), Info.DefiningBlocks.end());
00847 
00848   // Determine which blocks the value is live in.  These are blocks which lead
00849   // to uses.
00850   SmallPtrSet<BasicBlock *, 32> LiveInBlocks;
00851   ComputeLiveInBlocks(AI, Info, DefBlocks, LiveInBlocks);
00852 
00853   // Use a priority queue keyed on dominator tree level so that inserted nodes
00854   // are handled from the bottom of the dominator tree upwards.
00855   typedef std::pair<DomTreeNode *, unsigned> DomTreeNodePair;
00856   typedef std::priority_queue<DomTreeNodePair, SmallVector<DomTreeNodePair, 32>,
00857                               less_second> IDFPriorityQueue;
00858   IDFPriorityQueue PQ;
00859 
00860   for (SmallPtrSet<BasicBlock *, 32>::const_iterator I = DefBlocks.begin(),
00861                                                      E = DefBlocks.end();
00862        I != E; ++I) {
00863     if (DomTreeNode *Node = DT.getNode(*I))
00864       PQ.push(std::make_pair(Node, DomLevels[Node]));
00865   }
00866 
00867   SmallVector<std::pair<unsigned, BasicBlock *>, 32> DFBlocks;
00868   SmallPtrSet<DomTreeNode *, 32> Visited;
00869   SmallVector<DomTreeNode *, 32> Worklist;
00870   while (!PQ.empty()) {
00871     DomTreeNodePair RootPair = PQ.top();
00872     PQ.pop();
00873     DomTreeNode *Root = RootPair.first;
00874     unsigned RootLevel = RootPair.second;
00875 
00876     // Walk all dominator tree children of Root, inspecting their CFG edges with
00877     // targets elsewhere on the dominator tree. Only targets whose level is at
00878     // most Root's level are added to the iterated dominance frontier of the
00879     // definition set.
00880 
00881     Worklist.clear();
00882     Worklist.push_back(Root);
00883 
00884     while (!Worklist.empty()) {
00885       DomTreeNode *Node = Worklist.pop_back_val();
00886       BasicBlock *BB = Node->getBlock();
00887 
00888       for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE;
00889            ++SI) {
00890         DomTreeNode *SuccNode = DT.getNode(*SI);
00891 
00892         // Quickly skip all CFG edges that are also dominator tree edges instead
00893         // of catching them below.
00894         if (SuccNode->getIDom() == Node)
00895           continue;
00896 
00897         unsigned SuccLevel = DomLevels[SuccNode];
00898         if (SuccLevel > RootLevel)
00899           continue;
00900 
00901         if (!Visited.insert(SuccNode))
00902           continue;
00903 
00904         BasicBlock *SuccBB = SuccNode->getBlock();
00905         if (!LiveInBlocks.count(SuccBB))
00906           continue;
00907 
00908         DFBlocks.push_back(std::make_pair(BBNumbers[SuccBB], SuccBB));
00909         if (!DefBlocks.count(SuccBB))
00910           PQ.push(std::make_pair(SuccNode, SuccLevel));
00911       }
00912 
00913       for (DomTreeNode::iterator CI = Node->begin(), CE = Node->end(); CI != CE;
00914            ++CI) {
00915         if (!Visited.count(*CI))
00916           Worklist.push_back(*CI);
00917       }
00918     }
00919   }
00920 
00921   if (DFBlocks.size() > 1)
00922     std::sort(DFBlocks.begin(), DFBlocks.end());
00923 
00924   unsigned CurrentVersion = 0;
00925   for (unsigned i = 0, e = DFBlocks.size(); i != e; ++i)
00926     QueuePhiNode(DFBlocks[i].second, AllocaNum, CurrentVersion);
00927 }
00928 
00929 /// \brief Queue a phi-node to be added to a basic-block for a specific Alloca.
00930 ///
00931 /// Returns true if there wasn't already a phi-node for that variable
00932 bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo,
00933                                   unsigned &Version) {
00934   // Look up the basic-block in question.
00935   PHINode *&PN = NewPhiNodes[std::make_pair(BBNumbers[BB], AllocaNo)];
00936 
00937   // If the BB already has a phi node added for the i'th alloca then we're done!
00938   if (PN)
00939     return false;
00940 
00941   // Create a PhiNode using the dereferenced type... and add the phi-node to the
00942   // BasicBlock.
00943   PN = PHINode::Create(Allocas[AllocaNo]->getAllocatedType(), getNumPreds(BB),
00944                        Allocas[AllocaNo]->getName() + "." + Twine(Version++),
00945                        BB->begin());
00946   ++NumPHIInsert;
00947   PhiToAllocaMap[PN] = AllocaNo;
00948 
00949   if (AST && PN->getType()->isPointerTy())
00950     AST->copyValue(PointerAllocaValues[AllocaNo], PN);
00951 
00952   return true;
00953 }
00954 
00955 /// \brief Recursively traverse the CFG of the function, renaming loads and
00956 /// stores to the allocas which we are promoting.
00957 ///
00958 /// IncomingVals indicates what value each Alloca contains on exit from the
00959 /// predecessor block Pred.
00960 void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
00961                                 RenamePassData::ValVector &IncomingVals,
00962                                 std::vector<RenamePassData> &Worklist) {
00963 NextIteration:
00964   // If we are inserting any phi nodes into this BB, they will already be in the
00965   // block.
00966   if (PHINode *APN = dyn_cast<PHINode>(BB->begin())) {
00967     // If we have PHI nodes to update, compute the number of edges from Pred to
00968     // BB.
00969     if (PhiToAllocaMap.count(APN)) {
00970       // We want to be able to distinguish between PHI nodes being inserted by
00971       // this invocation of mem2reg from those phi nodes that already existed in
00972       // the IR before mem2reg was run.  We determine that APN is being inserted
00973       // because it is missing incoming edges.  All other PHI nodes being
00974       // inserted by this pass of mem2reg will have the same number of incoming
00975       // operands so far.  Remember this count.
00976       unsigned NewPHINumOperands = APN->getNumOperands();
00977 
00978       unsigned NumEdges = std::count(succ_begin(Pred), succ_end(Pred), BB);
00979       assert(NumEdges && "Must be at least one edge from Pred to BB!");
00980 
00981       // Add entries for all the phis.
00982       BasicBlock::iterator PNI = BB->begin();
00983       do {
00984         unsigned AllocaNo = PhiToAllocaMap[APN];
00985 
00986         // Add N incoming values to the PHI node.
00987         for (unsigned i = 0; i != NumEdges; ++i)
00988           APN->addIncoming(IncomingVals[AllocaNo], Pred);
00989 
00990         // The currently active variable for this block is now the PHI.
00991         IncomingVals[AllocaNo] = APN;
00992 
00993         // Get the next phi node.
00994         ++PNI;
00995         APN = dyn_cast<PHINode>(PNI);
00996         if (!APN)
00997           break;
00998 
00999         // Verify that it is missing entries.  If not, it is not being inserted
01000         // by this mem2reg invocation so we want to ignore it.
01001       } while (APN->getNumOperands() == NewPHINumOperands);
01002     }
01003   }
01004 
01005   // Don't revisit blocks.
01006   if (!Visited.insert(BB))
01007     return;
01008 
01009   for (BasicBlock::iterator II = BB->begin(); !isa<TerminatorInst>(II);) {
01010     Instruction *I = II++; // get the instruction, increment iterator
01011 
01012     if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
01013       AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand());
01014       if (!Src)
01015         continue;
01016 
01017       DenseMap<AllocaInst *, unsigned>::iterator AI = AllocaLookup.find(Src);
01018       if (AI == AllocaLookup.end())
01019         continue;
01020 
01021       Value *V = IncomingVals[AI->second];
01022 
01023       // Anything using the load now uses the current value.
01024       LI->replaceAllUsesWith(V);
01025       if (AST && LI->getType()->isPointerTy())
01026         AST->deleteValue(LI);
01027       BB->getInstList().erase(LI);
01028     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
01029       // Delete this instruction and mark the name as the current holder of the
01030       // value
01031       AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand());
01032       if (!Dest)
01033         continue;
01034 
01035       DenseMap<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest);
01036       if (ai == AllocaLookup.end())
01037         continue;
01038 
01039       // what value were we writing?
01040       IncomingVals[ai->second] = SI->getOperand(0);
01041       // Record debuginfo for the store before removing it.
01042       if (DbgDeclareInst *DDI = AllocaDbgDeclares[ai->second])
01043         ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
01044       BB->getInstList().erase(SI);
01045     }
01046   }
01047 
01048   // 'Recurse' to our successors.
01049   succ_iterator I = succ_begin(BB), E = succ_end(BB);
01050   if (I == E)
01051     return;
01052 
01053   // Keep track of the successors so we don't visit the same successor twice
01054   SmallPtrSet<BasicBlock *, 8> VisitedSuccs;
01055 
01056   // Handle the first successor without using the worklist.
01057   VisitedSuccs.insert(*I);
01058   Pred = BB;
01059   BB = *I;
01060   ++I;
01061 
01062   for (; I != E; ++I)
01063     if (VisitedSuccs.insert(*I))
01064       Worklist.push_back(RenamePassData(*I, Pred, IncomingVals));
01065 
01066   goto NextIteration;
01067 }
01068 
01069 void llvm::PromoteMemToReg(ArrayRef<AllocaInst *> Allocas, DominatorTree &DT,
01070                            AliasSetTracker *AST) {
01071   // If there is nothing to do, bail out...
01072   if (Allocas.empty())
01073     return;
01074 
01075   PromoteMem2Reg(Allocas, DT, AST).run();
01076 }