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