10b57cec5SDimitry Andric //===- PromoteMemoryToRegister.cpp - Convert allocas to registers ---------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file promotes memory references to be register references.  It promotes
100b57cec5SDimitry Andric // alloca instructions which only have loads and stores as uses.  An alloca is
110b57cec5SDimitry Andric // transformed by using iterated dominator frontiers to place PHI nodes, then
120b57cec5SDimitry Andric // traversing the function in depth-first order to rewrite loads and stores as
130b57cec5SDimitry Andric // appropriate.
140b57cec5SDimitry Andric //
150b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
160b57cec5SDimitry Andric 
170b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
180b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
190b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
200b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
210b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
220b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
230b57cec5SDimitry Andric #include "llvm/ADT/TinyPtrVector.h"
240b57cec5SDimitry Andric #include "llvm/ADT/Twine.h"
250b57cec5SDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
260b57cec5SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h"
270b57cec5SDimitry Andric #include "llvm/Analysis/IteratedDominanceFrontier.h"
280b57cec5SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
290b57cec5SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
300b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
310b57cec5SDimitry Andric #include "llvm/IR/CFG.h"
320b57cec5SDimitry Andric #include "llvm/IR/Constant.h"
330b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
340b57cec5SDimitry Andric #include "llvm/IR/DIBuilder.h"
350b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
360b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
370b57cec5SDimitry Andric #include "llvm/IR/Function.h"
380b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
390b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
400b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
410b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
420b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
430b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
440b57cec5SDimitry Andric #include "llvm/IR/Module.h"
450b57cec5SDimitry Andric #include "llvm/IR/Type.h"
460b57cec5SDimitry Andric #include "llvm/IR/User.h"
470b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
480b57cec5SDimitry Andric #include "llvm/Transforms/Utils/PromoteMemToReg.h"
490b57cec5SDimitry Andric #include <algorithm>
500b57cec5SDimitry Andric #include <cassert>
510b57cec5SDimitry Andric #include <iterator>
520b57cec5SDimitry Andric #include <utility>
530b57cec5SDimitry Andric #include <vector>
540b57cec5SDimitry Andric 
550b57cec5SDimitry Andric using namespace llvm;
560b57cec5SDimitry Andric 
570b57cec5SDimitry Andric #define DEBUG_TYPE "mem2reg"
580b57cec5SDimitry Andric 
590b57cec5SDimitry Andric STATISTIC(NumLocalPromoted, "Number of alloca's promoted within one block");
600b57cec5SDimitry Andric STATISTIC(NumSingleStore,   "Number of alloca's promoted with a single store");
610b57cec5SDimitry Andric STATISTIC(NumDeadAlloca,    "Number of dead alloca's removed");
620b57cec5SDimitry Andric STATISTIC(NumPHIInsert,     "Number of PHI nodes inserted");
630b57cec5SDimitry Andric 
isAllocaPromotable(const AllocaInst * AI)640b57cec5SDimitry Andric bool llvm::isAllocaPromotable(const AllocaInst *AI) {
650b57cec5SDimitry Andric   // Only allow direct and non-volatile loads and stores...
660b57cec5SDimitry Andric   for (const User *U : AI->users()) {
670b57cec5SDimitry Andric     if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
680b57cec5SDimitry Andric       // Note that atomic loads can be transformed; atomic semantics do
690b57cec5SDimitry Andric       // not have any meaning for a local alloca.
700b57cec5SDimitry Andric       if (LI->isVolatile())
710b57cec5SDimitry Andric         return false;
720b57cec5SDimitry Andric     } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
730b57cec5SDimitry Andric       if (SI->getOperand(0) == AI)
740b57cec5SDimitry Andric         return false; // Don't allow a store OF the AI, only INTO the AI.
750b57cec5SDimitry Andric       // Note that atomic stores can be transformed; atomic semantics do
760b57cec5SDimitry Andric       // not have any meaning for a local alloca.
770b57cec5SDimitry Andric       if (SI->isVolatile())
780b57cec5SDimitry Andric         return false;
790b57cec5SDimitry Andric     } else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
80af732203SDimitry Andric       if (!II->isLifetimeStartOrEnd() && !II->isDroppable())
810b57cec5SDimitry Andric         return false;
820b57cec5SDimitry Andric     } else if (const BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
83af732203SDimitry Andric       if (!onlyUsedByLifetimeMarkersOrDroppableInsts(BCI))
840b57cec5SDimitry Andric         return false;
850b57cec5SDimitry Andric     } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
860b57cec5SDimitry Andric       if (!GEPI->hasAllZeroIndices())
870b57cec5SDimitry Andric         return false;
88af732203SDimitry Andric       if (!onlyUsedByLifetimeMarkersOrDroppableInsts(GEPI))
89af732203SDimitry Andric         return false;
90af732203SDimitry Andric     } else if (const AddrSpaceCastInst *ASCI = dyn_cast<AddrSpaceCastInst>(U)) {
91af732203SDimitry Andric       if (!onlyUsedByLifetimeMarkers(ASCI))
920b57cec5SDimitry Andric         return false;
930b57cec5SDimitry Andric     } else {
940b57cec5SDimitry Andric       return false;
950b57cec5SDimitry Andric     }
960b57cec5SDimitry Andric   }
970b57cec5SDimitry Andric 
980b57cec5SDimitry Andric   return true;
990b57cec5SDimitry Andric }
1000b57cec5SDimitry Andric 
1010b57cec5SDimitry Andric namespace {
1020b57cec5SDimitry Andric 
1030b57cec5SDimitry Andric struct AllocaInfo {
104af732203SDimitry Andric   using DbgUserVec = SmallVector<DbgVariableIntrinsic *, 1>;
105af732203SDimitry Andric 
1060b57cec5SDimitry Andric   SmallVector<BasicBlock *, 32> DefiningBlocks;
1070b57cec5SDimitry Andric   SmallVector<BasicBlock *, 32> UsingBlocks;
1080b57cec5SDimitry Andric 
1090b57cec5SDimitry Andric   StoreInst *OnlyStore;
1100b57cec5SDimitry Andric   BasicBlock *OnlyBlock;
1110b57cec5SDimitry Andric   bool OnlyUsedInOneBlock;
1120b57cec5SDimitry Andric 
113af732203SDimitry Andric   DbgUserVec DbgUsers;
1140b57cec5SDimitry Andric 
clear__anon7f69c9690111::AllocaInfo1150b57cec5SDimitry Andric   void clear() {
1160b57cec5SDimitry Andric     DefiningBlocks.clear();
1170b57cec5SDimitry Andric     UsingBlocks.clear();
1180b57cec5SDimitry Andric     OnlyStore = nullptr;
1190b57cec5SDimitry Andric     OnlyBlock = nullptr;
1200b57cec5SDimitry Andric     OnlyUsedInOneBlock = true;
121af732203SDimitry Andric     DbgUsers.clear();
1220b57cec5SDimitry Andric   }
1230b57cec5SDimitry Andric 
1240b57cec5SDimitry Andric   /// Scan the uses of the specified alloca, filling in the AllocaInfo used
1250b57cec5SDimitry Andric   /// by the rest of the pass to reason about the uses of this alloca.
AnalyzeAlloca__anon7f69c9690111::AllocaInfo1260b57cec5SDimitry Andric   void AnalyzeAlloca(AllocaInst *AI) {
1270b57cec5SDimitry Andric     clear();
1280b57cec5SDimitry Andric 
1290b57cec5SDimitry Andric     // As we scan the uses of the alloca instruction, keep track of stores,
1300b57cec5SDimitry Andric     // and decide whether all of the loads and stores to the alloca are within
1310b57cec5SDimitry Andric     // the same basic block.
132af732203SDimitry Andric     for (User *U : AI->users()) {
133af732203SDimitry Andric       Instruction *User = cast<Instruction>(U);
1340b57cec5SDimitry Andric 
1350b57cec5SDimitry Andric       if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1360b57cec5SDimitry Andric         // Remember the basic blocks which define new values for the alloca
1370b57cec5SDimitry Andric         DefiningBlocks.push_back(SI->getParent());
1380b57cec5SDimitry Andric         OnlyStore = SI;
1390b57cec5SDimitry Andric       } else {
1400b57cec5SDimitry Andric         LoadInst *LI = cast<LoadInst>(User);
1410b57cec5SDimitry Andric         // Otherwise it must be a load instruction, keep track of variable
1420b57cec5SDimitry Andric         // reads.
1430b57cec5SDimitry Andric         UsingBlocks.push_back(LI->getParent());
1440b57cec5SDimitry Andric       }
1450b57cec5SDimitry Andric 
1460b57cec5SDimitry Andric       if (OnlyUsedInOneBlock) {
1470b57cec5SDimitry Andric         if (!OnlyBlock)
1480b57cec5SDimitry Andric           OnlyBlock = User->getParent();
1490b57cec5SDimitry Andric         else if (OnlyBlock != User->getParent())
1500b57cec5SDimitry Andric           OnlyUsedInOneBlock = false;
1510b57cec5SDimitry Andric       }
1520b57cec5SDimitry Andric     }
1530b57cec5SDimitry Andric 
154af732203SDimitry Andric     findDbgUsers(DbgUsers, AI);
1550b57cec5SDimitry Andric   }
1560b57cec5SDimitry Andric };
1570b57cec5SDimitry Andric 
1580b57cec5SDimitry Andric /// Data package used by RenamePass().
1590b57cec5SDimitry Andric struct RenamePassData {
1600b57cec5SDimitry Andric   using ValVector = std::vector<Value *>;
1610b57cec5SDimitry Andric   using LocationVector = std::vector<DebugLoc>;
1620b57cec5SDimitry Andric 
RenamePassData__anon7f69c9690111::RenamePassData1630b57cec5SDimitry Andric   RenamePassData(BasicBlock *B, BasicBlock *P, ValVector V, LocationVector L)
1640b57cec5SDimitry Andric       : BB(B), Pred(P), Values(std::move(V)), Locations(std::move(L)) {}
1650b57cec5SDimitry Andric 
1660b57cec5SDimitry Andric   BasicBlock *BB;
1670b57cec5SDimitry Andric   BasicBlock *Pred;
1680b57cec5SDimitry Andric   ValVector Values;
1690b57cec5SDimitry Andric   LocationVector Locations;
1700b57cec5SDimitry Andric };
1710b57cec5SDimitry Andric 
1720b57cec5SDimitry Andric /// This assigns and keeps a per-bb relative ordering of load/store
1730b57cec5SDimitry Andric /// instructions in the block that directly load or store an alloca.
1740b57cec5SDimitry Andric ///
1750b57cec5SDimitry Andric /// This functionality is important because it avoids scanning large basic
1760b57cec5SDimitry Andric /// blocks multiple times when promoting many allocas in the same block.
1770b57cec5SDimitry Andric class LargeBlockInfo {
1780b57cec5SDimitry Andric   /// For each instruction that we track, keep the index of the
1790b57cec5SDimitry Andric   /// instruction.
1800b57cec5SDimitry Andric   ///
1810b57cec5SDimitry Andric   /// The index starts out as the number of the instruction from the start of
1820b57cec5SDimitry Andric   /// the block.
1830b57cec5SDimitry Andric   DenseMap<const Instruction *, unsigned> InstNumbers;
1840b57cec5SDimitry Andric 
1850b57cec5SDimitry Andric public:
1860b57cec5SDimitry Andric 
1870b57cec5SDimitry Andric   /// This code only looks at accesses to allocas.
isInterestingInstruction(const Instruction * I)1880b57cec5SDimitry Andric   static bool isInterestingInstruction(const Instruction *I) {
1890b57cec5SDimitry Andric     return (isa<LoadInst>(I) && isa<AllocaInst>(I->getOperand(0))) ||
1900b57cec5SDimitry Andric            (isa<StoreInst>(I) && isa<AllocaInst>(I->getOperand(1)));
1910b57cec5SDimitry Andric   }
1920b57cec5SDimitry Andric 
1930b57cec5SDimitry Andric   /// Get or calculate the index of the specified instruction.
getInstructionIndex(const Instruction * I)1940b57cec5SDimitry Andric   unsigned getInstructionIndex(const Instruction *I) {
1950b57cec5SDimitry Andric     assert(isInterestingInstruction(I) &&
1960b57cec5SDimitry Andric            "Not a load/store to/from an alloca?");
1970b57cec5SDimitry Andric 
1980b57cec5SDimitry Andric     // If we already have this instruction number, return it.
1990b57cec5SDimitry Andric     DenseMap<const Instruction *, unsigned>::iterator It = InstNumbers.find(I);
2000b57cec5SDimitry Andric     if (It != InstNumbers.end())
2010b57cec5SDimitry Andric       return It->second;
2020b57cec5SDimitry Andric 
2030b57cec5SDimitry Andric     // Scan the whole block to get the instruction.  This accumulates
2040b57cec5SDimitry Andric     // information for every interesting instruction in the block, in order to
2050b57cec5SDimitry Andric     // avoid gratuitus rescans.
2060b57cec5SDimitry Andric     const BasicBlock *BB = I->getParent();
2070b57cec5SDimitry Andric     unsigned InstNo = 0;
2080b57cec5SDimitry Andric     for (const Instruction &BBI : *BB)
2090b57cec5SDimitry Andric       if (isInterestingInstruction(&BBI))
2100b57cec5SDimitry Andric         InstNumbers[&BBI] = InstNo++;
2110b57cec5SDimitry Andric     It = InstNumbers.find(I);
2120b57cec5SDimitry Andric 
2130b57cec5SDimitry Andric     assert(It != InstNumbers.end() && "Didn't insert instruction?");
2140b57cec5SDimitry Andric     return It->second;
2150b57cec5SDimitry Andric   }
2160b57cec5SDimitry Andric 
deleteValue(const Instruction * I)2170b57cec5SDimitry Andric   void deleteValue(const Instruction *I) { InstNumbers.erase(I); }
2180b57cec5SDimitry Andric 
clear()2190b57cec5SDimitry Andric   void clear() { InstNumbers.clear(); }
2200b57cec5SDimitry Andric };
2210b57cec5SDimitry Andric 
2220b57cec5SDimitry Andric struct PromoteMem2Reg {
2230b57cec5SDimitry Andric   /// The alloca instructions being promoted.
2240b57cec5SDimitry Andric   std::vector<AllocaInst *> Allocas;
2250b57cec5SDimitry Andric 
2260b57cec5SDimitry Andric   DominatorTree &DT;
2270b57cec5SDimitry Andric   DIBuilder DIB;
2280b57cec5SDimitry Andric 
2290b57cec5SDimitry Andric   /// A cache of @llvm.assume intrinsics used by SimplifyInstruction.
2300b57cec5SDimitry Andric   AssumptionCache *AC;
2310b57cec5SDimitry Andric 
2320b57cec5SDimitry Andric   const SimplifyQuery SQ;
2330b57cec5SDimitry Andric 
2340b57cec5SDimitry Andric   /// Reverse mapping of Allocas.
2350b57cec5SDimitry Andric   DenseMap<AllocaInst *, unsigned> AllocaLookup;
2360b57cec5SDimitry Andric 
2370b57cec5SDimitry Andric   /// The PhiNodes we're adding.
2380b57cec5SDimitry Andric   ///
2390b57cec5SDimitry Andric   /// That map is used to simplify some Phi nodes as we iterate over it, so
2400b57cec5SDimitry Andric   /// it should have deterministic iterators.  We could use a MapVector, but
2410b57cec5SDimitry Andric   /// since we already maintain a map from BasicBlock* to a stable numbering
2420b57cec5SDimitry Andric   /// (BBNumbers), the DenseMap is more efficient (also supports removal).
2430b57cec5SDimitry Andric   DenseMap<std::pair<unsigned, unsigned>, PHINode *> NewPhiNodes;
2440b57cec5SDimitry Andric 
2450b57cec5SDimitry Andric   /// For each PHI node, keep track of which entry in Allocas it corresponds
2460b57cec5SDimitry Andric   /// to.
2470b57cec5SDimitry Andric   DenseMap<PHINode *, unsigned> PhiToAllocaMap;
2480b57cec5SDimitry Andric 
2490b57cec5SDimitry Andric   /// For each alloca, we keep track of the dbg.declare intrinsic that
2500b57cec5SDimitry Andric   /// describes it, if any, so that we can convert it to a dbg.value
2510b57cec5SDimitry Andric   /// intrinsic if the alloca gets promoted.
252af732203SDimitry Andric   SmallVector<AllocaInfo::DbgUserVec, 8> AllocaDbgUsers;
2530b57cec5SDimitry Andric 
2540b57cec5SDimitry Andric   /// The set of basic blocks the renamer has already visited.
2550b57cec5SDimitry Andric   SmallPtrSet<BasicBlock *, 16> Visited;
2560b57cec5SDimitry Andric 
2570b57cec5SDimitry Andric   /// Contains a stable numbering of basic blocks to avoid non-determinstic
2580b57cec5SDimitry Andric   /// behavior.
2590b57cec5SDimitry Andric   DenseMap<BasicBlock *, unsigned> BBNumbers;
2600b57cec5SDimitry Andric 
2610b57cec5SDimitry Andric   /// Lazily compute the number of predecessors a block has.
2620b57cec5SDimitry Andric   DenseMap<const BasicBlock *, unsigned> BBNumPreds;
2630b57cec5SDimitry Andric 
2640b57cec5SDimitry Andric public:
PromoteMem2Reg__anon7f69c9690111::PromoteMem2Reg2650b57cec5SDimitry Andric   PromoteMem2Reg(ArrayRef<AllocaInst *> Allocas, DominatorTree &DT,
2660b57cec5SDimitry Andric                  AssumptionCache *AC)
2670b57cec5SDimitry Andric       : Allocas(Allocas.begin(), Allocas.end()), DT(DT),
2680b57cec5SDimitry Andric         DIB(*DT.getRoot()->getParent()->getParent(), /*AllowUnresolved*/ false),
2690b57cec5SDimitry Andric         AC(AC), SQ(DT.getRoot()->getParent()->getParent()->getDataLayout(),
2700b57cec5SDimitry Andric                    nullptr, &DT, AC) {}
2710b57cec5SDimitry Andric 
2720b57cec5SDimitry Andric   void run();
2730b57cec5SDimitry Andric 
2740b57cec5SDimitry Andric private:
RemoveFromAllocasList__anon7f69c9690111::PromoteMem2Reg2750b57cec5SDimitry Andric   void RemoveFromAllocasList(unsigned &AllocaIdx) {
2760b57cec5SDimitry Andric     Allocas[AllocaIdx] = Allocas.back();
2770b57cec5SDimitry Andric     Allocas.pop_back();
2780b57cec5SDimitry Andric     --AllocaIdx;
2790b57cec5SDimitry Andric   }
2800b57cec5SDimitry Andric 
getNumPreds__anon7f69c9690111::PromoteMem2Reg2810b57cec5SDimitry Andric   unsigned getNumPreds(const BasicBlock *BB) {
2820b57cec5SDimitry Andric     unsigned &NP = BBNumPreds[BB];
2830b57cec5SDimitry Andric     if (NP == 0)
2840b57cec5SDimitry Andric       NP = pred_size(BB) + 1;
2850b57cec5SDimitry Andric     return NP - 1;
2860b57cec5SDimitry Andric   }
2870b57cec5SDimitry Andric 
2880b57cec5SDimitry Andric   void ComputeLiveInBlocks(AllocaInst *AI, AllocaInfo &Info,
2890b57cec5SDimitry Andric                            const SmallPtrSetImpl<BasicBlock *> &DefBlocks,
2900b57cec5SDimitry Andric                            SmallPtrSetImpl<BasicBlock *> &LiveInBlocks);
2910b57cec5SDimitry Andric   void RenamePass(BasicBlock *BB, BasicBlock *Pred,
2920b57cec5SDimitry Andric                   RenamePassData::ValVector &IncVals,
2930b57cec5SDimitry Andric                   RenamePassData::LocationVector &IncLocs,
2940b57cec5SDimitry Andric                   std::vector<RenamePassData> &Worklist);
2950b57cec5SDimitry Andric   bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx, unsigned &Version);
2960b57cec5SDimitry Andric };
2970b57cec5SDimitry Andric 
2980b57cec5SDimitry Andric } // end anonymous namespace
2990b57cec5SDimitry Andric 
3000b57cec5SDimitry Andric /// Given a LoadInst LI this adds assume(LI != null) after it.
addAssumeNonNull(AssumptionCache * AC,LoadInst * LI)3010b57cec5SDimitry Andric static void addAssumeNonNull(AssumptionCache *AC, LoadInst *LI) {
3020b57cec5SDimitry Andric   Function *AssumeIntrinsic =
3030b57cec5SDimitry Andric       Intrinsic::getDeclaration(LI->getModule(), Intrinsic::assume);
3040b57cec5SDimitry Andric   ICmpInst *LoadNotNull = new ICmpInst(ICmpInst::ICMP_NE, LI,
3050b57cec5SDimitry Andric                                        Constant::getNullValue(LI->getType()));
3060b57cec5SDimitry Andric   LoadNotNull->insertAfter(LI);
3070b57cec5SDimitry Andric   CallInst *CI = CallInst::Create(AssumeIntrinsic, {LoadNotNull});
3080b57cec5SDimitry Andric   CI->insertAfter(LoadNotNull);
309*5f7ddb14SDimitry Andric   AC->registerAssumption(cast<AssumeInst>(CI));
3100b57cec5SDimitry Andric }
3110b57cec5SDimitry Andric 
removeIntrinsicUsers(AllocaInst * AI)312af732203SDimitry Andric static void removeIntrinsicUsers(AllocaInst *AI) {
3130b57cec5SDimitry Andric   // Knowing that this alloca is promotable, we know that it's safe to kill all
3140b57cec5SDimitry Andric   // instructions except for load and store.
3150b57cec5SDimitry Andric 
316*5f7ddb14SDimitry Andric   for (Use &U : llvm::make_early_inc_range(AI->uses())) {
317*5f7ddb14SDimitry Andric     Instruction *I = cast<Instruction>(U.getUser());
3180b57cec5SDimitry Andric     if (isa<LoadInst>(I) || isa<StoreInst>(I))
3190b57cec5SDimitry Andric       continue;
3200b57cec5SDimitry Andric 
321af732203SDimitry Andric     // Drop the use of AI in droppable instructions.
322af732203SDimitry Andric     if (I->isDroppable()) {
323af732203SDimitry Andric       I->dropDroppableUse(U);
324af732203SDimitry Andric       continue;
325af732203SDimitry Andric     }
326af732203SDimitry Andric 
3270b57cec5SDimitry Andric     if (!I->getType()->isVoidTy()) {
3280b57cec5SDimitry Andric       // The only users of this bitcast/GEP instruction are lifetime intrinsics.
3290b57cec5SDimitry Andric       // Follow the use/def chain to erase them now instead of leaving it for
3300b57cec5SDimitry Andric       // dead code elimination later.
331*5f7ddb14SDimitry Andric       for (Use &UU : llvm::make_early_inc_range(I->uses())) {
332*5f7ddb14SDimitry Andric         Instruction *Inst = cast<Instruction>(UU.getUser());
333af732203SDimitry Andric 
334af732203SDimitry Andric         // Drop the use of I in droppable instructions.
335af732203SDimitry Andric         if (Inst->isDroppable()) {
336af732203SDimitry Andric           Inst->dropDroppableUse(UU);
337af732203SDimitry Andric           continue;
338af732203SDimitry Andric         }
3390b57cec5SDimitry Andric         Inst->eraseFromParent();
3400b57cec5SDimitry Andric       }
3410b57cec5SDimitry Andric     }
3420b57cec5SDimitry Andric     I->eraseFromParent();
3430b57cec5SDimitry Andric   }
3440b57cec5SDimitry Andric }
3450b57cec5SDimitry Andric 
3460b57cec5SDimitry Andric /// Rewrite as many loads as possible given a single store.
3470b57cec5SDimitry Andric ///
3480b57cec5SDimitry Andric /// When there is only a single store, we can use the domtree to trivially
3490b57cec5SDimitry Andric /// replace all of the dominated loads with the stored value. Do so, and return
3500b57cec5SDimitry Andric /// true if this has successfully promoted the alloca entirely. If this returns
3510b57cec5SDimitry Andric /// false there were some loads which were not dominated by the single store
3520b57cec5SDimitry Andric /// and thus must be phi-ed with undef. We fall back to the standard alloca
3530b57cec5SDimitry Andric /// promotion algorithm in that case.
rewriteSingleStoreAlloca(AllocaInst * AI,AllocaInfo & Info,LargeBlockInfo & LBI,const DataLayout & DL,DominatorTree & DT,AssumptionCache * AC)3540b57cec5SDimitry Andric static bool rewriteSingleStoreAlloca(AllocaInst *AI, AllocaInfo &Info,
3550b57cec5SDimitry Andric                                      LargeBlockInfo &LBI, const DataLayout &DL,
3560b57cec5SDimitry Andric                                      DominatorTree &DT, AssumptionCache *AC) {
3570b57cec5SDimitry Andric   StoreInst *OnlyStore = Info.OnlyStore;
3580b57cec5SDimitry Andric   bool StoringGlobalVal = !isa<Instruction>(OnlyStore->getOperand(0));
3590b57cec5SDimitry Andric   BasicBlock *StoreBB = OnlyStore->getParent();
3600b57cec5SDimitry Andric   int StoreIndex = -1;
3610b57cec5SDimitry Andric 
3620b57cec5SDimitry Andric   // Clear out UsingBlocks.  We will reconstruct it here if needed.
3630b57cec5SDimitry Andric   Info.UsingBlocks.clear();
3640b57cec5SDimitry Andric 
365af732203SDimitry Andric   for (User *U : make_early_inc_range(AI->users())) {
366af732203SDimitry Andric     Instruction *UserInst = cast<Instruction>(U);
3670b57cec5SDimitry Andric     if (UserInst == OnlyStore)
3680b57cec5SDimitry Andric       continue;
3690b57cec5SDimitry Andric     LoadInst *LI = cast<LoadInst>(UserInst);
3700b57cec5SDimitry Andric 
3710b57cec5SDimitry Andric     // Okay, if we have a load from the alloca, we want to replace it with the
3720b57cec5SDimitry Andric     // only value stored to the alloca.  We can do this if the value is
3730b57cec5SDimitry Andric     // dominated by the store.  If not, we use the rest of the mem2reg machinery
3740b57cec5SDimitry Andric     // to insert the phi nodes as needed.
3750b57cec5SDimitry Andric     if (!StoringGlobalVal) { // Non-instructions are always dominated.
3760b57cec5SDimitry Andric       if (LI->getParent() == StoreBB) {
3770b57cec5SDimitry Andric         // If we have a use that is in the same block as the store, compare the
3780b57cec5SDimitry Andric         // indices of the two instructions to see which one came first.  If the
3790b57cec5SDimitry Andric         // load came before the store, we can't handle it.
3800b57cec5SDimitry Andric         if (StoreIndex == -1)
3810b57cec5SDimitry Andric           StoreIndex = LBI.getInstructionIndex(OnlyStore);
3820b57cec5SDimitry Andric 
3830b57cec5SDimitry Andric         if (unsigned(StoreIndex) > LBI.getInstructionIndex(LI)) {
3840b57cec5SDimitry Andric           // Can't handle this load, bail out.
3850b57cec5SDimitry Andric           Info.UsingBlocks.push_back(StoreBB);
3860b57cec5SDimitry Andric           continue;
3870b57cec5SDimitry Andric         }
3880b57cec5SDimitry Andric       } else if (!DT.dominates(StoreBB, LI->getParent())) {
3890b57cec5SDimitry Andric         // If the load and store are in different blocks, use BB dominance to
3900b57cec5SDimitry Andric         // check their relationships.  If the store doesn't dom the use, bail
3910b57cec5SDimitry Andric         // out.
3920b57cec5SDimitry Andric         Info.UsingBlocks.push_back(LI->getParent());
3930b57cec5SDimitry Andric         continue;
3940b57cec5SDimitry Andric       }
3950b57cec5SDimitry Andric     }
3960b57cec5SDimitry Andric 
3970b57cec5SDimitry Andric     // Otherwise, we *can* safely rewrite this load.
3980b57cec5SDimitry Andric     Value *ReplVal = OnlyStore->getOperand(0);
3990b57cec5SDimitry Andric     // If the replacement value is the load, this must occur in unreachable
4000b57cec5SDimitry Andric     // code.
4010b57cec5SDimitry Andric     if (ReplVal == LI)
402*5f7ddb14SDimitry Andric       ReplVal = PoisonValue::get(LI->getType());
4030b57cec5SDimitry Andric 
4040b57cec5SDimitry Andric     // If the load was marked as nonnull we don't want to lose
4050b57cec5SDimitry Andric     // that information when we erase this Load. So we preserve
4060b57cec5SDimitry Andric     // it with an assume.
4070b57cec5SDimitry Andric     if (AC && LI->getMetadata(LLVMContext::MD_nonnull) &&
4080b57cec5SDimitry Andric         !isKnownNonZero(ReplVal, DL, 0, AC, LI, &DT))
4090b57cec5SDimitry Andric       addAssumeNonNull(AC, LI);
4100b57cec5SDimitry Andric 
4110b57cec5SDimitry Andric     LI->replaceAllUsesWith(ReplVal);
4120b57cec5SDimitry Andric     LI->eraseFromParent();
4130b57cec5SDimitry Andric     LBI.deleteValue(LI);
4140b57cec5SDimitry Andric   }
4150b57cec5SDimitry Andric 
4160b57cec5SDimitry Andric   // Finally, after the scan, check to see if the store is all that is left.
4170b57cec5SDimitry Andric   if (!Info.UsingBlocks.empty())
4180b57cec5SDimitry Andric     return false; // If not, we'll have to fall back for the remainder.
4190b57cec5SDimitry Andric 
4200b57cec5SDimitry Andric   // Record debuginfo for the store and remove the declaration's
4210b57cec5SDimitry Andric   // debuginfo.
422af732203SDimitry Andric   for (DbgVariableIntrinsic *DII : Info.DbgUsers) {
423af732203SDimitry Andric     if (DII->isAddressOfVariable()) {
4240b57cec5SDimitry Andric       DIBuilder DIB(*AI->getModule(), /*AllowUnresolved*/ false);
4250b57cec5SDimitry Andric       ConvertDebugDeclareToDebugValue(DII, Info.OnlyStore, DIB);
4260b57cec5SDimitry Andric       DII->eraseFromParent();
427af732203SDimitry Andric     } else if (DII->getExpression()->startsWithDeref()) {
428af732203SDimitry Andric       DII->eraseFromParent();
429af732203SDimitry Andric     }
4300b57cec5SDimitry Andric   }
4310b57cec5SDimitry Andric   // Remove the (now dead) store and alloca.
4320b57cec5SDimitry Andric   Info.OnlyStore->eraseFromParent();
4330b57cec5SDimitry Andric   LBI.deleteValue(Info.OnlyStore);
4340b57cec5SDimitry Andric 
4350b57cec5SDimitry Andric   AI->eraseFromParent();
4360b57cec5SDimitry Andric   return true;
4370b57cec5SDimitry Andric }
4380b57cec5SDimitry Andric 
4390b57cec5SDimitry Andric /// Many allocas are only used within a single basic block.  If this is the
4400b57cec5SDimitry Andric /// case, avoid traversing the CFG and inserting a lot of potentially useless
4410b57cec5SDimitry Andric /// PHI nodes by just performing a single linear pass over the basic block
4420b57cec5SDimitry Andric /// using the Alloca.
4430b57cec5SDimitry Andric ///
4440b57cec5SDimitry Andric /// If we cannot promote this alloca (because it is read before it is written),
4450b57cec5SDimitry Andric /// return false.  This is necessary in cases where, due to control flow, the
4460b57cec5SDimitry Andric /// alloca is undefined only on some control flow paths.  e.g. code like
4470b57cec5SDimitry Andric /// this is correct in LLVM IR:
4480b57cec5SDimitry Andric ///  // A is an alloca with no stores so far
4490b57cec5SDimitry Andric ///  for (...) {
4500b57cec5SDimitry Andric ///    int t = *A;
4510b57cec5SDimitry Andric ///    if (!first_iteration)
4520b57cec5SDimitry Andric ///      use(t);
4530b57cec5SDimitry Andric ///    *A = 42;
4540b57cec5SDimitry Andric ///  }
promoteSingleBlockAlloca(AllocaInst * AI,const AllocaInfo & Info,LargeBlockInfo & LBI,const DataLayout & DL,DominatorTree & DT,AssumptionCache * AC)4550b57cec5SDimitry Andric static bool promoteSingleBlockAlloca(AllocaInst *AI, const AllocaInfo &Info,
4560b57cec5SDimitry Andric                                      LargeBlockInfo &LBI,
4570b57cec5SDimitry Andric                                      const DataLayout &DL,
4580b57cec5SDimitry Andric                                      DominatorTree &DT,
4590b57cec5SDimitry Andric                                      AssumptionCache *AC) {
4600b57cec5SDimitry Andric   // The trickiest case to handle is when we have large blocks. Because of this,
4610b57cec5SDimitry Andric   // this code is optimized assuming that large blocks happen.  This does not
4620b57cec5SDimitry Andric   // significantly pessimize the small block case.  This uses LargeBlockInfo to
4630b57cec5SDimitry Andric   // make it efficient to get the index of various operations in the block.
4640b57cec5SDimitry Andric 
4650b57cec5SDimitry Andric   // Walk the use-def list of the alloca, getting the locations of all stores.
4660b57cec5SDimitry Andric   using StoresByIndexTy = SmallVector<std::pair<unsigned, StoreInst *>, 64>;
4670b57cec5SDimitry Andric   StoresByIndexTy StoresByIndex;
4680b57cec5SDimitry Andric 
4690b57cec5SDimitry Andric   for (User *U : AI->users())
4700b57cec5SDimitry Andric     if (StoreInst *SI = dyn_cast<StoreInst>(U))
4710b57cec5SDimitry Andric       StoresByIndex.push_back(std::make_pair(LBI.getInstructionIndex(SI), SI));
4720b57cec5SDimitry Andric 
4730b57cec5SDimitry Andric   // Sort the stores by their index, making it efficient to do a lookup with a
4740b57cec5SDimitry Andric   // binary search.
4750b57cec5SDimitry Andric   llvm::sort(StoresByIndex, less_first());
4760b57cec5SDimitry Andric 
4770b57cec5SDimitry Andric   // Walk all of the loads from this alloca, replacing them with the nearest
4780b57cec5SDimitry Andric   // store above them, if any.
479af732203SDimitry Andric   for (User *U : make_early_inc_range(AI->users())) {
480af732203SDimitry Andric     LoadInst *LI = dyn_cast<LoadInst>(U);
4810b57cec5SDimitry Andric     if (!LI)
4820b57cec5SDimitry Andric       continue;
4830b57cec5SDimitry Andric 
4840b57cec5SDimitry Andric     unsigned LoadIdx = LBI.getInstructionIndex(LI);
4850b57cec5SDimitry Andric 
4860b57cec5SDimitry Andric     // Find the nearest store that has a lower index than this load.
4870b57cec5SDimitry Andric     StoresByIndexTy::iterator I = llvm::lower_bound(
4880b57cec5SDimitry Andric         StoresByIndex,
4890b57cec5SDimitry Andric         std::make_pair(LoadIdx, static_cast<StoreInst *>(nullptr)),
4900b57cec5SDimitry Andric         less_first());
4910b57cec5SDimitry Andric     if (I == StoresByIndex.begin()) {
4920b57cec5SDimitry Andric       if (StoresByIndex.empty())
4930b57cec5SDimitry Andric         // If there are no stores, the load takes the undef value.
4940b57cec5SDimitry Andric         LI->replaceAllUsesWith(UndefValue::get(LI->getType()));
4950b57cec5SDimitry Andric       else
4960b57cec5SDimitry Andric         // There is no store before this load, bail out (load may be affected
4970b57cec5SDimitry Andric         // by the following stores - see main comment).
4980b57cec5SDimitry Andric         return false;
4990b57cec5SDimitry Andric     } else {
5000b57cec5SDimitry Andric       // Otherwise, there was a store before this load, the load takes its value.
5010b57cec5SDimitry Andric       // Note, if the load was marked as nonnull we don't want to lose that
5020b57cec5SDimitry Andric       // information when we erase it. So we preserve it with an assume.
5030b57cec5SDimitry Andric       Value *ReplVal = std::prev(I)->second->getOperand(0);
5040b57cec5SDimitry Andric       if (AC && LI->getMetadata(LLVMContext::MD_nonnull) &&
5050b57cec5SDimitry Andric           !isKnownNonZero(ReplVal, DL, 0, AC, LI, &DT))
5060b57cec5SDimitry Andric         addAssumeNonNull(AC, LI);
5070b57cec5SDimitry Andric 
5080b57cec5SDimitry Andric       // If the replacement value is the load, this must occur in unreachable
5090b57cec5SDimitry Andric       // code.
5100b57cec5SDimitry Andric       if (ReplVal == LI)
511*5f7ddb14SDimitry Andric         ReplVal = PoisonValue::get(LI->getType());
5120b57cec5SDimitry Andric 
5130b57cec5SDimitry Andric       LI->replaceAllUsesWith(ReplVal);
5140b57cec5SDimitry Andric     }
5150b57cec5SDimitry Andric 
5160b57cec5SDimitry Andric     LI->eraseFromParent();
5170b57cec5SDimitry Andric     LBI.deleteValue(LI);
5180b57cec5SDimitry Andric   }
5190b57cec5SDimitry Andric 
5200b57cec5SDimitry Andric   // Remove the (now dead) stores and alloca.
5210b57cec5SDimitry Andric   while (!AI->use_empty()) {
5220b57cec5SDimitry Andric     StoreInst *SI = cast<StoreInst>(AI->user_back());
5230b57cec5SDimitry Andric     // Record debuginfo for the store before removing it.
524af732203SDimitry Andric     for (DbgVariableIntrinsic *DII : Info.DbgUsers) {
525af732203SDimitry Andric       if (DII->isAddressOfVariable()) {
5260b57cec5SDimitry Andric         DIBuilder DIB(*AI->getModule(), /*AllowUnresolved*/ false);
5270b57cec5SDimitry Andric         ConvertDebugDeclareToDebugValue(DII, SI, DIB);
5280b57cec5SDimitry Andric       }
529af732203SDimitry Andric     }
5300b57cec5SDimitry Andric     SI->eraseFromParent();
5310b57cec5SDimitry Andric     LBI.deleteValue(SI);
5320b57cec5SDimitry Andric   }
5330b57cec5SDimitry Andric 
5340b57cec5SDimitry Andric   AI->eraseFromParent();
5350b57cec5SDimitry Andric 
5360b57cec5SDimitry Andric   // The alloca's debuginfo can be removed as well.
537af732203SDimitry Andric   for (DbgVariableIntrinsic *DII : Info.DbgUsers)
538af732203SDimitry Andric     if (DII->isAddressOfVariable() || DII->getExpression()->startsWithDeref())
5390b57cec5SDimitry Andric       DII->eraseFromParent();
5400b57cec5SDimitry Andric 
5410b57cec5SDimitry Andric   ++NumLocalPromoted;
5420b57cec5SDimitry Andric   return true;
5430b57cec5SDimitry Andric }
5440b57cec5SDimitry Andric 
run()5450b57cec5SDimitry Andric void PromoteMem2Reg::run() {
5460b57cec5SDimitry Andric   Function &F = *DT.getRoot()->getParent();
5470b57cec5SDimitry Andric 
548af732203SDimitry Andric   AllocaDbgUsers.resize(Allocas.size());
5490b57cec5SDimitry Andric 
5500b57cec5SDimitry Andric   AllocaInfo Info;
5510b57cec5SDimitry Andric   LargeBlockInfo LBI;
5520b57cec5SDimitry Andric   ForwardIDFCalculator IDF(DT);
5530b57cec5SDimitry Andric 
5540b57cec5SDimitry Andric   for (unsigned AllocaNum = 0; AllocaNum != Allocas.size(); ++AllocaNum) {
5550b57cec5SDimitry Andric     AllocaInst *AI = Allocas[AllocaNum];
5560b57cec5SDimitry Andric 
5570b57cec5SDimitry Andric     assert(isAllocaPromotable(AI) && "Cannot promote non-promotable alloca!");
5580b57cec5SDimitry Andric     assert(AI->getParent()->getParent() == &F &&
5590b57cec5SDimitry Andric            "All allocas should be in the same function, which is same as DF!");
5600b57cec5SDimitry Andric 
561af732203SDimitry Andric     removeIntrinsicUsers(AI);
5620b57cec5SDimitry Andric 
5630b57cec5SDimitry Andric     if (AI->use_empty()) {
5640b57cec5SDimitry Andric       // If there are no uses of the alloca, just delete it now.
5650b57cec5SDimitry Andric       AI->eraseFromParent();
5660b57cec5SDimitry Andric 
5670b57cec5SDimitry Andric       // Remove the alloca from the Allocas list, since it has been processed
5680b57cec5SDimitry Andric       RemoveFromAllocasList(AllocaNum);
5690b57cec5SDimitry Andric       ++NumDeadAlloca;
5700b57cec5SDimitry Andric       continue;
5710b57cec5SDimitry Andric     }
5720b57cec5SDimitry Andric 
5730b57cec5SDimitry Andric     // Calculate the set of read and write-locations for each alloca.  This is
5740b57cec5SDimitry Andric     // analogous to finding the 'uses' and 'definitions' of each variable.
5750b57cec5SDimitry Andric     Info.AnalyzeAlloca(AI);
5760b57cec5SDimitry Andric 
5770b57cec5SDimitry Andric     // If there is only a single store to this value, replace any loads of
5780b57cec5SDimitry Andric     // it that are directly dominated by the definition with the value stored.
5790b57cec5SDimitry Andric     if (Info.DefiningBlocks.size() == 1) {
5800b57cec5SDimitry Andric       if (rewriteSingleStoreAlloca(AI, Info, LBI, SQ.DL, DT, AC)) {
5810b57cec5SDimitry Andric         // The alloca has been processed, move on.
5820b57cec5SDimitry Andric         RemoveFromAllocasList(AllocaNum);
5830b57cec5SDimitry Andric         ++NumSingleStore;
5840b57cec5SDimitry Andric         continue;
5850b57cec5SDimitry Andric       }
5860b57cec5SDimitry Andric     }
5870b57cec5SDimitry Andric 
5880b57cec5SDimitry Andric     // If the alloca is only read and written in one basic block, just perform a
5890b57cec5SDimitry Andric     // linear sweep over the block to eliminate it.
5900b57cec5SDimitry Andric     if (Info.OnlyUsedInOneBlock &&
5910b57cec5SDimitry Andric         promoteSingleBlockAlloca(AI, Info, LBI, SQ.DL, DT, AC)) {
5920b57cec5SDimitry Andric       // The alloca has been processed, move on.
5930b57cec5SDimitry Andric       RemoveFromAllocasList(AllocaNum);
5940b57cec5SDimitry Andric       continue;
5950b57cec5SDimitry Andric     }
5960b57cec5SDimitry Andric 
5970b57cec5SDimitry Andric     // If we haven't computed a numbering for the BB's in the function, do so
5980b57cec5SDimitry Andric     // now.
5990b57cec5SDimitry Andric     if (BBNumbers.empty()) {
6000b57cec5SDimitry Andric       unsigned ID = 0;
6010b57cec5SDimitry Andric       for (auto &BB : F)
6020b57cec5SDimitry Andric         BBNumbers[&BB] = ID++;
6030b57cec5SDimitry Andric     }
6040b57cec5SDimitry Andric 
6050b57cec5SDimitry Andric     // Remember the dbg.declare intrinsic describing this alloca, if any.
606af732203SDimitry Andric     if (!Info.DbgUsers.empty())
607af732203SDimitry Andric       AllocaDbgUsers[AllocaNum] = Info.DbgUsers;
6080b57cec5SDimitry Andric 
6090b57cec5SDimitry Andric     // Keep the reverse mapping of the 'Allocas' array for the rename pass.
6100b57cec5SDimitry Andric     AllocaLookup[Allocas[AllocaNum]] = AllocaNum;
6110b57cec5SDimitry Andric 
6120b57cec5SDimitry Andric     // Unique the set of defining blocks for efficient lookup.
6130b57cec5SDimitry Andric     SmallPtrSet<BasicBlock *, 32> DefBlocks(Info.DefiningBlocks.begin(),
6140b57cec5SDimitry Andric                                             Info.DefiningBlocks.end());
6150b57cec5SDimitry Andric 
6160b57cec5SDimitry Andric     // Determine which blocks the value is live in.  These are blocks which lead
6170b57cec5SDimitry Andric     // to uses.
6180b57cec5SDimitry Andric     SmallPtrSet<BasicBlock *, 32> LiveInBlocks;
6190b57cec5SDimitry Andric     ComputeLiveInBlocks(AI, Info, DefBlocks, LiveInBlocks);
6200b57cec5SDimitry Andric 
6210b57cec5SDimitry Andric     // At this point, we're committed to promoting the alloca using IDF's, and
6220b57cec5SDimitry Andric     // the standard SSA construction algorithm.  Determine which blocks need phi
6230b57cec5SDimitry Andric     // nodes and see if we can optimize out some work by avoiding insertion of
6240b57cec5SDimitry Andric     // dead phi nodes.
6250b57cec5SDimitry Andric     IDF.setLiveInBlocks(LiveInBlocks);
6260b57cec5SDimitry Andric     IDF.setDefiningBlocks(DefBlocks);
6270b57cec5SDimitry Andric     SmallVector<BasicBlock *, 32> PHIBlocks;
6280b57cec5SDimitry Andric     IDF.calculate(PHIBlocks);
6290b57cec5SDimitry Andric     llvm::sort(PHIBlocks, [this](BasicBlock *A, BasicBlock *B) {
6300b57cec5SDimitry Andric       return BBNumbers.find(A)->second < BBNumbers.find(B)->second;
6310b57cec5SDimitry Andric     });
6320b57cec5SDimitry Andric 
6330b57cec5SDimitry Andric     unsigned CurrentVersion = 0;
6340b57cec5SDimitry Andric     for (BasicBlock *BB : PHIBlocks)
6350b57cec5SDimitry Andric       QueuePhiNode(BB, AllocaNum, CurrentVersion);
6360b57cec5SDimitry Andric   }
6370b57cec5SDimitry Andric 
6380b57cec5SDimitry Andric   if (Allocas.empty())
6390b57cec5SDimitry Andric     return; // All of the allocas must have been trivial!
6400b57cec5SDimitry Andric 
6410b57cec5SDimitry Andric   LBI.clear();
6420b57cec5SDimitry Andric 
6430b57cec5SDimitry Andric   // Set the incoming values for the basic block to be null values for all of
6440b57cec5SDimitry Andric   // the alloca's.  We do this in case there is a load of a value that has not
6450b57cec5SDimitry Andric   // been stored yet.  In this case, it will get this null value.
6460b57cec5SDimitry Andric   RenamePassData::ValVector Values(Allocas.size());
6470b57cec5SDimitry Andric   for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
6480b57cec5SDimitry Andric     Values[i] = UndefValue::get(Allocas[i]->getAllocatedType());
6490b57cec5SDimitry Andric 
6500b57cec5SDimitry Andric   // When handling debug info, treat all incoming values as if they have unknown
6510b57cec5SDimitry Andric   // locations until proven otherwise.
6520b57cec5SDimitry Andric   RenamePassData::LocationVector Locations(Allocas.size());
6530b57cec5SDimitry Andric 
6540b57cec5SDimitry Andric   // Walks all basic blocks in the function performing the SSA rename algorithm
6550b57cec5SDimitry Andric   // and inserting the phi nodes we marked as necessary
6560b57cec5SDimitry Andric   std::vector<RenamePassData> RenamePassWorkList;
6570b57cec5SDimitry Andric   RenamePassWorkList.emplace_back(&F.front(), nullptr, std::move(Values),
6580b57cec5SDimitry Andric                                   std::move(Locations));
6590b57cec5SDimitry Andric   do {
6600b57cec5SDimitry Andric     RenamePassData RPD = std::move(RenamePassWorkList.back());
6610b57cec5SDimitry Andric     RenamePassWorkList.pop_back();
6620b57cec5SDimitry Andric     // RenamePass may add new worklist entries.
6630b57cec5SDimitry Andric     RenamePass(RPD.BB, RPD.Pred, RPD.Values, RPD.Locations, RenamePassWorkList);
6640b57cec5SDimitry Andric   } while (!RenamePassWorkList.empty());
6650b57cec5SDimitry Andric 
6660b57cec5SDimitry Andric   // The renamer uses the Visited set to avoid infinite loops.  Clear it now.
6670b57cec5SDimitry Andric   Visited.clear();
6680b57cec5SDimitry Andric 
6690b57cec5SDimitry Andric   // Remove the allocas themselves from the function.
6700b57cec5SDimitry Andric   for (Instruction *A : Allocas) {
6710b57cec5SDimitry Andric     // If there are any uses of the alloca instructions left, they must be in
6720b57cec5SDimitry Andric     // unreachable basic blocks that were not processed by walking the dominator
6730b57cec5SDimitry Andric     // tree. Just delete the users now.
6740b57cec5SDimitry Andric     if (!A->use_empty())
675*5f7ddb14SDimitry Andric       A->replaceAllUsesWith(PoisonValue::get(A->getType()));
6760b57cec5SDimitry Andric     A->eraseFromParent();
6770b57cec5SDimitry Andric   }
6780b57cec5SDimitry Andric 
6790b57cec5SDimitry Andric   // Remove alloca's dbg.declare instrinsics from the function.
680af732203SDimitry Andric   for (auto &DbgUsers : AllocaDbgUsers) {
681af732203SDimitry Andric     for (auto *DII : DbgUsers)
682af732203SDimitry Andric       if (DII->isAddressOfVariable() || DII->getExpression()->startsWithDeref())
6830b57cec5SDimitry Andric         DII->eraseFromParent();
684af732203SDimitry Andric   }
6850b57cec5SDimitry Andric 
6860b57cec5SDimitry Andric   // Loop over all of the PHI nodes and see if there are any that we can get
6870b57cec5SDimitry Andric   // rid of because they merge all of the same incoming values.  This can
6880b57cec5SDimitry Andric   // happen due to undef values coming into the PHI nodes.  This process is
6890b57cec5SDimitry Andric   // iterative, because eliminating one PHI node can cause others to be removed.
6900b57cec5SDimitry Andric   bool EliminatedAPHI = true;
6910b57cec5SDimitry Andric   while (EliminatedAPHI) {
6920b57cec5SDimitry Andric     EliminatedAPHI = false;
6930b57cec5SDimitry Andric 
6940b57cec5SDimitry Andric     // Iterating over NewPhiNodes is deterministic, so it is safe to try to
6950b57cec5SDimitry Andric     // simplify and RAUW them as we go.  If it was not, we could add uses to
6960b57cec5SDimitry Andric     // the values we replace with in a non-deterministic order, thus creating
6970b57cec5SDimitry Andric     // non-deterministic def->use chains.
6980b57cec5SDimitry Andric     for (DenseMap<std::pair<unsigned, unsigned>, PHINode *>::iterator
6990b57cec5SDimitry Andric              I = NewPhiNodes.begin(),
7000b57cec5SDimitry Andric              E = NewPhiNodes.end();
7010b57cec5SDimitry Andric          I != E;) {
7020b57cec5SDimitry Andric       PHINode *PN = I->second;
7030b57cec5SDimitry Andric 
7040b57cec5SDimitry Andric       // If this PHI node merges one value and/or undefs, get the value.
7050b57cec5SDimitry Andric       if (Value *V = SimplifyInstruction(PN, SQ)) {
7060b57cec5SDimitry Andric         PN->replaceAllUsesWith(V);
7070b57cec5SDimitry Andric         PN->eraseFromParent();
7080b57cec5SDimitry Andric         NewPhiNodes.erase(I++);
7090b57cec5SDimitry Andric         EliminatedAPHI = true;
7100b57cec5SDimitry Andric         continue;
7110b57cec5SDimitry Andric       }
7120b57cec5SDimitry Andric       ++I;
7130b57cec5SDimitry Andric     }
7140b57cec5SDimitry Andric   }
7150b57cec5SDimitry Andric 
7160b57cec5SDimitry Andric   // At this point, the renamer has added entries to PHI nodes for all reachable
7170b57cec5SDimitry Andric   // code.  Unfortunately, there may be unreachable blocks which the renamer
7180b57cec5SDimitry Andric   // hasn't traversed.  If this is the case, the PHI nodes may not
7190b57cec5SDimitry Andric   // have incoming values for all predecessors.  Loop over all PHI nodes we have
7200b57cec5SDimitry Andric   // created, inserting undef values if they are missing any incoming values.
7210b57cec5SDimitry Andric   for (DenseMap<std::pair<unsigned, unsigned>, PHINode *>::iterator
7220b57cec5SDimitry Andric            I = NewPhiNodes.begin(),
7230b57cec5SDimitry Andric            E = NewPhiNodes.end();
7240b57cec5SDimitry Andric        I != E; ++I) {
7250b57cec5SDimitry Andric     // We want to do this once per basic block.  As such, only process a block
7260b57cec5SDimitry Andric     // when we find the PHI that is the first entry in the block.
7270b57cec5SDimitry Andric     PHINode *SomePHI = I->second;
7280b57cec5SDimitry Andric     BasicBlock *BB = SomePHI->getParent();
7290b57cec5SDimitry Andric     if (&BB->front() != SomePHI)
7300b57cec5SDimitry Andric       continue;
7310b57cec5SDimitry Andric 
7320b57cec5SDimitry Andric     // Only do work here if there the PHI nodes are missing incoming values.  We
7330b57cec5SDimitry Andric     // know that all PHI nodes that were inserted in a block will have the same
7340b57cec5SDimitry Andric     // number of incoming values, so we can just check any of them.
7350b57cec5SDimitry Andric     if (SomePHI->getNumIncomingValues() == getNumPreds(BB))
7360b57cec5SDimitry Andric       continue;
7370b57cec5SDimitry Andric 
7380b57cec5SDimitry Andric     // Get the preds for BB.
739af732203SDimitry Andric     SmallVector<BasicBlock *, 16> Preds(predecessors(BB));
7400b57cec5SDimitry Andric 
7410b57cec5SDimitry Andric     // Ok, now we know that all of the PHI nodes are missing entries for some
7420b57cec5SDimitry Andric     // basic blocks.  Start by sorting the incoming predecessors for efficient
7430b57cec5SDimitry Andric     // access.
7440b57cec5SDimitry Andric     auto CompareBBNumbers = [this](BasicBlock *A, BasicBlock *B) {
7450b57cec5SDimitry Andric       return BBNumbers.find(A)->second < BBNumbers.find(B)->second;
7460b57cec5SDimitry Andric     };
7470b57cec5SDimitry Andric     llvm::sort(Preds, CompareBBNumbers);
7480b57cec5SDimitry Andric 
7490b57cec5SDimitry Andric     // Now we loop through all BB's which have entries in SomePHI and remove
7500b57cec5SDimitry Andric     // them from the Preds list.
7510b57cec5SDimitry Andric     for (unsigned i = 0, e = SomePHI->getNumIncomingValues(); i != e; ++i) {
7520b57cec5SDimitry Andric       // Do a log(n) search of the Preds list for the entry we want.
7530b57cec5SDimitry Andric       SmallVectorImpl<BasicBlock *>::iterator EntIt = llvm::lower_bound(
7540b57cec5SDimitry Andric           Preds, SomePHI->getIncomingBlock(i), CompareBBNumbers);
7550b57cec5SDimitry Andric       assert(EntIt != Preds.end() && *EntIt == SomePHI->getIncomingBlock(i) &&
7560b57cec5SDimitry Andric              "PHI node has entry for a block which is not a predecessor!");
7570b57cec5SDimitry Andric 
7580b57cec5SDimitry Andric       // Remove the entry
7590b57cec5SDimitry Andric       Preds.erase(EntIt);
7600b57cec5SDimitry Andric     }
7610b57cec5SDimitry Andric 
7620b57cec5SDimitry Andric     // At this point, the blocks left in the preds list must have dummy
7630b57cec5SDimitry Andric     // entries inserted into every PHI nodes for the block.  Update all the phi
7640b57cec5SDimitry Andric     // nodes in this block that we are inserting (there could be phis before
7650b57cec5SDimitry Andric     // mem2reg runs).
7660b57cec5SDimitry Andric     unsigned NumBadPreds = SomePHI->getNumIncomingValues();
7670b57cec5SDimitry Andric     BasicBlock::iterator BBI = BB->begin();
7680b57cec5SDimitry Andric     while ((SomePHI = dyn_cast<PHINode>(BBI++)) &&
7690b57cec5SDimitry Andric            SomePHI->getNumIncomingValues() == NumBadPreds) {
7700b57cec5SDimitry Andric       Value *UndefVal = UndefValue::get(SomePHI->getType());
7710b57cec5SDimitry Andric       for (BasicBlock *Pred : Preds)
7720b57cec5SDimitry Andric         SomePHI->addIncoming(UndefVal, Pred);
7730b57cec5SDimitry Andric     }
7740b57cec5SDimitry Andric   }
7750b57cec5SDimitry Andric 
7760b57cec5SDimitry Andric   NewPhiNodes.clear();
7770b57cec5SDimitry Andric }
7780b57cec5SDimitry Andric 
7790b57cec5SDimitry Andric /// Determine which blocks the value is live in.
7800b57cec5SDimitry Andric ///
7810b57cec5SDimitry Andric /// These are blocks which lead to uses.  Knowing this allows us to avoid
7820b57cec5SDimitry Andric /// inserting PHI nodes into blocks which don't lead to uses (thus, the
7830b57cec5SDimitry Andric /// inserted phi nodes would be dead).
ComputeLiveInBlocks(AllocaInst * AI,AllocaInfo & Info,const SmallPtrSetImpl<BasicBlock * > & DefBlocks,SmallPtrSetImpl<BasicBlock * > & LiveInBlocks)7840b57cec5SDimitry Andric void PromoteMem2Reg::ComputeLiveInBlocks(
7850b57cec5SDimitry Andric     AllocaInst *AI, AllocaInfo &Info,
7860b57cec5SDimitry Andric     const SmallPtrSetImpl<BasicBlock *> &DefBlocks,
7870b57cec5SDimitry Andric     SmallPtrSetImpl<BasicBlock *> &LiveInBlocks) {
7880b57cec5SDimitry Andric   // To determine liveness, we must iterate through the predecessors of blocks
7890b57cec5SDimitry Andric   // where the def is live.  Blocks are added to the worklist if we need to
7900b57cec5SDimitry Andric   // check their predecessors.  Start with all the using blocks.
7910b57cec5SDimitry Andric   SmallVector<BasicBlock *, 64> LiveInBlockWorklist(Info.UsingBlocks.begin(),
7920b57cec5SDimitry Andric                                                     Info.UsingBlocks.end());
7930b57cec5SDimitry Andric 
7940b57cec5SDimitry Andric   // If any of the using blocks is also a definition block, check to see if the
7950b57cec5SDimitry Andric   // definition occurs before or after the use.  If it happens before the use,
7960b57cec5SDimitry Andric   // the value isn't really live-in.
7970b57cec5SDimitry Andric   for (unsigned i = 0, e = LiveInBlockWorklist.size(); i != e; ++i) {
7980b57cec5SDimitry Andric     BasicBlock *BB = LiveInBlockWorklist[i];
7990b57cec5SDimitry Andric     if (!DefBlocks.count(BB))
8000b57cec5SDimitry Andric       continue;
8010b57cec5SDimitry Andric 
8020b57cec5SDimitry Andric     // Okay, this is a block that both uses and defines the value.  If the first
8030b57cec5SDimitry Andric     // reference to the alloca is a def (store), then we know it isn't live-in.
8040b57cec5SDimitry Andric     for (BasicBlock::iterator I = BB->begin();; ++I) {
8050b57cec5SDimitry Andric       if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
8060b57cec5SDimitry Andric         if (SI->getOperand(1) != AI)
8070b57cec5SDimitry Andric           continue;
8080b57cec5SDimitry Andric 
8090b57cec5SDimitry Andric         // We found a store to the alloca before a load.  The alloca is not
8100b57cec5SDimitry Andric         // actually live-in here.
8110b57cec5SDimitry Andric         LiveInBlockWorklist[i] = LiveInBlockWorklist.back();
8120b57cec5SDimitry Andric         LiveInBlockWorklist.pop_back();
8130b57cec5SDimitry Andric         --i;
8140b57cec5SDimitry Andric         --e;
8150b57cec5SDimitry Andric         break;
8160b57cec5SDimitry Andric       }
8170b57cec5SDimitry Andric 
8180b57cec5SDimitry Andric       if (LoadInst *LI = dyn_cast<LoadInst>(I))
8190b57cec5SDimitry Andric         // Okay, we found a load before a store to the alloca.  It is actually
8200b57cec5SDimitry Andric         // live into this block.
8210b57cec5SDimitry Andric         if (LI->getOperand(0) == AI)
8220b57cec5SDimitry Andric           break;
8230b57cec5SDimitry Andric     }
8240b57cec5SDimitry Andric   }
8250b57cec5SDimitry Andric 
8260b57cec5SDimitry Andric   // Now that we have a set of blocks where the phi is live-in, recursively add
8270b57cec5SDimitry Andric   // their predecessors until we find the full region the value is live.
8280b57cec5SDimitry Andric   while (!LiveInBlockWorklist.empty()) {
8290b57cec5SDimitry Andric     BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
8300b57cec5SDimitry Andric 
8310b57cec5SDimitry Andric     // The block really is live in here, insert it into the set.  If already in
8320b57cec5SDimitry Andric     // the set, then it has already been processed.
8330b57cec5SDimitry Andric     if (!LiveInBlocks.insert(BB).second)
8340b57cec5SDimitry Andric       continue;
8350b57cec5SDimitry Andric 
8360b57cec5SDimitry Andric     // Since the value is live into BB, it is either defined in a predecessor or
8370b57cec5SDimitry Andric     // live into it to.  Add the preds to the worklist unless they are a
8380b57cec5SDimitry Andric     // defining block.
8390b57cec5SDimitry Andric     for (BasicBlock *P : predecessors(BB)) {
8400b57cec5SDimitry Andric       // The value is not live into a predecessor if it defines the value.
8410b57cec5SDimitry Andric       if (DefBlocks.count(P))
8420b57cec5SDimitry Andric         continue;
8430b57cec5SDimitry Andric 
8440b57cec5SDimitry Andric       // Otherwise it is, add to the worklist.
8450b57cec5SDimitry Andric       LiveInBlockWorklist.push_back(P);
8460b57cec5SDimitry Andric     }
8470b57cec5SDimitry Andric   }
8480b57cec5SDimitry Andric }
8490b57cec5SDimitry Andric 
8500b57cec5SDimitry Andric /// Queue a phi-node to be added to a basic-block for a specific Alloca.
8510b57cec5SDimitry Andric ///
8520b57cec5SDimitry Andric /// Returns true if there wasn't already a phi-node for that variable
QueuePhiNode(BasicBlock * BB,unsigned AllocaNo,unsigned & Version)8530b57cec5SDimitry Andric bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo,
8540b57cec5SDimitry Andric                                   unsigned &Version) {
8550b57cec5SDimitry Andric   // Look up the basic-block in question.
8560b57cec5SDimitry Andric   PHINode *&PN = NewPhiNodes[std::make_pair(BBNumbers[BB], AllocaNo)];
8570b57cec5SDimitry Andric 
8580b57cec5SDimitry Andric   // If the BB already has a phi node added for the i'th alloca then we're done!
8590b57cec5SDimitry Andric   if (PN)
8600b57cec5SDimitry Andric     return false;
8610b57cec5SDimitry Andric 
8620b57cec5SDimitry Andric   // Create a PhiNode using the dereferenced type... and add the phi-node to the
8630b57cec5SDimitry Andric   // BasicBlock.
8640b57cec5SDimitry Andric   PN = PHINode::Create(Allocas[AllocaNo]->getAllocatedType(), getNumPreds(BB),
8650b57cec5SDimitry Andric                        Allocas[AllocaNo]->getName() + "." + Twine(Version++),
8660b57cec5SDimitry Andric                        &BB->front());
8670b57cec5SDimitry Andric   ++NumPHIInsert;
8680b57cec5SDimitry Andric   PhiToAllocaMap[PN] = AllocaNo;
8690b57cec5SDimitry Andric   return true;
8700b57cec5SDimitry Andric }
8710b57cec5SDimitry Andric 
8720b57cec5SDimitry Andric /// Update the debug location of a phi. \p ApplyMergedLoc indicates whether to
8730b57cec5SDimitry Andric /// create a merged location incorporating \p DL, or to set \p DL directly.
updateForIncomingValueLocation(PHINode * PN,DebugLoc DL,bool ApplyMergedLoc)8740b57cec5SDimitry Andric static void updateForIncomingValueLocation(PHINode *PN, DebugLoc DL,
8750b57cec5SDimitry Andric                                            bool ApplyMergedLoc) {
8760b57cec5SDimitry Andric   if (ApplyMergedLoc)
8770b57cec5SDimitry Andric     PN->applyMergedLocation(PN->getDebugLoc(), DL);
8780b57cec5SDimitry Andric   else
8790b57cec5SDimitry Andric     PN->setDebugLoc(DL);
8800b57cec5SDimitry Andric }
8810b57cec5SDimitry Andric 
8820b57cec5SDimitry Andric /// Recursively traverse the CFG of the function, renaming loads and
8830b57cec5SDimitry Andric /// stores to the allocas which we are promoting.
8840b57cec5SDimitry Andric ///
8850b57cec5SDimitry Andric /// IncomingVals indicates what value each Alloca contains on exit from the
8860b57cec5SDimitry Andric /// predecessor block Pred.
RenamePass(BasicBlock * BB,BasicBlock * Pred,RenamePassData::ValVector & IncomingVals,RenamePassData::LocationVector & IncomingLocs,std::vector<RenamePassData> & Worklist)8870b57cec5SDimitry Andric void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
8880b57cec5SDimitry Andric                                 RenamePassData::ValVector &IncomingVals,
8890b57cec5SDimitry Andric                                 RenamePassData::LocationVector &IncomingLocs,
8900b57cec5SDimitry Andric                                 std::vector<RenamePassData> &Worklist) {
8910b57cec5SDimitry Andric NextIteration:
8920b57cec5SDimitry Andric   // If we are inserting any phi nodes into this BB, they will already be in the
8930b57cec5SDimitry Andric   // block.
8940b57cec5SDimitry Andric   if (PHINode *APN = dyn_cast<PHINode>(BB->begin())) {
8950b57cec5SDimitry Andric     // If we have PHI nodes to update, compute the number of edges from Pred to
8960b57cec5SDimitry Andric     // BB.
8970b57cec5SDimitry Andric     if (PhiToAllocaMap.count(APN)) {
8980b57cec5SDimitry Andric       // We want to be able to distinguish between PHI nodes being inserted by
8990b57cec5SDimitry Andric       // this invocation of mem2reg from those phi nodes that already existed in
9000b57cec5SDimitry Andric       // the IR before mem2reg was run.  We determine that APN is being inserted
9010b57cec5SDimitry Andric       // because it is missing incoming edges.  All other PHI nodes being
9020b57cec5SDimitry Andric       // inserted by this pass of mem2reg will have the same number of incoming
9030b57cec5SDimitry Andric       // operands so far.  Remember this count.
9040b57cec5SDimitry Andric       unsigned NewPHINumOperands = APN->getNumOperands();
9050b57cec5SDimitry Andric 
906af732203SDimitry Andric       unsigned NumEdges = llvm::count(successors(Pred), BB);
9070b57cec5SDimitry Andric       assert(NumEdges && "Must be at least one edge from Pred to BB!");
9080b57cec5SDimitry Andric 
9090b57cec5SDimitry Andric       // Add entries for all the phis.
9100b57cec5SDimitry Andric       BasicBlock::iterator PNI = BB->begin();
9110b57cec5SDimitry Andric       do {
9120b57cec5SDimitry Andric         unsigned AllocaNo = PhiToAllocaMap[APN];
9130b57cec5SDimitry Andric 
9140b57cec5SDimitry Andric         // Update the location of the phi node.
9150b57cec5SDimitry Andric         updateForIncomingValueLocation(APN, IncomingLocs[AllocaNo],
9160b57cec5SDimitry Andric                                        APN->getNumIncomingValues() > 0);
9170b57cec5SDimitry Andric 
9180b57cec5SDimitry Andric         // Add N incoming values to the PHI node.
9190b57cec5SDimitry Andric         for (unsigned i = 0; i != NumEdges; ++i)
9200b57cec5SDimitry Andric           APN->addIncoming(IncomingVals[AllocaNo], Pred);
9210b57cec5SDimitry Andric 
9220b57cec5SDimitry Andric         // The currently active variable for this block is now the PHI.
9230b57cec5SDimitry Andric         IncomingVals[AllocaNo] = APN;
924af732203SDimitry Andric         for (DbgVariableIntrinsic *DII : AllocaDbgUsers[AllocaNo])
925af732203SDimitry Andric           if (DII->isAddressOfVariable())
9260b57cec5SDimitry Andric             ConvertDebugDeclareToDebugValue(DII, APN, DIB);
9270b57cec5SDimitry Andric 
9280b57cec5SDimitry Andric         // Get the next phi node.
9290b57cec5SDimitry Andric         ++PNI;
9300b57cec5SDimitry Andric         APN = dyn_cast<PHINode>(PNI);
9310b57cec5SDimitry Andric         if (!APN)
9320b57cec5SDimitry Andric           break;
9330b57cec5SDimitry Andric 
9340b57cec5SDimitry Andric         // Verify that it is missing entries.  If not, it is not being inserted
9350b57cec5SDimitry Andric         // by this mem2reg invocation so we want to ignore it.
9360b57cec5SDimitry Andric       } while (APN->getNumOperands() == NewPHINumOperands);
9370b57cec5SDimitry Andric     }
9380b57cec5SDimitry Andric   }
9390b57cec5SDimitry Andric 
9400b57cec5SDimitry Andric   // Don't revisit blocks.
9410b57cec5SDimitry Andric   if (!Visited.insert(BB).second)
9420b57cec5SDimitry Andric     return;
9430b57cec5SDimitry Andric 
9440b57cec5SDimitry Andric   for (BasicBlock::iterator II = BB->begin(); !II->isTerminator();) {
9450b57cec5SDimitry Andric     Instruction *I = &*II++; // get the instruction, increment iterator
9460b57cec5SDimitry Andric 
9470b57cec5SDimitry Andric     if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9480b57cec5SDimitry Andric       AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand());
9490b57cec5SDimitry Andric       if (!Src)
9500b57cec5SDimitry Andric         continue;
9510b57cec5SDimitry Andric 
9520b57cec5SDimitry Andric       DenseMap<AllocaInst *, unsigned>::iterator AI = AllocaLookup.find(Src);
9530b57cec5SDimitry Andric       if (AI == AllocaLookup.end())
9540b57cec5SDimitry Andric         continue;
9550b57cec5SDimitry Andric 
9560b57cec5SDimitry Andric       Value *V = IncomingVals[AI->second];
9570b57cec5SDimitry Andric 
9580b57cec5SDimitry Andric       // If the load was marked as nonnull we don't want to lose
9590b57cec5SDimitry Andric       // that information when we erase this Load. So we preserve
9600b57cec5SDimitry Andric       // it with an assume.
9610b57cec5SDimitry Andric       if (AC && LI->getMetadata(LLVMContext::MD_nonnull) &&
9620b57cec5SDimitry Andric           !isKnownNonZero(V, SQ.DL, 0, AC, LI, &DT))
9630b57cec5SDimitry Andric         addAssumeNonNull(AC, LI);
9640b57cec5SDimitry Andric 
9650b57cec5SDimitry Andric       // Anything using the load now uses the current value.
9660b57cec5SDimitry Andric       LI->replaceAllUsesWith(V);
9670b57cec5SDimitry Andric       BB->getInstList().erase(LI);
9680b57cec5SDimitry Andric     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
9690b57cec5SDimitry Andric       // Delete this instruction and mark the name as the current holder of the
9700b57cec5SDimitry Andric       // value
9710b57cec5SDimitry Andric       AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand());
9720b57cec5SDimitry Andric       if (!Dest)
9730b57cec5SDimitry Andric         continue;
9740b57cec5SDimitry Andric 
9750b57cec5SDimitry Andric       DenseMap<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest);
9760b57cec5SDimitry Andric       if (ai == AllocaLookup.end())
9770b57cec5SDimitry Andric         continue;
9780b57cec5SDimitry Andric 
9790b57cec5SDimitry Andric       // what value were we writing?
9800b57cec5SDimitry Andric       unsigned AllocaNo = ai->second;
9810b57cec5SDimitry Andric       IncomingVals[AllocaNo] = SI->getOperand(0);
9820b57cec5SDimitry Andric 
9830b57cec5SDimitry Andric       // Record debuginfo for the store before removing it.
9840b57cec5SDimitry Andric       IncomingLocs[AllocaNo] = SI->getDebugLoc();
985af732203SDimitry Andric       for (DbgVariableIntrinsic *DII : AllocaDbgUsers[ai->second])
986af732203SDimitry Andric         if (DII->isAddressOfVariable())
9870b57cec5SDimitry Andric           ConvertDebugDeclareToDebugValue(DII, SI, DIB);
9880b57cec5SDimitry Andric       BB->getInstList().erase(SI);
9890b57cec5SDimitry Andric     }
9900b57cec5SDimitry Andric   }
9910b57cec5SDimitry Andric 
9920b57cec5SDimitry Andric   // 'Recurse' to our successors.
9930b57cec5SDimitry Andric   succ_iterator I = succ_begin(BB), E = succ_end(BB);
9940b57cec5SDimitry Andric   if (I == E)
9950b57cec5SDimitry Andric     return;
9960b57cec5SDimitry Andric 
9970b57cec5SDimitry Andric   // Keep track of the successors so we don't visit the same successor twice
9980b57cec5SDimitry Andric   SmallPtrSet<BasicBlock *, 8> VisitedSuccs;
9990b57cec5SDimitry Andric 
10000b57cec5SDimitry Andric   // Handle the first successor without using the worklist.
10010b57cec5SDimitry Andric   VisitedSuccs.insert(*I);
10020b57cec5SDimitry Andric   Pred = BB;
10030b57cec5SDimitry Andric   BB = *I;
10040b57cec5SDimitry Andric   ++I;
10050b57cec5SDimitry Andric 
10060b57cec5SDimitry Andric   for (; I != E; ++I)
10070b57cec5SDimitry Andric     if (VisitedSuccs.insert(*I).second)
10080b57cec5SDimitry Andric       Worklist.emplace_back(*I, Pred, IncomingVals, IncomingLocs);
10090b57cec5SDimitry Andric 
10100b57cec5SDimitry Andric   goto NextIteration;
10110b57cec5SDimitry Andric }
10120b57cec5SDimitry Andric 
PromoteMemToReg(ArrayRef<AllocaInst * > Allocas,DominatorTree & DT,AssumptionCache * AC)10130b57cec5SDimitry Andric void llvm::PromoteMemToReg(ArrayRef<AllocaInst *> Allocas, DominatorTree &DT,
10140b57cec5SDimitry Andric                            AssumptionCache *AC) {
10150b57cec5SDimitry Andric   // If there is nothing to do, bail out...
10160b57cec5SDimitry Andric   if (Allocas.empty())
10170b57cec5SDimitry Andric     return;
10180b57cec5SDimitry Andric 
10190b57cec5SDimitry Andric   PromoteMem2Reg(Allocas, DT, AC).run();
10200b57cec5SDimitry Andric }
1021