1f22ef01cSRoman Divacky //===- PromoteMemoryToRegister.cpp - Convert allocas to registers ---------===//
2f22ef01cSRoman Divacky //
3f22ef01cSRoman Divacky //                     The LLVM Compiler Infrastructure
4f22ef01cSRoman Divacky //
5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source
6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details.
7f22ef01cSRoman Divacky //
8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
9f22ef01cSRoman Divacky //
10f22ef01cSRoman Divacky // This file promotes memory references to be register references.  It promotes
11f22ef01cSRoman Divacky // alloca instructions which only have loads and stores as uses.  An alloca is
122754fe60SDimitry Andric // transformed by using iterated dominator frontiers to place PHI nodes, then
132754fe60SDimitry Andric // traversing the function in depth-first order to rewrite loads and stores as
142754fe60SDimitry Andric // appropriate.
152754fe60SDimitry Andric //
16f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
17f22ef01cSRoman Divacky 
18f785676fSDimitry Andric #include "llvm/ADT/ArrayRef.h"
19139f7f9bSDimitry Andric #include "llvm/ADT/DenseMap.h"
20139f7f9bSDimitry Andric #include "llvm/ADT/STLExtras.h"
21139f7f9bSDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
22139f7f9bSDimitry Andric #include "llvm/ADT/SmallVector.h"
23139f7f9bSDimitry Andric #include "llvm/ADT/Statistic.h"
242cab237bSDimitry Andric #include "llvm/ADT/TinyPtrVector.h"
252cab237bSDimitry Andric #include "llvm/ADT/Twine.h"
267a7e6055SDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
272754fe60SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h"
28ff0cc061SDimitry Andric #include "llvm/Analysis/IteratedDominanceFrontier.h"
294ba319b5SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
3017a519f9SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
312cab237bSDimitry Andric #include "llvm/IR/BasicBlock.h"
3291bc56edSDimitry Andric #include "llvm/IR/CFG.h"
332cab237bSDimitry Andric #include "llvm/IR/Constant.h"
34139f7f9bSDimitry Andric #include "llvm/IR/Constants.h"
3591bc56edSDimitry Andric #include "llvm/IR/DIBuilder.h"
36139f7f9bSDimitry Andric #include "llvm/IR/DerivedTypes.h"
3791bc56edSDimitry Andric #include "llvm/IR/Dominators.h"
38139f7f9bSDimitry Andric #include "llvm/IR/Function.h"
392cab237bSDimitry Andric #include "llvm/IR/InstrTypes.h"
402cab237bSDimitry Andric #include "llvm/IR/Instruction.h"
41139f7f9bSDimitry Andric #include "llvm/IR/Instructions.h"
42139f7f9bSDimitry Andric #include "llvm/IR/IntrinsicInst.h"
432cab237bSDimitry Andric #include "llvm/IR/Intrinsics.h"
442cab237bSDimitry Andric #include "llvm/IR/LLVMContext.h"
45ff0cc061SDimitry Andric #include "llvm/IR/Module.h"
462cab237bSDimitry Andric #include "llvm/IR/Type.h"
472cab237bSDimitry Andric #include "llvm/IR/User.h"
482cab237bSDimitry Andric #include "llvm/Support/Casting.h"
497a7e6055SDimitry Andric #include "llvm/Transforms/Utils/PromoteMemToReg.h"
50f22ef01cSRoman Divacky #include <algorithm>
512cab237bSDimitry Andric #include <cassert>
522cab237bSDimitry Andric #include <iterator>
532cab237bSDimitry Andric #include <utility>
542cab237bSDimitry Andric #include <vector>
552cab237bSDimitry Andric 
56f22ef01cSRoman Divacky using namespace llvm;
57f22ef01cSRoman Divacky 
5891bc56edSDimitry Andric #define DEBUG_TYPE "mem2reg"
5991bc56edSDimitry Andric 
60f22ef01cSRoman Divacky STATISTIC(NumLocalPromoted, "Number of alloca's promoted within one block");
61f22ef01cSRoman Divacky STATISTIC(NumSingleStore,   "Number of alloca's promoted with a single store");
62f22ef01cSRoman Divacky STATISTIC(NumDeadAlloca,    "Number of dead alloca's removed");
63f22ef01cSRoman Divacky STATISTIC(NumPHIInsert,     "Number of PHI nodes inserted");
64f22ef01cSRoman Divacky 
isAllocaPromotable(const AllocaInst * AI)65f22ef01cSRoman Divacky bool llvm::isAllocaPromotable(const AllocaInst *AI) {
66f22ef01cSRoman Divacky   // FIXME: If the memory unit is of pointer or integer type, we can permit
67f22ef01cSRoman Divacky   // assignments to subsections of the memory unit.
6891bc56edSDimitry Andric   unsigned AS = AI->getType()->getAddressSpace();
69f22ef01cSRoman Divacky 
70f22ef01cSRoman Divacky   // Only allow direct and non-volatile loads and stores...
7191bc56edSDimitry Andric   for (const User *U : AI->users()) {
72ffd1746dSEd Schouten     if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
736122f3e6SDimitry Andric       // Note that atomic loads can be transformed; atomic semantics do
746122f3e6SDimitry Andric       // not have any meaning for a local alloca.
75f22ef01cSRoman Divacky       if (LI->isVolatile())
76f22ef01cSRoman Divacky         return false;
77ffd1746dSEd Schouten     } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
78f22ef01cSRoman Divacky       if (SI->getOperand(0) == AI)
79f22ef01cSRoman Divacky         return false; // Don't allow a store OF the AI, only INTO the AI.
806122f3e6SDimitry Andric       // Note that atomic stores can be transformed; atomic semantics do
816122f3e6SDimitry Andric       // not have any meaning for a local alloca.
82f22ef01cSRoman Divacky       if (SI->isVolatile())
83f22ef01cSRoman Divacky         return false;
8417a519f9SDimitry Andric     } else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
85*b5893f02SDimitry Andric       if (!II->isLifetimeStartOrEnd())
8617a519f9SDimitry Andric         return false;
8717a519f9SDimitry Andric     } else if (const BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
8891bc56edSDimitry Andric       if (BCI->getType() != Type::getInt8PtrTy(U->getContext(), AS))
8917a519f9SDimitry Andric         return false;
9017a519f9SDimitry Andric       if (!onlyUsedByLifetimeMarkers(BCI))
9117a519f9SDimitry Andric         return false;
9217a519f9SDimitry Andric     } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
9391bc56edSDimitry Andric       if (GEPI->getType() != Type::getInt8PtrTy(U->getContext(), AS))
9417a519f9SDimitry Andric         return false;
9517a519f9SDimitry Andric       if (!GEPI->hasAllZeroIndices())
9617a519f9SDimitry Andric         return false;
9717a519f9SDimitry Andric       if (!onlyUsedByLifetimeMarkers(GEPI))
9817a519f9SDimitry Andric         return false;
99f22ef01cSRoman Divacky     } else {
100f22ef01cSRoman Divacky       return false;
101f22ef01cSRoman Divacky     }
102ffd1746dSEd Schouten   }
103f22ef01cSRoman Divacky 
104f22ef01cSRoman Divacky   return true;
105f22ef01cSRoman Divacky }
106f22ef01cSRoman Divacky 
107f22ef01cSRoman Divacky namespace {
108f22ef01cSRoman Divacky 
109f22ef01cSRoman Divacky struct AllocaInfo {
1102754fe60SDimitry Andric   SmallVector<BasicBlock *, 32> DefiningBlocks;
1112754fe60SDimitry Andric   SmallVector<BasicBlock *, 32> UsingBlocks;
112f22ef01cSRoman Divacky 
113f22ef01cSRoman Divacky   StoreInst *OnlyStore;
114f22ef01cSRoman Divacky   BasicBlock *OnlyBlock;
115f22ef01cSRoman Divacky   bool OnlyUsedInOneBlock;
116f22ef01cSRoman Divacky 
117f22ef01cSRoman Divacky   Value *AllocaPointerVal;
118*b5893f02SDimitry Andric   TinyPtrVector<DbgVariableIntrinsic *> DbgDeclares;
119f22ef01cSRoman Divacky 
clear__anonb6e2acda0111::AllocaInfo120f22ef01cSRoman Divacky   void clear() {
121f22ef01cSRoman Divacky     DefiningBlocks.clear();
122f22ef01cSRoman Divacky     UsingBlocks.clear();
12391bc56edSDimitry Andric     OnlyStore = nullptr;
12491bc56edSDimitry Andric     OnlyBlock = nullptr;
125f22ef01cSRoman Divacky     OnlyUsedInOneBlock = true;
12691bc56edSDimitry Andric     AllocaPointerVal = nullptr;
1272cab237bSDimitry Andric     DbgDeclares.clear();
128f22ef01cSRoman Divacky   }
129f22ef01cSRoman Divacky 
130f785676fSDimitry Andric   /// Scan the uses of the specified alloca, filling in the AllocaInfo used
131f785676fSDimitry Andric   /// by the rest of the pass to reason about the uses of this alloca.
AnalyzeAlloca__anonb6e2acda0111::AllocaInfo132f22ef01cSRoman Divacky   void AnalyzeAlloca(AllocaInst *AI) {
133f22ef01cSRoman Divacky     clear();
134f22ef01cSRoman Divacky 
135f22ef01cSRoman Divacky     // As we scan the uses of the alloca instruction, keep track of stores,
136f22ef01cSRoman Divacky     // and decide whether all of the loads and stores to the alloca are within
137f22ef01cSRoman Divacky     // the same basic block.
13891bc56edSDimitry Andric     for (auto UI = AI->user_begin(), E = AI->user_end(); UI != E;) {
139f22ef01cSRoman Divacky       Instruction *User = cast<Instruction>(*UI++);
140f22ef01cSRoman Divacky 
141f22ef01cSRoman Divacky       if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
142f22ef01cSRoman Divacky         // Remember the basic blocks which define new values for the alloca
143f22ef01cSRoman Divacky         DefiningBlocks.push_back(SI->getParent());
144f22ef01cSRoman Divacky         AllocaPointerVal = SI->getOperand(0);
145f22ef01cSRoman Divacky         OnlyStore = SI;
146f22ef01cSRoman Divacky       } else {
147f22ef01cSRoman Divacky         LoadInst *LI = cast<LoadInst>(User);
148f22ef01cSRoman Divacky         // Otherwise it must be a load instruction, keep track of variable
149f22ef01cSRoman Divacky         // reads.
150f22ef01cSRoman Divacky         UsingBlocks.push_back(LI->getParent());
151f22ef01cSRoman Divacky         AllocaPointerVal = LI;
152f22ef01cSRoman Divacky       }
153f22ef01cSRoman Divacky 
154f22ef01cSRoman Divacky       if (OnlyUsedInOneBlock) {
15591bc56edSDimitry Andric         if (!OnlyBlock)
156f22ef01cSRoman Divacky           OnlyBlock = User->getParent();
157f22ef01cSRoman Divacky         else if (OnlyBlock != User->getParent())
158f22ef01cSRoman Divacky           OnlyUsedInOneBlock = false;
159f22ef01cSRoman Divacky       }
160f22ef01cSRoman Divacky     }
161f22ef01cSRoman Divacky 
1622cab237bSDimitry Andric     DbgDeclares = FindDbgAddrUses(AI);
163f22ef01cSRoman Divacky   }
164f22ef01cSRoman Divacky };
1652754fe60SDimitry Andric 
1664ba319b5SDimitry Andric /// Data package used by RenamePass().
1674ba319b5SDimitry Andric struct RenamePassData {
1682cab237bSDimitry Andric   using ValVector = std::vector<Value *>;
1694ba319b5SDimitry Andric   using LocationVector = std::vector<DebugLoc>;
1702754fe60SDimitry Andric 
RenamePassData__anonb6e2acda0111::RenamePassData1714ba319b5SDimitry Andric   RenamePassData(BasicBlock *B, BasicBlock *P, ValVector V, LocationVector L)
1724ba319b5SDimitry Andric       : BB(B), Pred(P), Values(std::move(V)), Locations(std::move(L)) {}
1732cab237bSDimitry Andric 
174f785676fSDimitry Andric   BasicBlock *BB;
175f785676fSDimitry Andric   BasicBlock *Pred;
176f785676fSDimitry Andric   ValVector Values;
1774ba319b5SDimitry Andric   LocationVector Locations;
1782754fe60SDimitry Andric };
179f785676fSDimitry Andric 
1804ba319b5SDimitry Andric /// This assigns and keeps a per-bb relative ordering of load/store
181f785676fSDimitry Andric /// instructions in the block that directly load or store an alloca.
182f785676fSDimitry Andric ///
183f785676fSDimitry Andric /// This functionality is important because it avoids scanning large basic
184f785676fSDimitry Andric /// blocks multiple times when promoting many allocas in the same block.
185f785676fSDimitry Andric class LargeBlockInfo {
1864ba319b5SDimitry Andric   /// For each instruction that we track, keep the index of the
187f785676fSDimitry Andric   /// instruction.
188f785676fSDimitry Andric   ///
189f785676fSDimitry Andric   /// The index starts out as the number of the instruction from the start of
190f785676fSDimitry Andric   /// the block.
191f785676fSDimitry Andric   DenseMap<const Instruction *, unsigned> InstNumbers;
192f785676fSDimitry Andric 
193f785676fSDimitry Andric public:
194f785676fSDimitry Andric 
195f785676fSDimitry Andric   /// This code only looks at accesses to allocas.
isInterestingInstruction(const Instruction * I)196f785676fSDimitry Andric   static bool isInterestingInstruction(const Instruction *I) {
197f785676fSDimitry Andric     return (isa<LoadInst>(I) && isa<AllocaInst>(I->getOperand(0))) ||
198f785676fSDimitry Andric            (isa<StoreInst>(I) && isa<AllocaInst>(I->getOperand(1)));
199f785676fSDimitry Andric   }
200f785676fSDimitry Andric 
201f785676fSDimitry Andric   /// Get or calculate the index of the specified instruction.
getInstructionIndex(const Instruction * I)202f785676fSDimitry Andric   unsigned getInstructionIndex(const Instruction *I) {
203f785676fSDimitry Andric     assert(isInterestingInstruction(I) &&
204f785676fSDimitry Andric            "Not a load/store to/from an alloca?");
205f785676fSDimitry Andric 
206f785676fSDimitry Andric     // If we already have this instruction number, return it.
207f785676fSDimitry Andric     DenseMap<const Instruction *, unsigned>::iterator It = InstNumbers.find(I);
208f785676fSDimitry Andric     if (It != InstNumbers.end())
209f785676fSDimitry Andric       return It->second;
210f785676fSDimitry Andric 
211f785676fSDimitry Andric     // Scan the whole block to get the instruction.  This accumulates
212f785676fSDimitry Andric     // information for every interesting instruction in the block, in order to
213f785676fSDimitry Andric     // avoid gratuitus rescans.
214f785676fSDimitry Andric     const BasicBlock *BB = I->getParent();
215f785676fSDimitry Andric     unsigned InstNo = 0;
2167d523365SDimitry Andric     for (const Instruction &BBI : *BB)
2177d523365SDimitry Andric       if (isInterestingInstruction(&BBI))
2187d523365SDimitry Andric         InstNumbers[&BBI] = InstNo++;
219f785676fSDimitry Andric     It = InstNumbers.find(I);
220f785676fSDimitry Andric 
221f785676fSDimitry Andric     assert(It != InstNumbers.end() && "Didn't insert instruction?");
222f785676fSDimitry Andric     return It->second;
223f785676fSDimitry Andric   }
224f785676fSDimitry Andric 
deleteValue(const Instruction * I)225f785676fSDimitry Andric   void deleteValue(const Instruction *I) { InstNumbers.erase(I); }
226f785676fSDimitry Andric 
clear()227f785676fSDimitry Andric   void clear() { InstNumbers.clear(); }
228f785676fSDimitry Andric };
229f785676fSDimitry Andric 
230f785676fSDimitry Andric struct PromoteMem2Reg {
231f785676fSDimitry Andric   /// The alloca instructions being promoted.
232f785676fSDimitry Andric   std::vector<AllocaInst *> Allocas;
2332cab237bSDimitry Andric 
234f785676fSDimitry Andric   DominatorTree &DT;
235f785676fSDimitry Andric   DIBuilder DIB;
2362cab237bSDimitry Andric 
23739d628a0SDimitry Andric   /// A cache of @llvm.assume intrinsics used by SimplifyInstruction.
23839d628a0SDimitry Andric   AssumptionCache *AC;
23939d628a0SDimitry Andric 
240f37b6182SDimitry Andric   const SimplifyQuery SQ;
2412cab237bSDimitry Andric 
242f785676fSDimitry Andric   /// Reverse mapping of Allocas.
243f785676fSDimitry Andric   DenseMap<AllocaInst *, unsigned> AllocaLookup;
244f785676fSDimitry Andric 
2454ba319b5SDimitry Andric   /// The PhiNodes we're adding.
246f785676fSDimitry Andric   ///
247f785676fSDimitry Andric   /// That map is used to simplify some Phi nodes as we iterate over it, so
248f785676fSDimitry Andric   /// it should have deterministic iterators.  We could use a MapVector, but
249f785676fSDimitry Andric   /// since we already maintain a map from BasicBlock* to a stable numbering
250f785676fSDimitry Andric   /// (BBNumbers), the DenseMap is more efficient (also supports removal).
251f785676fSDimitry Andric   DenseMap<std::pair<unsigned, unsigned>, PHINode *> NewPhiNodes;
252f785676fSDimitry Andric 
253f785676fSDimitry Andric   /// For each PHI node, keep track of which entry in Allocas it corresponds
254f785676fSDimitry Andric   /// to.
255f785676fSDimitry Andric   DenseMap<PHINode *, unsigned> PhiToAllocaMap;
256f785676fSDimitry Andric 
257f785676fSDimitry Andric   /// If we are updating an AliasSetTracker, then for each alloca that is of
258f785676fSDimitry Andric   /// pointer type, we keep track of what to copyValue to the inserted PHI
259f785676fSDimitry Andric   /// nodes here.
260f785676fSDimitry Andric   std::vector<Value *> PointerAllocaValues;
261f785676fSDimitry Andric 
262f785676fSDimitry Andric   /// For each alloca, we keep track of the dbg.declare intrinsic that
263f785676fSDimitry Andric   /// describes it, if any, so that we can convert it to a dbg.value
264f785676fSDimitry Andric   /// intrinsic if the alloca gets promoted.
265*b5893f02SDimitry Andric   SmallVector<TinyPtrVector<DbgVariableIntrinsic *>, 8> AllocaDbgDeclares;
266f785676fSDimitry Andric 
267f785676fSDimitry Andric   /// The set of basic blocks the renamer has already visited.
268f785676fSDimitry Andric   SmallPtrSet<BasicBlock *, 16> Visited;
269f785676fSDimitry Andric 
270f785676fSDimitry Andric   /// Contains a stable numbering of basic blocks to avoid non-determinstic
271f785676fSDimitry Andric   /// behavior.
272f785676fSDimitry Andric   DenseMap<BasicBlock *, unsigned> BBNumbers;
273f785676fSDimitry Andric 
274f785676fSDimitry Andric   /// Lazily compute the number of predecessors a block has.
275f785676fSDimitry Andric   DenseMap<const BasicBlock *, unsigned> BBNumPreds;
276f785676fSDimitry Andric 
277f785676fSDimitry Andric public:
PromoteMem2Reg__anonb6e2acda0111::PromoteMem2Reg278f785676fSDimitry Andric   PromoteMem2Reg(ArrayRef<AllocaInst *> Allocas, DominatorTree &DT,
2797a7e6055SDimitry Andric                  AssumptionCache *AC)
280f785676fSDimitry Andric       : Allocas(Allocas.begin(), Allocas.end()), DT(DT),
28139d628a0SDimitry Andric         DIB(*DT.getRoot()->getParent()->getParent(), /*AllowUnresolved*/ false),
282f37b6182SDimitry Andric         AC(AC), SQ(DT.getRoot()->getParent()->getParent()->getDataLayout(),
283f37b6182SDimitry Andric                    nullptr, &DT, AC) {}
284f785676fSDimitry Andric 
285f785676fSDimitry Andric   void run();
286f785676fSDimitry Andric 
287f785676fSDimitry Andric private:
RemoveFromAllocasList__anonb6e2acda0111::PromoteMem2Reg288f785676fSDimitry Andric   void RemoveFromAllocasList(unsigned &AllocaIdx) {
289f785676fSDimitry Andric     Allocas[AllocaIdx] = Allocas.back();
290f785676fSDimitry Andric     Allocas.pop_back();
291f785676fSDimitry Andric     --AllocaIdx;
292f785676fSDimitry Andric   }
293f785676fSDimitry Andric 
getNumPreds__anonb6e2acda0111::PromoteMem2Reg294f785676fSDimitry Andric   unsigned getNumPreds(const BasicBlock *BB) {
295f785676fSDimitry Andric     unsigned &NP = BBNumPreds[BB];
296f785676fSDimitry Andric     if (NP == 0)
2974ba319b5SDimitry Andric       NP = pred_size(BB) + 1;
298f785676fSDimitry Andric     return NP - 1;
299f785676fSDimitry Andric   }
300f785676fSDimitry Andric 
301f785676fSDimitry Andric   void ComputeLiveInBlocks(AllocaInst *AI, AllocaInfo &Info,
30239d628a0SDimitry Andric                            const SmallPtrSetImpl<BasicBlock *> &DefBlocks,
30339d628a0SDimitry Andric                            SmallPtrSetImpl<BasicBlock *> &LiveInBlocks);
304f785676fSDimitry Andric   void RenamePass(BasicBlock *BB, BasicBlock *Pred,
305f785676fSDimitry Andric                   RenamePassData::ValVector &IncVals,
3064ba319b5SDimitry Andric                   RenamePassData::LocationVector &IncLocs,
307f785676fSDimitry Andric                   std::vector<RenamePassData> &Worklist);
308f785676fSDimitry Andric   bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx, unsigned &Version);
309f785676fSDimitry Andric };
310f785676fSDimitry Andric 
3112cab237bSDimitry Andric } // end anonymous namespace
312f22ef01cSRoman Divacky 
3137a7e6055SDimitry Andric /// Given a LoadInst LI this adds assume(LI != null) after it.
addAssumeNonNull(AssumptionCache * AC,LoadInst * LI)3147a7e6055SDimitry Andric static void addAssumeNonNull(AssumptionCache *AC, LoadInst *LI) {
3157a7e6055SDimitry Andric   Function *AssumeIntrinsic =
3167a7e6055SDimitry Andric       Intrinsic::getDeclaration(LI->getModule(), Intrinsic::assume);
3177a7e6055SDimitry Andric   ICmpInst *LoadNotNull = new ICmpInst(ICmpInst::ICMP_NE, LI,
3187a7e6055SDimitry Andric                                        Constant::getNullValue(LI->getType()));
3197a7e6055SDimitry Andric   LoadNotNull->insertAfter(LI);
3207a7e6055SDimitry Andric   CallInst *CI = CallInst::Create(AssumeIntrinsic, {LoadNotNull});
3217a7e6055SDimitry Andric   CI->insertAfter(LoadNotNull);
3227a7e6055SDimitry Andric   AC->registerAssumption(CI);
3237a7e6055SDimitry Andric }
3247a7e6055SDimitry Andric 
removeLifetimeIntrinsicUsers(AllocaInst * AI)32517a519f9SDimitry Andric static void removeLifetimeIntrinsicUsers(AllocaInst *AI) {
32617a519f9SDimitry Andric   // Knowing that this alloca is promotable, we know that it's safe to kill all
32717a519f9SDimitry Andric   // instructions except for load and store.
32817a519f9SDimitry Andric 
32991bc56edSDimitry Andric   for (auto UI = AI->user_begin(), UE = AI->user_end(); UI != UE;) {
33017a519f9SDimitry Andric     Instruction *I = cast<Instruction>(*UI);
33117a519f9SDimitry Andric     ++UI;
33217a519f9SDimitry Andric     if (isa<LoadInst>(I) || isa<StoreInst>(I))
33317a519f9SDimitry Andric       continue;
33417a519f9SDimitry Andric 
33517a519f9SDimitry Andric     if (!I->getType()->isVoidTy()) {
33617a519f9SDimitry Andric       // The only users of this bitcast/GEP instruction are lifetime intrinsics.
33717a519f9SDimitry Andric       // Follow the use/def chain to erase them now instead of leaving it for
33817a519f9SDimitry Andric       // dead code elimination later.
33991bc56edSDimitry Andric       for (auto UUI = I->user_begin(), UUE = I->user_end(); UUI != UUE;) {
34091bc56edSDimitry Andric         Instruction *Inst = cast<Instruction>(*UUI);
34191bc56edSDimitry Andric         ++UUI;
34217a519f9SDimitry Andric         Inst->eraseFromParent();
34317a519f9SDimitry Andric       }
34417a519f9SDimitry Andric     }
34517a519f9SDimitry Andric     I->eraseFromParent();
34617a519f9SDimitry Andric   }
34717a519f9SDimitry Andric }
348f22ef01cSRoman Divacky 
3494ba319b5SDimitry Andric /// Rewrite as many loads as possible given a single store.
350f785676fSDimitry Andric ///
351f785676fSDimitry Andric /// When there is only a single store, we can use the domtree to trivially
352f785676fSDimitry Andric /// replace all of the dominated loads with the stored value. Do so, and return
353f785676fSDimitry Andric /// true if this has successfully promoted the alloca entirely. If this returns
354f785676fSDimitry Andric /// false there were some loads which were not dominated by the single store
355f785676fSDimitry Andric /// and thus must be phi-ed with undef. We fall back to the standard alloca
356f785676fSDimitry Andric /// promotion algorithm in that case.
rewriteSingleStoreAlloca(AllocaInst * AI,AllocaInfo & Info,LargeBlockInfo & LBI,const DataLayout & DL,DominatorTree & DT,AssumptionCache * AC)357f785676fSDimitry Andric static bool rewriteSingleStoreAlloca(AllocaInst *AI, AllocaInfo &Info,
3582cab237bSDimitry Andric                                      LargeBlockInfo &LBI, const DataLayout &DL,
3592cab237bSDimitry Andric                                      DominatorTree &DT, AssumptionCache *AC) {
360f785676fSDimitry Andric   StoreInst *OnlyStore = Info.OnlyStore;
361f785676fSDimitry Andric   bool StoringGlobalVal = !isa<Instruction>(OnlyStore->getOperand(0));
362f785676fSDimitry Andric   BasicBlock *StoreBB = OnlyStore->getParent();
363f785676fSDimitry Andric   int StoreIndex = -1;
364f785676fSDimitry Andric 
365f785676fSDimitry Andric   // Clear out UsingBlocks.  We will reconstruct it here if needed.
366f785676fSDimitry Andric   Info.UsingBlocks.clear();
367f785676fSDimitry Andric 
36891bc56edSDimitry Andric   for (auto UI = AI->user_begin(), E = AI->user_end(); UI != E;) {
369f785676fSDimitry Andric     Instruction *UserInst = cast<Instruction>(*UI++);
370f785676fSDimitry Andric     if (!isa<LoadInst>(UserInst)) {
371f785676fSDimitry Andric       assert(UserInst == OnlyStore && "Should only have load/stores");
372f785676fSDimitry Andric       continue;
373f785676fSDimitry Andric     }
374f785676fSDimitry Andric     LoadInst *LI = cast<LoadInst>(UserInst);
375f785676fSDimitry Andric 
376f785676fSDimitry Andric     // Okay, if we have a load from the alloca, we want to replace it with the
377f785676fSDimitry Andric     // only value stored to the alloca.  We can do this if the value is
378f785676fSDimitry Andric     // dominated by the store.  If not, we use the rest of the mem2reg machinery
379f785676fSDimitry Andric     // to insert the phi nodes as needed.
380f785676fSDimitry Andric     if (!StoringGlobalVal) { // Non-instructions are always dominated.
381f785676fSDimitry Andric       if (LI->getParent() == StoreBB) {
382f785676fSDimitry Andric         // If we have a use that is in the same block as the store, compare the
383f785676fSDimitry Andric         // indices of the two instructions to see which one came first.  If the
384f785676fSDimitry Andric         // load came before the store, we can't handle it.
385f785676fSDimitry Andric         if (StoreIndex == -1)
386f785676fSDimitry Andric           StoreIndex = LBI.getInstructionIndex(OnlyStore);
387f785676fSDimitry Andric 
388f785676fSDimitry Andric         if (unsigned(StoreIndex) > LBI.getInstructionIndex(LI)) {
389f785676fSDimitry Andric           // Can't handle this load, bail out.
390f785676fSDimitry Andric           Info.UsingBlocks.push_back(StoreBB);
391f785676fSDimitry Andric           continue;
392f785676fSDimitry Andric         }
393f785676fSDimitry Andric       } else if (LI->getParent() != StoreBB &&
394f785676fSDimitry Andric                  !DT.dominates(StoreBB, LI->getParent())) {
395f785676fSDimitry Andric         // If the load and store are in different blocks, use BB dominance to
396f785676fSDimitry Andric         // check their relationships.  If the store doesn't dom the use, bail
397f785676fSDimitry Andric         // out.
398f785676fSDimitry Andric         Info.UsingBlocks.push_back(LI->getParent());
399f785676fSDimitry Andric         continue;
400f785676fSDimitry Andric       }
401f785676fSDimitry Andric     }
402f785676fSDimitry Andric 
403f785676fSDimitry Andric     // Otherwise, we *can* safely rewrite this load.
404f785676fSDimitry Andric     Value *ReplVal = OnlyStore->getOperand(0);
405f785676fSDimitry Andric     // If the replacement value is the load, this must occur in unreachable
406f785676fSDimitry Andric     // code.
407f785676fSDimitry Andric     if (ReplVal == LI)
408f785676fSDimitry Andric       ReplVal = UndefValue::get(LI->getType());
4097a7e6055SDimitry Andric 
4107a7e6055SDimitry Andric     // If the load was marked as nonnull we don't want to lose
4117a7e6055SDimitry Andric     // that information when we erase this Load. So we preserve
4127a7e6055SDimitry Andric     // it with an assume.
4137a7e6055SDimitry Andric     if (AC && LI->getMetadata(LLVMContext::MD_nonnull) &&
4142cab237bSDimitry Andric         !isKnownNonZero(ReplVal, DL, 0, AC, LI, &DT))
4157a7e6055SDimitry Andric       addAssumeNonNull(AC, LI);
4167a7e6055SDimitry Andric 
417f785676fSDimitry Andric     LI->replaceAllUsesWith(ReplVal);
418f785676fSDimitry Andric     LI->eraseFromParent();
419f785676fSDimitry Andric     LBI.deleteValue(LI);
420f785676fSDimitry Andric   }
421f785676fSDimitry Andric 
422f785676fSDimitry Andric   // Finally, after the scan, check to see if the store is all that is left.
423f785676fSDimitry Andric   if (!Info.UsingBlocks.empty())
424f785676fSDimitry Andric     return false; // If not, we'll have to fall back for the remainder.
425f785676fSDimitry Andric 
426f785676fSDimitry Andric   // Record debuginfo for the store and remove the declaration's
427f785676fSDimitry Andric   // debuginfo.
428*b5893f02SDimitry Andric   for (DbgVariableIntrinsic *DII : Info.DbgDeclares) {
4297d523365SDimitry Andric     DIBuilder DIB(*AI->getModule(), /*AllowUnresolved*/ false);
4302cab237bSDimitry Andric     ConvertDebugDeclareToDebugValue(DII, Info.OnlyStore, DIB);
4312cab237bSDimitry Andric     DII->eraseFromParent();
4322cab237bSDimitry Andric     LBI.deleteValue(DII);
433f785676fSDimitry Andric   }
434f785676fSDimitry Andric   // Remove the (now dead) store and alloca.
435f785676fSDimitry Andric   Info.OnlyStore->eraseFromParent();
436f785676fSDimitry Andric   LBI.deleteValue(Info.OnlyStore);
437f785676fSDimitry Andric 
438f785676fSDimitry Andric   AI->eraseFromParent();
439f785676fSDimitry Andric   LBI.deleteValue(AI);
440f785676fSDimitry Andric   return true;
441f785676fSDimitry Andric }
442f785676fSDimitry Andric 
443f785676fSDimitry Andric /// Many allocas are only used within a single basic block.  If this is the
444f785676fSDimitry Andric /// case, avoid traversing the CFG and inserting a lot of potentially useless
445f785676fSDimitry Andric /// PHI nodes by just performing a single linear pass over the basic block
446f785676fSDimitry Andric /// using the Alloca.
447f785676fSDimitry Andric ///
448f785676fSDimitry Andric /// If we cannot promote this alloca (because it is read before it is written),
4497d523365SDimitry Andric /// return false.  This is necessary in cases where, due to control flow, the
4507d523365SDimitry Andric /// alloca is undefined only on some control flow paths.  e.g. code like
4517d523365SDimitry Andric /// this is correct in LLVM IR:
4527d523365SDimitry Andric ///  // A is an alloca with no stores so far
4537d523365SDimitry Andric ///  for (...) {
4547d523365SDimitry Andric ///    int t = *A;
4557d523365SDimitry Andric ///    if (!first_iteration)
4567d523365SDimitry Andric ///      use(t);
4577d523365SDimitry Andric ///    *A = 42;
4587d523365SDimitry Andric ///  }
promoteSingleBlockAlloca(AllocaInst * AI,const AllocaInfo & Info,LargeBlockInfo & LBI,const DataLayout & DL,DominatorTree & DT,AssumptionCache * AC)4597d523365SDimitry Andric static bool promoteSingleBlockAlloca(AllocaInst *AI, const AllocaInfo &Info,
460f785676fSDimitry Andric                                      LargeBlockInfo &LBI,
4612cab237bSDimitry Andric                                      const DataLayout &DL,
4627a7e6055SDimitry Andric                                      DominatorTree &DT,
4637a7e6055SDimitry Andric                                      AssumptionCache *AC) {
464f785676fSDimitry Andric   // The trickiest case to handle is when we have large blocks. Because of this,
465f785676fSDimitry Andric   // this code is optimized assuming that large blocks happen.  This does not
466f785676fSDimitry Andric   // significantly pessimize the small block case.  This uses LargeBlockInfo to
467f785676fSDimitry Andric   // make it efficient to get the index of various operations in the block.
468f785676fSDimitry Andric 
469f785676fSDimitry Andric   // Walk the use-def list of the alloca, getting the locations of all stores.
4702cab237bSDimitry Andric   using StoresByIndexTy = SmallVector<std::pair<unsigned, StoreInst *>, 64>;
471f785676fSDimitry Andric   StoresByIndexTy StoresByIndex;
472f785676fSDimitry Andric 
47391bc56edSDimitry Andric   for (User *U : AI->users())
47491bc56edSDimitry Andric     if (StoreInst *SI = dyn_cast<StoreInst>(U))
475f785676fSDimitry Andric       StoresByIndex.push_back(std::make_pair(LBI.getInstructionIndex(SI), SI));
476f785676fSDimitry Andric 
477f785676fSDimitry Andric   // Sort the stores by their index, making it efficient to do a lookup with a
478f785676fSDimitry Andric   // binary search.
479*b5893f02SDimitry Andric   llvm::sort(StoresByIndex, less_first());
480f785676fSDimitry Andric 
481f785676fSDimitry Andric   // Walk all of the loads from this alloca, replacing them with the nearest
482f785676fSDimitry Andric   // store above them, if any.
48391bc56edSDimitry Andric   for (auto UI = AI->user_begin(), E = AI->user_end(); UI != E;) {
484f785676fSDimitry Andric     LoadInst *LI = dyn_cast<LoadInst>(*UI++);
485f785676fSDimitry Andric     if (!LI)
486f785676fSDimitry Andric       continue;
487f785676fSDimitry Andric 
488f785676fSDimitry Andric     unsigned LoadIdx = LBI.getInstructionIndex(LI);
489f785676fSDimitry Andric 
490f785676fSDimitry Andric     // Find the nearest store that has a lower index than this load.
491f785676fSDimitry Andric     StoresByIndexTy::iterator I =
492f785676fSDimitry Andric         std::lower_bound(StoresByIndex.begin(), StoresByIndex.end(),
49391bc56edSDimitry Andric                          std::make_pair(LoadIdx,
49491bc56edSDimitry Andric                                         static_cast<StoreInst *>(nullptr)),
495f785676fSDimitry Andric                          less_first());
4967d523365SDimitry Andric     if (I == StoresByIndex.begin()) {
4977d523365SDimitry Andric       if (StoresByIndex.empty())
4987d523365SDimitry Andric         // If there are no stores, the load takes the undef value.
499f785676fSDimitry Andric         LI->replaceAllUsesWith(UndefValue::get(LI->getType()));
500f785676fSDimitry Andric       else
5017d523365SDimitry Andric         // There is no store before this load, bail out (load may be affected
5027d523365SDimitry Andric         // by the following stores - see main comment).
5037d523365SDimitry Andric         return false;
5047a7e6055SDimitry Andric     } else {
505f785676fSDimitry Andric       // Otherwise, there was a store before this load, the load takes its value.
5067a7e6055SDimitry Andric       // Note, if the load was marked as nonnull we don't want to lose that
5077a7e6055SDimitry Andric       // information when we erase it. So we preserve it with an assume.
5087a7e6055SDimitry Andric       Value *ReplVal = std::prev(I)->second->getOperand(0);
5097a7e6055SDimitry Andric       if (AC && LI->getMetadata(LLVMContext::MD_nonnull) &&
5102cab237bSDimitry Andric           !isKnownNonZero(ReplVal, DL, 0, AC, LI, &DT))
5117a7e6055SDimitry Andric         addAssumeNonNull(AC, LI);
512f785676fSDimitry Andric 
5134ba319b5SDimitry Andric       // If the replacement value is the load, this must occur in unreachable
5144ba319b5SDimitry Andric       // code.
5154ba319b5SDimitry Andric       if (ReplVal == LI)
5164ba319b5SDimitry Andric         ReplVal = UndefValue::get(LI->getType());
5174ba319b5SDimitry Andric 
5187a7e6055SDimitry Andric       LI->replaceAllUsesWith(ReplVal);
5197a7e6055SDimitry Andric     }
5207a7e6055SDimitry Andric 
521f785676fSDimitry Andric     LI->eraseFromParent();
522f785676fSDimitry Andric     LBI.deleteValue(LI);
523f785676fSDimitry Andric   }
524f785676fSDimitry Andric 
525f785676fSDimitry Andric   // Remove the (now dead) stores and alloca.
526f785676fSDimitry Andric   while (!AI->use_empty()) {
52791bc56edSDimitry Andric     StoreInst *SI = cast<StoreInst>(AI->user_back());
528f785676fSDimitry Andric     // Record debuginfo for the store before removing it.
529*b5893f02SDimitry Andric     for (DbgVariableIntrinsic *DII : Info.DbgDeclares) {
5307d523365SDimitry Andric       DIBuilder DIB(*AI->getModule(), /*AllowUnresolved*/ false);
5312cab237bSDimitry Andric       ConvertDebugDeclareToDebugValue(DII, SI, DIB);
532f785676fSDimitry Andric     }
533f785676fSDimitry Andric     SI->eraseFromParent();
534f785676fSDimitry Andric     LBI.deleteValue(SI);
535f785676fSDimitry Andric   }
536f785676fSDimitry Andric 
537f785676fSDimitry Andric   AI->eraseFromParent();
538f785676fSDimitry Andric   LBI.deleteValue(AI);
539f785676fSDimitry Andric 
540f785676fSDimitry Andric   // The alloca's debuginfo can be removed as well.
541*b5893f02SDimitry Andric   for (DbgVariableIntrinsic *DII : Info.DbgDeclares) {
5422cab237bSDimitry Andric     DII->eraseFromParent();
5432cab237bSDimitry Andric     LBI.deleteValue(DII);
544f785676fSDimitry Andric   }
545f785676fSDimitry Andric 
546f785676fSDimitry Andric   ++NumLocalPromoted;
5477d523365SDimitry Andric   return true;
548f785676fSDimitry Andric }
549f785676fSDimitry Andric 
run()550f22ef01cSRoman Divacky void PromoteMem2Reg::run() {
5512754fe60SDimitry Andric   Function &F = *DT.getRoot()->getParent();
552f22ef01cSRoman Divacky 
553f22ef01cSRoman Divacky   AllocaDbgDeclares.resize(Allocas.size());
554f22ef01cSRoman Divacky 
555f22ef01cSRoman Divacky   AllocaInfo Info;
556f22ef01cSRoman Divacky   LargeBlockInfo LBI;
5573ca95b02SDimitry Andric   ForwardIDFCalculator IDF(DT);
558f22ef01cSRoman Divacky 
559f22ef01cSRoman Divacky   for (unsigned AllocaNum = 0; AllocaNum != Allocas.size(); ++AllocaNum) {
560f22ef01cSRoman Divacky     AllocaInst *AI = Allocas[AllocaNum];
561f22ef01cSRoman Divacky 
562f785676fSDimitry Andric     assert(isAllocaPromotable(AI) && "Cannot promote non-promotable alloca!");
563f22ef01cSRoman Divacky     assert(AI->getParent()->getParent() == &F &&
564f22ef01cSRoman Divacky            "All allocas should be in the same function, which is same as DF!");
565f22ef01cSRoman Divacky 
56617a519f9SDimitry Andric     removeLifetimeIntrinsicUsers(AI);
56717a519f9SDimitry Andric 
568f22ef01cSRoman Divacky     if (AI->use_empty()) {
569f22ef01cSRoman Divacky       // If there are no uses of the alloca, just delete it now.
570f22ef01cSRoman Divacky       AI->eraseFromParent();
571f22ef01cSRoman Divacky 
572f22ef01cSRoman Divacky       // Remove the alloca from the Allocas list, since it has been processed
573f22ef01cSRoman Divacky       RemoveFromAllocasList(AllocaNum);
574f22ef01cSRoman Divacky       ++NumDeadAlloca;
575f22ef01cSRoman Divacky       continue;
576f22ef01cSRoman Divacky     }
577f22ef01cSRoman Divacky 
578f22ef01cSRoman Divacky     // Calculate the set of read and write-locations for each alloca.  This is
579f22ef01cSRoman Divacky     // analogous to finding the 'uses' and 'definitions' of each variable.
580f22ef01cSRoman Divacky     Info.AnalyzeAlloca(AI);
581f22ef01cSRoman Divacky 
582f22ef01cSRoman Divacky     // If there is only a single store to this value, replace any loads of
583f22ef01cSRoman Divacky     // it that are directly dominated by the definition with the value stored.
584f22ef01cSRoman Divacky     if (Info.DefiningBlocks.size() == 1) {
5852cab237bSDimitry Andric       if (rewriteSingleStoreAlloca(AI, Info, LBI, SQ.DL, DT, AC)) {
586f22ef01cSRoman Divacky         // The alloca has been processed, move on.
587f22ef01cSRoman Divacky         RemoveFromAllocasList(AllocaNum);
588f22ef01cSRoman Divacky         ++NumSingleStore;
589f22ef01cSRoman Divacky         continue;
590f22ef01cSRoman Divacky       }
591f22ef01cSRoman Divacky     }
592f22ef01cSRoman Divacky 
593f22ef01cSRoman Divacky     // If the alloca is only read and written in one basic block, just perform a
594f22ef01cSRoman Divacky     // linear sweep over the block to eliminate it.
5957d523365SDimitry Andric     if (Info.OnlyUsedInOneBlock &&
5962cab237bSDimitry Andric         promoteSingleBlockAlloca(AI, Info, LBI, SQ.DL, DT, AC)) {
597f22ef01cSRoman Divacky       // The alloca has been processed, move on.
598f22ef01cSRoman Divacky       RemoveFromAllocasList(AllocaNum);
599f22ef01cSRoman Divacky       continue;
600f22ef01cSRoman Divacky     }
601f22ef01cSRoman Divacky 
602f22ef01cSRoman Divacky     // If we haven't computed a numbering for the BB's in the function, do so
603f22ef01cSRoman Divacky     // now.
604f22ef01cSRoman Divacky     if (BBNumbers.empty()) {
605f22ef01cSRoman Divacky       unsigned ID = 0;
606ff0cc061SDimitry Andric       for (auto &BB : F)
607ff0cc061SDimitry Andric         BBNumbers[&BB] = ID++;
608f22ef01cSRoman Divacky     }
609f22ef01cSRoman Divacky 
610f22ef01cSRoman Divacky     // Remember the dbg.declare intrinsic describing this alloca, if any.
6112cab237bSDimitry Andric     if (!Info.DbgDeclares.empty())
6122cab237bSDimitry Andric       AllocaDbgDeclares[AllocaNum] = Info.DbgDeclares;
613f22ef01cSRoman Divacky 
614f22ef01cSRoman Divacky     // Keep the reverse mapping of the 'Allocas' array for the rename pass.
615f22ef01cSRoman Divacky     AllocaLookup[Allocas[AllocaNum]] = AllocaNum;
616f22ef01cSRoman Divacky 
617f22ef01cSRoman Divacky     // At this point, we're committed to promoting the alloca using IDF's, and
618f22ef01cSRoman Divacky     // the standard SSA construction algorithm.  Determine which blocks need PHI
619f22ef01cSRoman Divacky     // nodes and see if we can optimize out some work by avoiding insertion of
620f22ef01cSRoman Divacky     // dead phi nodes.
621ff0cc061SDimitry Andric 
622ff0cc061SDimitry Andric     // Unique the set of defining blocks for efficient lookup.
623ff0cc061SDimitry Andric     SmallPtrSet<BasicBlock *, 32> DefBlocks;
624ff0cc061SDimitry Andric     DefBlocks.insert(Info.DefiningBlocks.begin(), Info.DefiningBlocks.end());
625ff0cc061SDimitry Andric 
626ff0cc061SDimitry Andric     // Determine which blocks the value is live in.  These are blocks which lead
627ff0cc061SDimitry Andric     // to uses.
628ff0cc061SDimitry Andric     SmallPtrSet<BasicBlock *, 32> LiveInBlocks;
629ff0cc061SDimitry Andric     ComputeLiveInBlocks(AI, Info, DefBlocks, LiveInBlocks);
630ff0cc061SDimitry Andric 
631ff0cc061SDimitry Andric     // At this point, we're committed to promoting the alloca using IDF's, and
632ff0cc061SDimitry Andric     // the standard SSA construction algorithm.  Determine which blocks need phi
633ff0cc061SDimitry Andric     // nodes and see if we can optimize out some work by avoiding insertion of
634ff0cc061SDimitry Andric     // dead phi nodes.
635ff0cc061SDimitry Andric     IDF.setLiveInBlocks(LiveInBlocks);
636ff0cc061SDimitry Andric     IDF.setDefiningBlocks(DefBlocks);
637ff0cc061SDimitry Andric     SmallVector<BasicBlock *, 32> PHIBlocks;
638ff0cc061SDimitry Andric     IDF.calculate(PHIBlocks);
639ff0cc061SDimitry Andric     if (PHIBlocks.size() > 1)
640*b5893f02SDimitry Andric       llvm::sort(PHIBlocks, [this](BasicBlock *A, BasicBlock *B) {
641ff0cc061SDimitry Andric         return BBNumbers.lookup(A) < BBNumbers.lookup(B);
642ff0cc061SDimitry Andric       });
643ff0cc061SDimitry Andric 
644ff0cc061SDimitry Andric     unsigned CurrentVersion = 0;
6452cab237bSDimitry Andric     for (BasicBlock *BB : PHIBlocks)
6462cab237bSDimitry Andric       QueuePhiNode(BB, AllocaNum, CurrentVersion);
647f22ef01cSRoman Divacky   }
648f22ef01cSRoman Divacky 
649f22ef01cSRoman Divacky   if (Allocas.empty())
650f22ef01cSRoman Divacky     return; // All of the allocas must have been trivial!
651f22ef01cSRoman Divacky 
652f22ef01cSRoman Divacky   LBI.clear();
653f22ef01cSRoman Divacky 
654f22ef01cSRoman Divacky   // Set the incoming values for the basic block to be null values for all of
655f22ef01cSRoman Divacky   // the alloca's.  We do this in case there is a load of a value that has not
656f22ef01cSRoman Divacky   // been stored yet.  In this case, it will get this null value.
657f22ef01cSRoman Divacky   RenamePassData::ValVector Values(Allocas.size());
658f22ef01cSRoman Divacky   for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
659f22ef01cSRoman Divacky     Values[i] = UndefValue::get(Allocas[i]->getAllocatedType());
660f22ef01cSRoman Divacky 
6614ba319b5SDimitry Andric   // When handling debug info, treat all incoming values as if they have unknown
6624ba319b5SDimitry Andric   // locations until proven otherwise.
6634ba319b5SDimitry Andric   RenamePassData::LocationVector Locations(Allocas.size());
6644ba319b5SDimitry Andric 
665f22ef01cSRoman Divacky   // Walks all basic blocks in the function performing the SSA rename algorithm
666f22ef01cSRoman Divacky   // and inserting the phi nodes we marked as necessary
667f22ef01cSRoman Divacky   std::vector<RenamePassData> RenamePassWorkList;
6684ba319b5SDimitry Andric   RenamePassWorkList.emplace_back(&F.front(), nullptr, std::move(Values),
6694ba319b5SDimitry Andric                                   std::move(Locations));
670f22ef01cSRoman Divacky   do {
6712cab237bSDimitry Andric     RenamePassData RPD = std::move(RenamePassWorkList.back());
672f22ef01cSRoman Divacky     RenamePassWorkList.pop_back();
673f22ef01cSRoman Divacky     // RenamePass may add new worklist entries.
6744ba319b5SDimitry Andric     RenamePass(RPD.BB, RPD.Pred, RPD.Values, RPD.Locations, RenamePassWorkList);
675f22ef01cSRoman Divacky   } while (!RenamePassWorkList.empty());
676f22ef01cSRoman Divacky 
677f22ef01cSRoman Divacky   // The renamer uses the Visited set to avoid infinite loops.  Clear it now.
678f22ef01cSRoman Divacky   Visited.clear();
679f22ef01cSRoman Divacky 
680f22ef01cSRoman Divacky   // Remove the allocas themselves from the function.
6812cab237bSDimitry Andric   for (Instruction *A : Allocas) {
682f22ef01cSRoman Divacky     // If there are any uses of the alloca instructions left, they must be in
6832754fe60SDimitry Andric     // unreachable basic blocks that were not processed by walking the dominator
6842754fe60SDimitry Andric     // tree. Just delete the users now.
685f22ef01cSRoman Divacky     if (!A->use_empty())
686f22ef01cSRoman Divacky       A->replaceAllUsesWith(UndefValue::get(A->getType()));
687f22ef01cSRoman Divacky     A->eraseFromParent();
688f22ef01cSRoman Divacky   }
689f22ef01cSRoman Divacky 
690f22ef01cSRoman Divacky   // Remove alloca's dbg.declare instrinsics from the function.
6912cab237bSDimitry Andric   for (auto &Declares : AllocaDbgDeclares)
6922cab237bSDimitry Andric     for (auto *DII : Declares)
6932cab237bSDimitry Andric       DII->eraseFromParent();
694f22ef01cSRoman Divacky 
695f22ef01cSRoman Divacky   // Loop over all of the PHI nodes and see if there are any that we can get
696f22ef01cSRoman Divacky   // rid of because they merge all of the same incoming values.  This can
697f22ef01cSRoman Divacky   // happen due to undef values coming into the PHI nodes.  This process is
698f22ef01cSRoman Divacky   // iterative, because eliminating one PHI node can cause others to be removed.
699f22ef01cSRoman Divacky   bool EliminatedAPHI = true;
700f22ef01cSRoman Divacky   while (EliminatedAPHI) {
701f22ef01cSRoman Divacky     EliminatedAPHI = false;
702f22ef01cSRoman Divacky 
7033861d79fSDimitry Andric     // Iterating over NewPhiNodes is deterministic, so it is safe to try to
7043861d79fSDimitry Andric     // simplify and RAUW them as we go.  If it was not, we could add uses to
70591bc56edSDimitry Andric     // the values we replace with in a non-deterministic order, thus creating
70691bc56edSDimitry Andric     // non-deterministic def->use chains.
707f785676fSDimitry Andric     for (DenseMap<std::pair<unsigned, unsigned>, PHINode *>::iterator
708f785676fSDimitry Andric              I = NewPhiNodes.begin(),
709f785676fSDimitry Andric              E = NewPhiNodes.end();
710f785676fSDimitry Andric          I != E;) {
711f22ef01cSRoman Divacky       PHINode *PN = I->second;
712f22ef01cSRoman Divacky 
713f22ef01cSRoman Divacky       // If this PHI node merges one value and/or undefs, get the value.
714f37b6182SDimitry Andric       if (Value *V = SimplifyInstruction(PN, SQ)) {
715f22ef01cSRoman Divacky         PN->replaceAllUsesWith(V);
716f22ef01cSRoman Divacky         PN->eraseFromParent();
717f22ef01cSRoman Divacky         NewPhiNodes.erase(I++);
718f22ef01cSRoman Divacky         EliminatedAPHI = true;
719f22ef01cSRoman Divacky         continue;
720f22ef01cSRoman Divacky       }
721f22ef01cSRoman Divacky       ++I;
722f22ef01cSRoman Divacky     }
723f22ef01cSRoman Divacky   }
724f22ef01cSRoman Divacky 
725f22ef01cSRoman Divacky   // At this point, the renamer has added entries to PHI nodes for all reachable
726f22ef01cSRoman Divacky   // code.  Unfortunately, there may be unreachable blocks which the renamer
727f22ef01cSRoman Divacky   // hasn't traversed.  If this is the case, the PHI nodes may not
728f22ef01cSRoman Divacky   // have incoming values for all predecessors.  Loop over all PHI nodes we have
729f22ef01cSRoman Divacky   // created, inserting undef values if they are missing any incoming values.
730f785676fSDimitry Andric   for (DenseMap<std::pair<unsigned, unsigned>, PHINode *>::iterator
731f785676fSDimitry Andric            I = NewPhiNodes.begin(),
732f785676fSDimitry Andric            E = NewPhiNodes.end();
733f785676fSDimitry Andric        I != E; ++I) {
734f22ef01cSRoman Divacky     // We want to do this once per basic block.  As such, only process a block
735f22ef01cSRoman Divacky     // when we find the PHI that is the first entry in the block.
736f22ef01cSRoman Divacky     PHINode *SomePHI = I->second;
737f22ef01cSRoman Divacky     BasicBlock *BB = SomePHI->getParent();
738f22ef01cSRoman Divacky     if (&BB->front() != SomePHI)
739f22ef01cSRoman Divacky       continue;
740f22ef01cSRoman Divacky 
741f22ef01cSRoman Divacky     // Only do work here if there the PHI nodes are missing incoming values.  We
742f22ef01cSRoman Divacky     // know that all PHI nodes that were inserted in a block will have the same
743f22ef01cSRoman Divacky     // number of incoming values, so we can just check any of them.
744f22ef01cSRoman Divacky     if (SomePHI->getNumIncomingValues() == getNumPreds(BB))
745f22ef01cSRoman Divacky       continue;
746f22ef01cSRoman Divacky 
747f22ef01cSRoman Divacky     // Get the preds for BB.
748f22ef01cSRoman Divacky     SmallVector<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB));
749f22ef01cSRoman Divacky 
750f22ef01cSRoman Divacky     // Ok, now we know that all of the PHI nodes are missing entries for some
751f22ef01cSRoman Divacky     // basic blocks.  Start by sorting the incoming predecessors for efficient
752f22ef01cSRoman Divacky     // access.
753*b5893f02SDimitry Andric     auto CompareBBNumbers = [this](BasicBlock *A, BasicBlock *B) {
754*b5893f02SDimitry Andric       return BBNumbers.lookup(A) < BBNumbers.lookup(B);
755*b5893f02SDimitry Andric     };
756*b5893f02SDimitry Andric     llvm::sort(Preds, CompareBBNumbers);
757f22ef01cSRoman Divacky 
758f22ef01cSRoman Divacky     // Now we loop through all BB's which have entries in SomePHI and remove
759f22ef01cSRoman Divacky     // them from the Preds list.
760f22ef01cSRoman Divacky     for (unsigned i = 0, e = SomePHI->getNumIncomingValues(); i != e; ++i) {
761f22ef01cSRoman Divacky       // Do a log(n) search of the Preds list for the entry we want.
762f785676fSDimitry Andric       SmallVectorImpl<BasicBlock *>::iterator EntIt = std::lower_bound(
763*b5893f02SDimitry Andric           Preds.begin(), Preds.end(), SomePHI->getIncomingBlock(i),
764*b5893f02SDimitry Andric           CompareBBNumbers);
765f22ef01cSRoman Divacky       assert(EntIt != Preds.end() && *EntIt == SomePHI->getIncomingBlock(i) &&
766f22ef01cSRoman Divacky              "PHI node has entry for a block which is not a predecessor!");
767f22ef01cSRoman Divacky 
768f22ef01cSRoman Divacky       // Remove the entry
769f22ef01cSRoman Divacky       Preds.erase(EntIt);
770f22ef01cSRoman Divacky     }
771f22ef01cSRoman Divacky 
772f22ef01cSRoman Divacky     // At this point, the blocks left in the preds list must have dummy
773f22ef01cSRoman Divacky     // entries inserted into every PHI nodes for the block.  Update all the phi
774f22ef01cSRoman Divacky     // nodes in this block that we are inserting (there could be phis before
775f22ef01cSRoman Divacky     // mem2reg runs).
776f22ef01cSRoman Divacky     unsigned NumBadPreds = SomePHI->getNumIncomingValues();
777f22ef01cSRoman Divacky     BasicBlock::iterator BBI = BB->begin();
778f22ef01cSRoman Divacky     while ((SomePHI = dyn_cast<PHINode>(BBI++)) &&
779f22ef01cSRoman Divacky            SomePHI->getNumIncomingValues() == NumBadPreds) {
780f22ef01cSRoman Divacky       Value *UndefVal = UndefValue::get(SomePHI->getType());
7812cab237bSDimitry Andric       for (BasicBlock *Pred : Preds)
7822cab237bSDimitry Andric         SomePHI->addIncoming(UndefVal, Pred);
783f22ef01cSRoman Divacky     }
784f22ef01cSRoman Divacky   }
785f22ef01cSRoman Divacky 
786f22ef01cSRoman Divacky   NewPhiNodes.clear();
787f22ef01cSRoman Divacky }
788f22ef01cSRoman Divacky 
7894ba319b5SDimitry Andric /// Determine which blocks the value is live in.
790f785676fSDimitry Andric ///
791f785676fSDimitry Andric /// These are blocks which lead to uses.  Knowing this allows us to avoid
792f785676fSDimitry Andric /// inserting PHI nodes into blocks which don't lead to uses (thus, the
793f785676fSDimitry Andric /// inserted phi nodes would be dead).
ComputeLiveInBlocks(AllocaInst * AI,AllocaInfo & Info,const SmallPtrSetImpl<BasicBlock * > & DefBlocks,SmallPtrSetImpl<BasicBlock * > & LiveInBlocks)794f785676fSDimitry Andric void PromoteMem2Reg::ComputeLiveInBlocks(
795f785676fSDimitry Andric     AllocaInst *AI, AllocaInfo &Info,
79639d628a0SDimitry Andric     const SmallPtrSetImpl<BasicBlock *> &DefBlocks,
79739d628a0SDimitry Andric     SmallPtrSetImpl<BasicBlock *> &LiveInBlocks) {
798f22ef01cSRoman Divacky   // To determine liveness, we must iterate through the predecessors of blocks
799f22ef01cSRoman Divacky   // where the def is live.  Blocks are added to the worklist if we need to
800f22ef01cSRoman Divacky   // check their predecessors.  Start with all the using blocks.
801ffd1746dSEd Schouten   SmallVector<BasicBlock *, 64> LiveInBlockWorklist(Info.UsingBlocks.begin(),
802ffd1746dSEd Schouten                                                     Info.UsingBlocks.end());
803f22ef01cSRoman Divacky 
804f22ef01cSRoman Divacky   // If any of the using blocks is also a definition block, check to see if the
805f22ef01cSRoman Divacky   // definition occurs before or after the use.  If it happens before the use,
806f22ef01cSRoman Divacky   // the value isn't really live-in.
807f22ef01cSRoman Divacky   for (unsigned i = 0, e = LiveInBlockWorklist.size(); i != e; ++i) {
808f22ef01cSRoman Divacky     BasicBlock *BB = LiveInBlockWorklist[i];
809f785676fSDimitry Andric     if (!DefBlocks.count(BB))
810f785676fSDimitry Andric       continue;
811f22ef01cSRoman Divacky 
812f22ef01cSRoman Divacky     // Okay, this is a block that both uses and defines the value.  If the first
813f22ef01cSRoman Divacky     // reference to the alloca is a def (store), then we know it isn't live-in.
814f22ef01cSRoman Divacky     for (BasicBlock::iterator I = BB->begin();; ++I) {
815f22ef01cSRoman Divacky       if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
816f785676fSDimitry Andric         if (SI->getOperand(1) != AI)
817f785676fSDimitry Andric           continue;
818f22ef01cSRoman Divacky 
819f22ef01cSRoman Divacky         // We found a store to the alloca before a load.  The alloca is not
820f22ef01cSRoman Divacky         // actually live-in here.
821f22ef01cSRoman Divacky         LiveInBlockWorklist[i] = LiveInBlockWorklist.back();
822f22ef01cSRoman Divacky         LiveInBlockWorklist.pop_back();
8233ca95b02SDimitry Andric         --i;
8243ca95b02SDimitry Andric         --e;
825f22ef01cSRoman Divacky         break;
826f22ef01cSRoman Divacky       }
827f22ef01cSRoman Divacky 
828f22ef01cSRoman Divacky       if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
829f785676fSDimitry Andric         if (LI->getOperand(0) != AI)
830f785676fSDimitry Andric           continue;
831f22ef01cSRoman Divacky 
832f22ef01cSRoman Divacky         // Okay, we found a load before a store to the alloca.  It is actually
833f22ef01cSRoman Divacky         // live into this block.
834f22ef01cSRoman Divacky         break;
835f22ef01cSRoman Divacky       }
836f22ef01cSRoman Divacky     }
837f22ef01cSRoman Divacky   }
838f22ef01cSRoman Divacky 
839f22ef01cSRoman Divacky   // Now that we have a set of blocks where the phi is live-in, recursively add
840f22ef01cSRoman Divacky   // their predecessors until we find the full region the value is live.
841f22ef01cSRoman Divacky   while (!LiveInBlockWorklist.empty()) {
842f22ef01cSRoman Divacky     BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
843f22ef01cSRoman Divacky 
844f22ef01cSRoman Divacky     // The block really is live in here, insert it into the set.  If already in
845f22ef01cSRoman Divacky     // the set, then it has already been processed.
84639d628a0SDimitry Andric     if (!LiveInBlocks.insert(BB).second)
847f22ef01cSRoman Divacky       continue;
848f22ef01cSRoman Divacky 
849f22ef01cSRoman Divacky     // Since the value is live into BB, it is either defined in a predecessor or
850f22ef01cSRoman Divacky     // live into it to.  Add the preds to the worklist unless they are a
851f22ef01cSRoman Divacky     // defining block.
8522cab237bSDimitry Andric     for (BasicBlock *P : predecessors(BB)) {
853f22ef01cSRoman Divacky       // The value is not live into a predecessor if it defines the value.
854f22ef01cSRoman Divacky       if (DefBlocks.count(P))
855f22ef01cSRoman Divacky         continue;
856f22ef01cSRoman Divacky 
857f22ef01cSRoman Divacky       // Otherwise it is, add to the worklist.
858f22ef01cSRoman Divacky       LiveInBlockWorklist.push_back(P);
859f22ef01cSRoman Divacky     }
860f22ef01cSRoman Divacky   }
861f22ef01cSRoman Divacky }
862f22ef01cSRoman Divacky 
8634ba319b5SDimitry Andric /// Queue a phi-node to be added to a basic-block for a specific Alloca.
864f22ef01cSRoman Divacky ///
865f785676fSDimitry Andric /// Returns true if there wasn't already a phi-node for that variable
QueuePhiNode(BasicBlock * BB,unsigned AllocaNo,unsigned & Version)866f22ef01cSRoman Divacky bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo,
8672754fe60SDimitry Andric                                   unsigned &Version) {
868f22ef01cSRoman Divacky   // Look up the basic-block in question.
8693861d79fSDimitry Andric   PHINode *&PN = NewPhiNodes[std::make_pair(BBNumbers[BB], AllocaNo)];
870f22ef01cSRoman Divacky 
871f22ef01cSRoman Divacky   // If the BB already has a phi node added for the i'th alloca then we're done!
872f785676fSDimitry Andric   if (PN)
873f785676fSDimitry Andric     return false;
874f22ef01cSRoman Divacky 
875f22ef01cSRoman Divacky   // Create a PhiNode using the dereferenced type... and add the phi-node to the
876f22ef01cSRoman Divacky   // BasicBlock.
8773b0f4066SDimitry Andric   PN = PHINode::Create(Allocas[AllocaNo]->getAllocatedType(), getNumPreds(BB),
878f22ef01cSRoman Divacky                        Allocas[AllocaNo]->getName() + "." + Twine(Version++),
8797d523365SDimitry Andric                        &BB->front());
880f22ef01cSRoman Divacky   ++NumPHIInsert;
881f22ef01cSRoman Divacky   PhiToAllocaMap[PN] = AllocaNo;
882f22ef01cSRoman Divacky   return true;
883f22ef01cSRoman Divacky }
884f22ef01cSRoman Divacky 
8854ba319b5SDimitry Andric /// Update the debug location of a phi. \p ApplyMergedLoc indicates whether to
8864ba319b5SDimitry Andric /// create a merged location incorporating \p DL, or to set \p DL directly.
updateForIncomingValueLocation(PHINode * PN,DebugLoc DL,bool ApplyMergedLoc)8874ba319b5SDimitry Andric static void updateForIncomingValueLocation(PHINode *PN, DebugLoc DL,
8884ba319b5SDimitry Andric                                            bool ApplyMergedLoc) {
8894ba319b5SDimitry Andric   if (ApplyMergedLoc)
8904ba319b5SDimitry Andric     PN->applyMergedLocation(PN->getDebugLoc(), DL);
8914ba319b5SDimitry Andric   else
8924ba319b5SDimitry Andric     PN->setDebugLoc(DL);
8934ba319b5SDimitry Andric }
8944ba319b5SDimitry Andric 
8954ba319b5SDimitry Andric /// Recursively traverse the CFG of the function, renaming loads and
896f785676fSDimitry Andric /// stores to the allocas which we are promoting.
897f785676fSDimitry Andric ///
898f785676fSDimitry Andric /// IncomingVals indicates what value each Alloca contains on exit from the
899f785676fSDimitry Andric /// predecessor block Pred.
RenamePass(BasicBlock * BB,BasicBlock * Pred,RenamePassData::ValVector & IncomingVals,RenamePassData::LocationVector & IncomingLocs,std::vector<RenamePassData> & Worklist)900f22ef01cSRoman Divacky void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
901f22ef01cSRoman Divacky                                 RenamePassData::ValVector &IncomingVals,
9024ba319b5SDimitry Andric                                 RenamePassData::LocationVector &IncomingLocs,
903f22ef01cSRoman Divacky                                 std::vector<RenamePassData> &Worklist) {
904f22ef01cSRoman Divacky NextIteration:
905f22ef01cSRoman Divacky   // If we are inserting any phi nodes into this BB, they will already be in the
906f22ef01cSRoman Divacky   // block.
907f22ef01cSRoman Divacky   if (PHINode *APN = dyn_cast<PHINode>(BB->begin())) {
908f22ef01cSRoman Divacky     // If we have PHI nodes to update, compute the number of edges from Pred to
909f22ef01cSRoman Divacky     // BB.
910f22ef01cSRoman Divacky     if (PhiToAllocaMap.count(APN)) {
911f22ef01cSRoman Divacky       // We want to be able to distinguish between PHI nodes being inserted by
912f22ef01cSRoman Divacky       // this invocation of mem2reg from those phi nodes that already existed in
913f22ef01cSRoman Divacky       // the IR before mem2reg was run.  We determine that APN is being inserted
914f22ef01cSRoman Divacky       // because it is missing incoming edges.  All other PHI nodes being
915f22ef01cSRoman Divacky       // inserted by this pass of mem2reg will have the same number of incoming
916f22ef01cSRoman Divacky       // operands so far.  Remember this count.
917f22ef01cSRoman Divacky       unsigned NewPHINumOperands = APN->getNumOperands();
918f22ef01cSRoman Divacky 
919f785676fSDimitry Andric       unsigned NumEdges = std::count(succ_begin(Pred), succ_end(Pred), BB);
920f22ef01cSRoman Divacky       assert(NumEdges && "Must be at least one edge from Pred to BB!");
921f22ef01cSRoman Divacky 
922f22ef01cSRoman Divacky       // Add entries for all the phis.
923f22ef01cSRoman Divacky       BasicBlock::iterator PNI = BB->begin();
924f22ef01cSRoman Divacky       do {
925f22ef01cSRoman Divacky         unsigned AllocaNo = PhiToAllocaMap[APN];
926f22ef01cSRoman Divacky 
9274ba319b5SDimitry Andric         // Update the location of the phi node.
9284ba319b5SDimitry Andric         updateForIncomingValueLocation(APN, IncomingLocs[AllocaNo],
9294ba319b5SDimitry Andric                                        APN->getNumIncomingValues() > 0);
9304ba319b5SDimitry Andric 
931f22ef01cSRoman Divacky         // Add N incoming values to the PHI node.
932f22ef01cSRoman Divacky         for (unsigned i = 0; i != NumEdges; ++i)
933f22ef01cSRoman Divacky           APN->addIncoming(IncomingVals[AllocaNo], Pred);
934f22ef01cSRoman Divacky 
935f22ef01cSRoman Divacky         // The currently active variable for this block is now the PHI.
936f22ef01cSRoman Divacky         IncomingVals[AllocaNo] = APN;
937*b5893f02SDimitry Andric         for (DbgVariableIntrinsic *DII : AllocaDbgDeclares[AllocaNo])
9382cab237bSDimitry Andric           ConvertDebugDeclareToDebugValue(DII, APN, DIB);
939f22ef01cSRoman Divacky 
940f22ef01cSRoman Divacky         // Get the next phi node.
941f22ef01cSRoman Divacky         ++PNI;
942f22ef01cSRoman Divacky         APN = dyn_cast<PHINode>(PNI);
94391bc56edSDimitry Andric         if (!APN)
944f785676fSDimitry Andric           break;
945f22ef01cSRoman Divacky 
946f22ef01cSRoman Divacky         // Verify that it is missing entries.  If not, it is not being inserted
947f22ef01cSRoman Divacky         // by this mem2reg invocation so we want to ignore it.
948f22ef01cSRoman Divacky       } while (APN->getNumOperands() == NewPHINumOperands);
949f22ef01cSRoman Divacky     }
950f22ef01cSRoman Divacky   }
951f22ef01cSRoman Divacky 
952f22ef01cSRoman Divacky   // Don't revisit blocks.
95339d628a0SDimitry Andric   if (!Visited.insert(BB).second)
954f785676fSDimitry Andric     return;
955f22ef01cSRoman Divacky 
956*b5893f02SDimitry Andric   for (BasicBlock::iterator II = BB->begin(); !II->isTerminator();) {
9577d523365SDimitry Andric     Instruction *I = &*II++; // get the instruction, increment iterator
958f22ef01cSRoman Divacky 
959f22ef01cSRoman Divacky     if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
960f22ef01cSRoman Divacky       AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand());
961f785676fSDimitry Andric       if (!Src)
962f785676fSDimitry Andric         continue;
963f22ef01cSRoman Divacky 
9642754fe60SDimitry Andric       DenseMap<AllocaInst *, unsigned>::iterator AI = AllocaLookup.find(Src);
965f785676fSDimitry Andric       if (AI == AllocaLookup.end())
966f785676fSDimitry Andric         continue;
967f22ef01cSRoman Divacky 
968f22ef01cSRoman Divacky       Value *V = IncomingVals[AI->second];
969f22ef01cSRoman Divacky 
9707a7e6055SDimitry Andric       // If the load was marked as nonnull we don't want to lose
9717a7e6055SDimitry Andric       // that information when we erase this Load. So we preserve
9727a7e6055SDimitry Andric       // it with an assume.
9737a7e6055SDimitry Andric       if (AC && LI->getMetadata(LLVMContext::MD_nonnull) &&
9742cab237bSDimitry Andric           !isKnownNonZero(V, SQ.DL, 0, AC, LI, &DT))
9757a7e6055SDimitry Andric         addAssumeNonNull(AC, LI);
9767a7e6055SDimitry Andric 
977f22ef01cSRoman Divacky       // Anything using the load now uses the current value.
978f22ef01cSRoman Divacky       LI->replaceAllUsesWith(V);
979f22ef01cSRoman Divacky       BB->getInstList().erase(LI);
980f22ef01cSRoman Divacky     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
981f22ef01cSRoman Divacky       // Delete this instruction and mark the name as the current holder of the
982f22ef01cSRoman Divacky       // value
983f22ef01cSRoman Divacky       AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand());
984f785676fSDimitry Andric       if (!Dest)
985f785676fSDimitry Andric         continue;
986f22ef01cSRoman Divacky 
9872754fe60SDimitry Andric       DenseMap<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest);
988f22ef01cSRoman Divacky       if (ai == AllocaLookup.end())
989f22ef01cSRoman Divacky         continue;
990f22ef01cSRoman Divacky 
991f22ef01cSRoman Divacky       // what value were we writing?
9924ba319b5SDimitry Andric       unsigned AllocaNo = ai->second;
9934ba319b5SDimitry Andric       IncomingVals[AllocaNo] = SI->getOperand(0);
9944ba319b5SDimitry Andric 
995f22ef01cSRoman Divacky       // Record debuginfo for the store before removing it.
9964ba319b5SDimitry Andric       IncomingLocs[AllocaNo] = SI->getDebugLoc();
997*b5893f02SDimitry Andric       for (DbgVariableIntrinsic *DII : AllocaDbgDeclares[ai->second])
9982cab237bSDimitry Andric         ConvertDebugDeclareToDebugValue(DII, SI, DIB);
999f22ef01cSRoman Divacky       BB->getInstList().erase(SI);
1000f22ef01cSRoman Divacky     }
1001f22ef01cSRoman Divacky   }
1002f22ef01cSRoman Divacky 
1003f22ef01cSRoman Divacky   // 'Recurse' to our successors.
1004f22ef01cSRoman Divacky   succ_iterator I = succ_begin(BB), E = succ_end(BB);
1005f785676fSDimitry Andric   if (I == E)
1006f785676fSDimitry Andric     return;
1007f22ef01cSRoman Divacky 
1008f22ef01cSRoman Divacky   // Keep track of the successors so we don't visit the same successor twice
1009f22ef01cSRoman Divacky   SmallPtrSet<BasicBlock *, 8> VisitedSuccs;
1010f22ef01cSRoman Divacky 
1011f22ef01cSRoman Divacky   // Handle the first successor without using the worklist.
1012f22ef01cSRoman Divacky   VisitedSuccs.insert(*I);
1013f22ef01cSRoman Divacky   Pred = BB;
1014f22ef01cSRoman Divacky   BB = *I;
1015f22ef01cSRoman Divacky   ++I;
1016f22ef01cSRoman Divacky 
1017f22ef01cSRoman Divacky   for (; I != E; ++I)
101839d628a0SDimitry Andric     if (VisitedSuccs.insert(*I).second)
10194ba319b5SDimitry Andric       Worklist.emplace_back(*I, Pred, IncomingVals, IncomingLocs);
1020f22ef01cSRoman Divacky 
1021f22ef01cSRoman Divacky   goto NextIteration;
1022f22ef01cSRoman Divacky }
1023f22ef01cSRoman Divacky 
PromoteMemToReg(ArrayRef<AllocaInst * > Allocas,DominatorTree & DT,AssumptionCache * AC)1024f785676fSDimitry Andric void llvm::PromoteMemToReg(ArrayRef<AllocaInst *> Allocas, DominatorTree &DT,
10257a7e6055SDimitry Andric                            AssumptionCache *AC) {
1026f22ef01cSRoman Divacky   // If there is nothing to do, bail out...
1027f785676fSDimitry Andric   if (Allocas.empty())
1028f785676fSDimitry Andric     return;
1029f22ef01cSRoman Divacky 
10307a7e6055SDimitry Andric   PromoteMem2Reg(Allocas, DT, AC).run();
1031f22ef01cSRoman Divacky }
1032