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