1193323Sed//===- PromoteMemoryToRegister.cpp - Convert allocas to registers ---------===//
2193323Sed//
3353358Sdim// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4353358Sdim// See https://llvm.org/LICENSE.txt for license information.
5353358Sdim// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6193323Sed//
7193323Sed//===----------------------------------------------------------------------===//
8193323Sed//
9193323Sed// This file promotes memory references to be register references.  It promotes
10193323Sed// alloca instructions which only have loads and stores as uses.  An alloca is
11218893Sdim// transformed by using iterated dominator frontiers to place PHI nodes, then
12218893Sdim// traversing the function in depth-first order to rewrite loads and stores as
13218893Sdim// appropriate.
14193323Sed//
15193323Sed//===----------------------------------------------------------------------===//
16193323Sed
17261991Sdim#include "llvm/ADT/ArrayRef.h"
18193323Sed#include "llvm/ADT/DenseMap.h"
19249423Sdim#include "llvm/ADT/STLExtras.h"
20193323Sed#include "llvm/ADT/SmallPtrSet.h"
21193323Sed#include "llvm/ADT/SmallVector.h"
22193323Sed#include "llvm/ADT/Statistic.h"
23327952Sdim#include "llvm/ADT/TinyPtrVector.h"
24327952Sdim#include "llvm/ADT/Twine.h"
25321369Sdim#include "llvm/Analysis/AssumptionCache.h"
26249423Sdim#include "llvm/Analysis/InstructionSimplify.h"
27288943Sdim#include "llvm/Analysis/IteratedDominanceFrontier.h"
28341825Sdim#include "llvm/Transforms/Utils/Local.h"
29249423Sdim#include "llvm/Analysis/ValueTracking.h"
30327952Sdim#include "llvm/IR/BasicBlock.h"
31276479Sdim#include "llvm/IR/CFG.h"
32327952Sdim#include "llvm/IR/Constant.h"
33249423Sdim#include "llvm/IR/Constants.h"
34276479Sdim#include "llvm/IR/DIBuilder.h"
35249423Sdim#include "llvm/IR/DerivedTypes.h"
36276479Sdim#include "llvm/IR/Dominators.h"
37249423Sdim#include "llvm/IR/Function.h"
38327952Sdim#include "llvm/IR/InstrTypes.h"
39327952Sdim#include "llvm/IR/Instruction.h"
40249423Sdim#include "llvm/IR/Instructions.h"
41249423Sdim#include "llvm/IR/IntrinsicInst.h"
42327952Sdim#include "llvm/IR/Intrinsics.h"
43327952Sdim#include "llvm/IR/LLVMContext.h"
44288943Sdim#include "llvm/IR/Module.h"
45327952Sdim#include "llvm/IR/Type.h"
46327952Sdim#include "llvm/IR/User.h"
47327952Sdim#include "llvm/Support/Casting.h"
48321369Sdim#include "llvm/Transforms/Utils/PromoteMemToReg.h"
49193323Sed#include <algorithm>
50327952Sdim#include <cassert>
51327952Sdim#include <iterator>
52327952Sdim#include <utility>
53327952Sdim#include <vector>
54327952Sdim
55193323Sedusing namespace llvm;
56193323Sed
57276479Sdim#define DEBUG_TYPE "mem2reg"
58276479Sdim
59193323SedSTATISTIC(NumLocalPromoted, "Number of alloca's promoted within one block");
60193323SedSTATISTIC(NumSingleStore,   "Number of alloca's promoted with a single store");
61193323SedSTATISTIC(NumDeadAlloca,    "Number of dead alloca's removed");
62193323SedSTATISTIC(NumPHIInsert,     "Number of PHI nodes inserted");
63193323Sed
64193323Sedbool llvm::isAllocaPromotable(const AllocaInst *AI) {
65193323Sed  // FIXME: If the memory unit is of pointer or integer type, we can permit
66193323Sed  // assignments to subsections of the memory unit.
67276479Sdim  unsigned AS = AI->getType()->getAddressSpace();
68193323Sed
69193323Sed  // Only allow direct and non-volatile loads and stores...
70276479Sdim  for (const User *U : AI->users()) {
71210299Sed    if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
72226633Sdim      // Note that atomic loads can be transformed; atomic semantics do
73226633Sdim      // not have any meaning for a local alloca.
74193323Sed      if (LI->isVolatile())
75193323Sed        return false;
76210299Sed    } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
77193323Sed      if (SI->getOperand(0) == AI)
78261991Sdim        return false; // Don't allow a store OF the AI, only INTO the AI.
79226633Sdim      // Note that atomic stores can be transformed; atomic semantics do
80226633Sdim      // not have any meaning for a local alloca.
81193323Sed      if (SI->isVolatile())
82193323Sed        return false;
83224145Sdim    } else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
84344779Sdim      if (!II->isLifetimeStartOrEnd())
85224145Sdim        return false;
86224145Sdim    } else if (const BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
87276479Sdim      if (BCI->getType() != Type::getInt8PtrTy(U->getContext(), AS))
88224145Sdim        return false;
89224145Sdim      if (!onlyUsedByLifetimeMarkers(BCI))
90224145Sdim        return false;
91224145Sdim    } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
92276479Sdim      if (GEPI->getType() != Type::getInt8PtrTy(U->getContext(), AS))
93224145Sdim        return false;
94224145Sdim      if (!GEPI->hasAllZeroIndices())
95224145Sdim        return false;
96224145Sdim      if (!onlyUsedByLifetimeMarkers(GEPI))
97224145Sdim        return false;
98193323Sed    } else {
99193323Sed      return false;
100193323Sed    }
101210299Sed  }
102193323Sed
103193323Sed  return true;
104193323Sed}
105193323Sed
106193323Sednamespace {
107193323Sed
108261991Sdimstruct AllocaInfo {
109261991Sdim  SmallVector<BasicBlock *, 32> DefiningBlocks;
110261991Sdim  SmallVector<BasicBlock *, 32> UsingBlocks;
111261991Sdim
112261991Sdim  StoreInst *OnlyStore;
113261991Sdim  BasicBlock *OnlyBlock;
114261991Sdim  bool OnlyUsedInOneBlock;
115261991Sdim
116344779Sdim  TinyPtrVector<DbgVariableIntrinsic *> DbgDeclares;
117261991Sdim
118261991Sdim  void clear() {
119261991Sdim    DefiningBlocks.clear();
120261991Sdim    UsingBlocks.clear();
121276479Sdim    OnlyStore = nullptr;
122276479Sdim    OnlyBlock = nullptr;
123261991Sdim    OnlyUsedInOneBlock = true;
124327952Sdim    DbgDeclares.clear();
125261991Sdim  }
126261991Sdim
127261991Sdim  /// Scan the uses of the specified alloca, filling in the AllocaInfo used
128261991Sdim  /// by the rest of the pass to reason about the uses of this alloca.
129261991Sdim  void AnalyzeAlloca(AllocaInst *AI) {
130261991Sdim    clear();
131261991Sdim
132261991Sdim    // As we scan the uses of the alloca instruction, keep track of stores,
133261991Sdim    // and decide whether all of the loads and stores to the alloca are within
134261991Sdim    // the same basic block.
135276479Sdim    for (auto UI = AI->user_begin(), E = AI->user_end(); UI != E;) {
136261991Sdim      Instruction *User = cast<Instruction>(*UI++);
137261991Sdim
138261991Sdim      if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
139261991Sdim        // Remember the basic blocks which define new values for the alloca
140261991Sdim        DefiningBlocks.push_back(SI->getParent());
141261991Sdim        OnlyStore = SI;
142261991Sdim      } else {
143261991Sdim        LoadInst *LI = cast<LoadInst>(User);
144261991Sdim        // Otherwise it must be a load instruction, keep track of variable
145261991Sdim        // reads.
146261991Sdim        UsingBlocks.push_back(LI->getParent());
147261991Sdim      }
148261991Sdim
149261991Sdim      if (OnlyUsedInOneBlock) {
150276479Sdim        if (!OnlyBlock)
151261991Sdim          OnlyBlock = User->getParent();
152261991Sdim        else if (OnlyBlock != User->getParent())
153261991Sdim          OnlyUsedInOneBlock = false;
154261991Sdim      }
155193323Sed    }
156261991Sdim
157327952Sdim    DbgDeclares = FindDbgAddrUses(AI);
158261991Sdim  }
159261991Sdim};
160261991Sdim
161341825Sdim/// Data package used by RenamePass().
162341825Sdimstruct RenamePassData {
163327952Sdim  using ValVector = std::vector<Value *>;
164341825Sdim  using LocationVector = std::vector<DebugLoc>;
165261991Sdim
166341825Sdim  RenamePassData(BasicBlock *B, BasicBlock *P, ValVector V, LocationVector L)
167341825Sdim      : BB(B), Pred(P), Values(std::move(V)), Locations(std::move(L)) {}
168327952Sdim
169261991Sdim  BasicBlock *BB;
170261991Sdim  BasicBlock *Pred;
171261991Sdim  ValVector Values;
172341825Sdim  LocationVector Locations;
173261991Sdim};
174261991Sdim
175341825Sdim/// This assigns and keeps a per-bb relative ordering of load/store
176261991Sdim/// instructions in the block that directly load or store an alloca.
177261991Sdim///
178261991Sdim/// This functionality is important because it avoids scanning large basic
179261991Sdim/// blocks multiple times when promoting many allocas in the same block.
180261991Sdimclass LargeBlockInfo {
181341825Sdim  /// For each instruction that we track, keep the index of the
182261991Sdim  /// instruction.
183193323Sed  ///
184261991Sdim  /// The index starts out as the number of the instruction from the start of
185261991Sdim  /// the block.
186261991Sdim  DenseMap<const Instruction *, unsigned> InstNumbers;
187261991Sdim
188261991Sdimpublic:
189261991Sdim
190261991Sdim  /// This code only looks at accesses to allocas.
191261991Sdim  static bool isInterestingInstruction(const Instruction *I) {
192261991Sdim    return (isa<LoadInst>(I) && isa<AllocaInst>(I->getOperand(0))) ||
193261991Sdim           (isa<StoreInst>(I) && isa<AllocaInst>(I->getOperand(1)));
194261991Sdim  }
195261991Sdim
196261991Sdim  /// Get or calculate the index of the specified instruction.
197261991Sdim  unsigned getInstructionIndex(const Instruction *I) {
198261991Sdim    assert(isInterestingInstruction(I) &&
199261991Sdim           "Not a load/store to/from an alloca?");
200261991Sdim
201261991Sdim    // If we already have this instruction number, return it.
202261991Sdim    DenseMap<const Instruction *, unsigned>::iterator It = InstNumbers.find(I);
203261991Sdim    if (It != InstNumbers.end())
204193323Sed      return It->second;
205193323Sed
206261991Sdim    // Scan the whole block to get the instruction.  This accumulates
207261991Sdim    // information for every interesting instruction in the block, in order to
208261991Sdim    // avoid gratuitus rescans.
209261991Sdim    const BasicBlock *BB = I->getParent();
210261991Sdim    unsigned InstNo = 0;
211296417Sdim    for (const Instruction &BBI : *BB)
212296417Sdim      if (isInterestingInstruction(&BBI))
213296417Sdim        InstNumbers[&BBI] = InstNo++;
214261991Sdim    It = InstNumbers.find(I);
215193323Sed
216261991Sdim    assert(It != InstNumbers.end() && "Didn't insert instruction?");
217261991Sdim    return It->second;
218261991Sdim  }
219193323Sed
220261991Sdim  void deleteValue(const Instruction *I) { InstNumbers.erase(I); }
221193323Sed
222261991Sdim  void clear() { InstNumbers.clear(); }
223261991Sdim};
224203954Srdivacky
225261991Sdimstruct PromoteMem2Reg {
226261991Sdim  /// The alloca instructions being promoted.
227261991Sdim  std::vector<AllocaInst *> Allocas;
228327952Sdim
229261991Sdim  DominatorTree &DT;
230261991Sdim  DIBuilder DIB;
231327952Sdim
232280031Sdim  /// A cache of @llvm.assume intrinsics used by SimplifyInstruction.
233280031Sdim  AssumptionCache *AC;
234280031Sdim
235321369Sdim  const SimplifyQuery SQ;
236327952Sdim
237261991Sdim  /// Reverse mapping of Allocas.
238261991Sdim  DenseMap<AllocaInst *, unsigned> AllocaLookup;
239218893Sdim
240341825Sdim  /// The PhiNodes we're adding.
241261991Sdim  ///
242261991Sdim  /// That map is used to simplify some Phi nodes as we iterate over it, so
243261991Sdim  /// it should have deterministic iterators.  We could use a MapVector, but
244261991Sdim  /// since we already maintain a map from BasicBlock* to a stable numbering
245261991Sdim  /// (BBNumbers), the DenseMap is more efficient (also supports removal).
246261991Sdim  DenseMap<std::pair<unsigned, unsigned>, PHINode *> NewPhiNodes;
247193323Sed
248261991Sdim  /// For each PHI node, keep track of which entry in Allocas it corresponds
249261991Sdim  /// to.
250261991Sdim  DenseMap<PHINode *, unsigned> PhiToAllocaMap;
251193323Sed
252261991Sdim  /// For each alloca, we keep track of the dbg.declare intrinsic that
253261991Sdim  /// describes it, if any, so that we can convert it to a dbg.value
254261991Sdim  /// intrinsic if the alloca gets promoted.
255344779Sdim  SmallVector<TinyPtrVector<DbgVariableIntrinsic *>, 8> AllocaDbgDeclares;
256193323Sed
257261991Sdim  /// The set of basic blocks the renamer has already visited.
258261991Sdim  SmallPtrSet<BasicBlock *, 16> Visited;
259193323Sed
260261991Sdim  /// Contains a stable numbering of basic blocks to avoid non-determinstic
261261991Sdim  /// behavior.
262261991Sdim  DenseMap<BasicBlock *, unsigned> BBNumbers;
263193323Sed
264261991Sdim  /// Lazily compute the number of predecessors a block has.
265261991Sdim  DenseMap<const BasicBlock *, unsigned> BBNumPreds;
266218893Sdim
267261991Sdimpublic:
268261991Sdim  PromoteMem2Reg(ArrayRef<AllocaInst *> Allocas, DominatorTree &DT,
269321369Sdim                 AssumptionCache *AC)
270261991Sdim      : Allocas(Allocas.begin(), Allocas.end()), DT(DT),
271280031Sdim        DIB(*DT.getRoot()->getParent()->getParent(), /*AllowUnresolved*/ false),
272321369Sdim        AC(AC), SQ(DT.getRoot()->getParent()->getParent()->getDataLayout(),
273321369Sdim                   nullptr, &DT, AC) {}
274218893Sdim
275261991Sdim  void run();
276193323Sed
277261991Sdimprivate:
278261991Sdim  void RemoveFromAllocasList(unsigned &AllocaIdx) {
279261991Sdim    Allocas[AllocaIdx] = Allocas.back();
280261991Sdim    Allocas.pop_back();
281261991Sdim    --AllocaIdx;
282261991Sdim  }
283261991Sdim
284261991Sdim  unsigned getNumPreds(const BasicBlock *BB) {
285261991Sdim    unsigned &NP = BBNumPreds[BB];
286261991Sdim    if (NP == 0)
287341825Sdim      NP = pred_size(BB) + 1;
288261991Sdim    return NP - 1;
289261991Sdim  }
290261991Sdim
291261991Sdim  void ComputeLiveInBlocks(AllocaInst *AI, AllocaInfo &Info,
292280031Sdim                           const SmallPtrSetImpl<BasicBlock *> &DefBlocks,
293280031Sdim                           SmallPtrSetImpl<BasicBlock *> &LiveInBlocks);
294261991Sdim  void RenamePass(BasicBlock *BB, BasicBlock *Pred,
295261991Sdim                  RenamePassData::ValVector &IncVals,
296341825Sdim                  RenamePassData::LocationVector &IncLocs,
297261991Sdim                  std::vector<RenamePassData> &Worklist);
298261991Sdim  bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx, unsigned &Version);
299261991Sdim};
300261991Sdim
301327952Sdim} // end anonymous namespace
302261991Sdim
303321369Sdim/// Given a LoadInst LI this adds assume(LI != null) after it.
304321369Sdimstatic void addAssumeNonNull(AssumptionCache *AC, LoadInst *LI) {
305321369Sdim  Function *AssumeIntrinsic =
306321369Sdim      Intrinsic::getDeclaration(LI->getModule(), Intrinsic::assume);
307321369Sdim  ICmpInst *LoadNotNull = new ICmpInst(ICmpInst::ICMP_NE, LI,
308321369Sdim                                       Constant::getNullValue(LI->getType()));
309321369Sdim  LoadNotNull->insertAfter(LI);
310321369Sdim  CallInst *CI = CallInst::Create(AssumeIntrinsic, {LoadNotNull});
311321369Sdim  CI->insertAfter(LoadNotNull);
312321369Sdim  AC->registerAssumption(CI);
313321369Sdim}
314321369Sdim
315224145Sdimstatic void removeLifetimeIntrinsicUsers(AllocaInst *AI) {
316224145Sdim  // Knowing that this alloca is promotable, we know that it's safe to kill all
317224145Sdim  // instructions except for load and store.
318193323Sed
319276479Sdim  for (auto UI = AI->user_begin(), UE = AI->user_end(); UI != UE;) {
320224145Sdim    Instruction *I = cast<Instruction>(*UI);
321224145Sdim    ++UI;
322224145Sdim    if (isa<LoadInst>(I) || isa<StoreInst>(I))
323224145Sdim      continue;
324224145Sdim
325224145Sdim    if (!I->getType()->isVoidTy()) {
326224145Sdim      // The only users of this bitcast/GEP instruction are lifetime intrinsics.
327224145Sdim      // Follow the use/def chain to erase them now instead of leaving it for
328224145Sdim      // dead code elimination later.
329276479Sdim      for (auto UUI = I->user_begin(), UUE = I->user_end(); UUI != UUE;) {
330276479Sdim        Instruction *Inst = cast<Instruction>(*UUI);
331276479Sdim        ++UUI;
332224145Sdim        Inst->eraseFromParent();
333224145Sdim      }
334224145Sdim    }
335224145Sdim    I->eraseFromParent();
336224145Sdim  }
337224145Sdim}
338224145Sdim
339341825Sdim/// Rewrite as many loads as possible given a single store.
340261991Sdim///
341261991Sdim/// When there is only a single store, we can use the domtree to trivially
342261991Sdim/// replace all of the dominated loads with the stored value. Do so, and return
343261991Sdim/// true if this has successfully promoted the alloca entirely. If this returns
344261991Sdim/// false there were some loads which were not dominated by the single store
345261991Sdim/// and thus must be phi-ed with undef. We fall back to the standard alloca
346261991Sdim/// promotion algorithm in that case.
347261991Sdimstatic bool rewriteSingleStoreAlloca(AllocaInst *AI, AllocaInfo &Info,
348327952Sdim                                     LargeBlockInfo &LBI, const DataLayout &DL,
349327952Sdim                                     DominatorTree &DT, AssumptionCache *AC) {
350261991Sdim  StoreInst *OnlyStore = Info.OnlyStore;
351261991Sdim  bool StoringGlobalVal = !isa<Instruction>(OnlyStore->getOperand(0));
352261991Sdim  BasicBlock *StoreBB = OnlyStore->getParent();
353261991Sdim  int StoreIndex = -1;
354261991Sdim
355261991Sdim  // Clear out UsingBlocks.  We will reconstruct it here if needed.
356261991Sdim  Info.UsingBlocks.clear();
357261991Sdim
358276479Sdim  for (auto UI = AI->user_begin(), E = AI->user_end(); UI != E;) {
359261991Sdim    Instruction *UserInst = cast<Instruction>(*UI++);
360353358Sdim    if (UserInst == OnlyStore)
361261991Sdim      continue;
362261991Sdim    LoadInst *LI = cast<LoadInst>(UserInst);
363261991Sdim
364261991Sdim    // Okay, if we have a load from the alloca, we want to replace it with the
365261991Sdim    // only value stored to the alloca.  We can do this if the value is
366261991Sdim    // dominated by the store.  If not, we use the rest of the mem2reg machinery
367261991Sdim    // to insert the phi nodes as needed.
368261991Sdim    if (!StoringGlobalVal) { // Non-instructions are always dominated.
369261991Sdim      if (LI->getParent() == StoreBB) {
370261991Sdim        // If we have a use that is in the same block as the store, compare the
371261991Sdim        // indices of the two instructions to see which one came first.  If the
372261991Sdim        // load came before the store, we can't handle it.
373261991Sdim        if (StoreIndex == -1)
374261991Sdim          StoreIndex = LBI.getInstructionIndex(OnlyStore);
375261991Sdim
376261991Sdim        if (unsigned(StoreIndex) > LBI.getInstructionIndex(LI)) {
377261991Sdim          // Can't handle this load, bail out.
378261991Sdim          Info.UsingBlocks.push_back(StoreBB);
379261991Sdim          continue;
380261991Sdim        }
381353358Sdim      } else if (!DT.dominates(StoreBB, LI->getParent())) {
382261991Sdim        // If the load and store are in different blocks, use BB dominance to
383261991Sdim        // check their relationships.  If the store doesn't dom the use, bail
384261991Sdim        // out.
385261991Sdim        Info.UsingBlocks.push_back(LI->getParent());
386261991Sdim        continue;
387261991Sdim      }
388261991Sdim    }
389261991Sdim
390261991Sdim    // Otherwise, we *can* safely rewrite this load.
391261991Sdim    Value *ReplVal = OnlyStore->getOperand(0);
392261991Sdim    // If the replacement value is the load, this must occur in unreachable
393261991Sdim    // code.
394261991Sdim    if (ReplVal == LI)
395261991Sdim      ReplVal = UndefValue::get(LI->getType());
396321369Sdim
397321369Sdim    // If the load was marked as nonnull we don't want to lose
398321369Sdim    // that information when we erase this Load. So we preserve
399321369Sdim    // it with an assume.
400321369Sdim    if (AC && LI->getMetadata(LLVMContext::MD_nonnull) &&
401327952Sdim        !isKnownNonZero(ReplVal, DL, 0, AC, LI, &DT))
402321369Sdim      addAssumeNonNull(AC, LI);
403321369Sdim
404261991Sdim    LI->replaceAllUsesWith(ReplVal);
405261991Sdim    LI->eraseFromParent();
406261991Sdim    LBI.deleteValue(LI);
407261991Sdim  }
408261991Sdim
409261991Sdim  // Finally, after the scan, check to see if the store is all that is left.
410261991Sdim  if (!Info.UsingBlocks.empty())
411261991Sdim    return false; // If not, we'll have to fall back for the remainder.
412261991Sdim
413261991Sdim  // Record debuginfo for the store and remove the declaration's
414261991Sdim  // debuginfo.
415344779Sdim  for (DbgVariableIntrinsic *DII : Info.DbgDeclares) {
416296417Sdim    DIBuilder DIB(*AI->getModule(), /*AllowUnresolved*/ false);
417327952Sdim    ConvertDebugDeclareToDebugValue(DII, Info.OnlyStore, DIB);
418327952Sdim    DII->eraseFromParent();
419261991Sdim  }
420261991Sdim  // Remove the (now dead) store and alloca.
421261991Sdim  Info.OnlyStore->eraseFromParent();
422261991Sdim  LBI.deleteValue(Info.OnlyStore);
423261991Sdim
424261991Sdim  AI->eraseFromParent();
425261991Sdim  return true;
426261991Sdim}
427261991Sdim
428261991Sdim/// Many allocas are only used within a single basic block.  If this is the
429261991Sdim/// case, avoid traversing the CFG and inserting a lot of potentially useless
430261991Sdim/// PHI nodes by just performing a single linear pass over the basic block
431261991Sdim/// using the Alloca.
432261991Sdim///
433261991Sdim/// If we cannot promote this alloca (because it is read before it is written),
434296417Sdim/// return false.  This is necessary in cases where, due to control flow, the
435296417Sdim/// alloca is undefined only on some control flow paths.  e.g. code like
436296417Sdim/// this is correct in LLVM IR:
437296417Sdim///  // A is an alloca with no stores so far
438296417Sdim///  for (...) {
439296417Sdim///    int t = *A;
440296417Sdim///    if (!first_iteration)
441296417Sdim///      use(t);
442296417Sdim///    *A = 42;
443296417Sdim///  }
444296417Sdimstatic bool promoteSingleBlockAlloca(AllocaInst *AI, const AllocaInfo &Info,
445261991Sdim                                     LargeBlockInfo &LBI,
446327952Sdim                                     const DataLayout &DL,
447321369Sdim                                     DominatorTree &DT,
448321369Sdim                                     AssumptionCache *AC) {
449261991Sdim  // The trickiest case to handle is when we have large blocks. Because of this,
450261991Sdim  // this code is optimized assuming that large blocks happen.  This does not
451261991Sdim  // significantly pessimize the small block case.  This uses LargeBlockInfo to
452261991Sdim  // make it efficient to get the index of various operations in the block.
453261991Sdim
454261991Sdim  // Walk the use-def list of the alloca, getting the locations of all stores.
455327952Sdim  using StoresByIndexTy = SmallVector<std::pair<unsigned, StoreInst *>, 64>;
456261991Sdim  StoresByIndexTy StoresByIndex;
457261991Sdim
458276479Sdim  for (User *U : AI->users())
459276479Sdim    if (StoreInst *SI = dyn_cast<StoreInst>(U))
460261991Sdim      StoresByIndex.push_back(std::make_pair(LBI.getInstructionIndex(SI), SI));
461261991Sdim
462261991Sdim  // Sort the stores by their index, making it efficient to do a lookup with a
463261991Sdim  // binary search.
464344779Sdim  llvm::sort(StoresByIndex, less_first());
465261991Sdim
466261991Sdim  // Walk all of the loads from this alloca, replacing them with the nearest
467261991Sdim  // store above them, if any.
468276479Sdim  for (auto UI = AI->user_begin(), E = AI->user_end(); UI != E;) {
469261991Sdim    LoadInst *LI = dyn_cast<LoadInst>(*UI++);
470261991Sdim    if (!LI)
471261991Sdim      continue;
472261991Sdim
473261991Sdim    unsigned LoadIdx = LBI.getInstructionIndex(LI);
474261991Sdim
475261991Sdim    // Find the nearest store that has a lower index than this load.
476353358Sdim    StoresByIndexTy::iterator I = llvm::lower_bound(
477353358Sdim        StoresByIndex,
478353358Sdim        std::make_pair(LoadIdx, static_cast<StoreInst *>(nullptr)),
479353358Sdim        less_first());
480296417Sdim    if (I == StoresByIndex.begin()) {
481296417Sdim      if (StoresByIndex.empty())
482296417Sdim        // If there are no stores, the load takes the undef value.
483296417Sdim        LI->replaceAllUsesWith(UndefValue::get(LI->getType()));
484296417Sdim      else
485296417Sdim        // There is no store before this load, bail out (load may be affected
486296417Sdim        // by the following stores - see main comment).
487296417Sdim        return false;
488321369Sdim    } else {
489261991Sdim      // Otherwise, there was a store before this load, the load takes its value.
490321369Sdim      // Note, if the load was marked as nonnull we don't want to lose that
491321369Sdim      // information when we erase it. So we preserve it with an assume.
492321369Sdim      Value *ReplVal = std::prev(I)->second->getOperand(0);
493321369Sdim      if (AC && LI->getMetadata(LLVMContext::MD_nonnull) &&
494327952Sdim          !isKnownNonZero(ReplVal, DL, 0, AC, LI, &DT))
495321369Sdim        addAssumeNonNull(AC, LI);
496261991Sdim
497341825Sdim      // If the replacement value is the load, this must occur in unreachable
498341825Sdim      // code.
499341825Sdim      if (ReplVal == LI)
500341825Sdim        ReplVal = UndefValue::get(LI->getType());
501341825Sdim
502321369Sdim      LI->replaceAllUsesWith(ReplVal);
503321369Sdim    }
504321369Sdim
505261991Sdim    LI->eraseFromParent();
506261991Sdim    LBI.deleteValue(LI);
507261991Sdim  }
508261991Sdim
509261991Sdim  // Remove the (now dead) stores and alloca.
510261991Sdim  while (!AI->use_empty()) {
511276479Sdim    StoreInst *SI = cast<StoreInst>(AI->user_back());
512261991Sdim    // Record debuginfo for the store before removing it.
513344779Sdim    for (DbgVariableIntrinsic *DII : Info.DbgDeclares) {
514296417Sdim      DIBuilder DIB(*AI->getModule(), /*AllowUnresolved*/ false);
515327952Sdim      ConvertDebugDeclareToDebugValue(DII, SI, DIB);
516261991Sdim    }
517261991Sdim    SI->eraseFromParent();
518261991Sdim    LBI.deleteValue(SI);
519261991Sdim  }
520261991Sdim
521261991Sdim  AI->eraseFromParent();
522261991Sdim
523261991Sdim  // The alloca's debuginfo can be removed as well.
524353358Sdim  for (DbgVariableIntrinsic *DII : Info.DbgDeclares)
525327952Sdim    DII->eraseFromParent();
526261991Sdim
527261991Sdim  ++NumLocalPromoted;
528296417Sdim  return true;
529261991Sdim}
530261991Sdim
531193323Sedvoid PromoteMem2Reg::run() {
532218893Sdim  Function &F = *DT.getRoot()->getParent();
533193323Sed
534203954Srdivacky  AllocaDbgDeclares.resize(Allocas.size());
535193323Sed
536193323Sed  AllocaInfo Info;
537193323Sed  LargeBlockInfo LBI;
538309124Sdim  ForwardIDFCalculator IDF(DT);
539193323Sed
540193323Sed  for (unsigned AllocaNum = 0; AllocaNum != Allocas.size(); ++AllocaNum) {
541193323Sed    AllocaInst *AI = Allocas[AllocaNum];
542193323Sed
543261991Sdim    assert(isAllocaPromotable(AI) && "Cannot promote non-promotable alloca!");
544193323Sed    assert(AI->getParent()->getParent() == &F &&
545193323Sed           "All allocas should be in the same function, which is same as DF!");
546193323Sed
547224145Sdim    removeLifetimeIntrinsicUsers(AI);
548224145Sdim
549193323Sed    if (AI->use_empty()) {
550193323Sed      // If there are no uses of the alloca, just delete it now.
551193323Sed      AI->eraseFromParent();
552193323Sed
553193323Sed      // Remove the alloca from the Allocas list, since it has been processed
554193323Sed      RemoveFromAllocasList(AllocaNum);
555193323Sed      ++NumDeadAlloca;
556193323Sed      continue;
557193323Sed    }
558261991Sdim
559193323Sed    // Calculate the set of read and write-locations for each alloca.  This is
560193323Sed    // analogous to finding the 'uses' and 'definitions' of each variable.
561193323Sed    Info.AnalyzeAlloca(AI);
562193323Sed
563193323Sed    // If there is only a single store to this value, replace any loads of
564193323Sed    // it that are directly dominated by the definition with the value stored.
565193323Sed    if (Info.DefiningBlocks.size() == 1) {
566327952Sdim      if (rewriteSingleStoreAlloca(AI, Info, LBI, SQ.DL, DT, AC)) {
567193323Sed        // The alloca has been processed, move on.
568193323Sed        RemoveFromAllocasList(AllocaNum);
569193323Sed        ++NumSingleStore;
570193323Sed        continue;
571193323Sed      }
572193323Sed    }
573261991Sdim
574193323Sed    // If the alloca is only read and written in one basic block, just perform a
575193323Sed    // linear sweep over the block to eliminate it.
576296417Sdim    if (Info.OnlyUsedInOneBlock &&
577327952Sdim        promoteSingleBlockAlloca(AI, Info, LBI, SQ.DL, DT, AC)) {
578261991Sdim      // The alloca has been processed, move on.
579261991Sdim      RemoveFromAllocasList(AllocaNum);
580261991Sdim      continue;
581193323Sed    }
582218893Sdim
583193323Sed    // If we haven't computed a numbering for the BB's in the function, do so
584193323Sed    // now.
585193323Sed    if (BBNumbers.empty()) {
586193323Sed      unsigned ID = 0;
587288943Sdim      for (auto &BB : F)
588288943Sdim        BBNumbers[&BB] = ID++;
589193323Sed    }
590193323Sed
591203954Srdivacky    // Remember the dbg.declare intrinsic describing this alloca, if any.
592327952Sdim    if (!Info.DbgDeclares.empty())
593327952Sdim      AllocaDbgDeclares[AllocaNum] = Info.DbgDeclares;
594261991Sdim
595193323Sed    // Keep the reverse mapping of the 'Allocas' array for the rename pass.
596193323Sed    AllocaLookup[Allocas[AllocaNum]] = AllocaNum;
597193323Sed
598193323Sed    // At this point, we're committed to promoting the alloca using IDF's, and
599193323Sed    // the standard SSA construction algorithm.  Determine which blocks need PHI
600193323Sed    // nodes and see if we can optimize out some work by avoiding insertion of
601193323Sed    // dead phi nodes.
602288943Sdim
603288943Sdim    // Unique the set of defining blocks for efficient lookup.
604353358Sdim    SmallPtrSet<BasicBlock *, 32> DefBlocks(Info.DefiningBlocks.begin(),
605353358Sdim                                            Info.DefiningBlocks.end());
606288943Sdim
607288943Sdim    // Determine which blocks the value is live in.  These are blocks which lead
608288943Sdim    // to uses.
609288943Sdim    SmallPtrSet<BasicBlock *, 32> LiveInBlocks;
610288943Sdim    ComputeLiveInBlocks(AI, Info, DefBlocks, LiveInBlocks);
611288943Sdim
612288943Sdim    // At this point, we're committed to promoting the alloca using IDF's, and
613288943Sdim    // the standard SSA construction algorithm.  Determine which blocks need phi
614288943Sdim    // nodes and see if we can optimize out some work by avoiding insertion of
615288943Sdim    // dead phi nodes.
616288943Sdim    IDF.setLiveInBlocks(LiveInBlocks);
617288943Sdim    IDF.setDefiningBlocks(DefBlocks);
618288943Sdim    SmallVector<BasicBlock *, 32> PHIBlocks;
619288943Sdim    IDF.calculate(PHIBlocks);
620353358Sdim    llvm::sort(PHIBlocks, [this](BasicBlock *A, BasicBlock *B) {
621353358Sdim      return BBNumbers.find(A)->second < BBNumbers.find(B)->second;
622353358Sdim    });
623288943Sdim
624288943Sdim    unsigned CurrentVersion = 0;
625327952Sdim    for (BasicBlock *BB : PHIBlocks)
626327952Sdim      QueuePhiNode(BB, AllocaNum, CurrentVersion);
627193323Sed  }
628193323Sed
629193323Sed  if (Allocas.empty())
630193323Sed    return; // All of the allocas must have been trivial!
631193323Sed
632193323Sed  LBI.clear();
633261991Sdim
634193323Sed  // Set the incoming values for the basic block to be null values for all of
635193323Sed  // the alloca's.  We do this in case there is a load of a value that has not
636193323Sed  // been stored yet.  In this case, it will get this null value.
637193323Sed  RenamePassData::ValVector Values(Allocas.size());
638193323Sed  for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
639193323Sed    Values[i] = UndefValue::get(Allocas[i]->getAllocatedType());
640193323Sed
641341825Sdim  // When handling debug info, treat all incoming values as if they have unknown
642341825Sdim  // locations until proven otherwise.
643341825Sdim  RenamePassData::LocationVector Locations(Allocas.size());
644341825Sdim
645193323Sed  // Walks all basic blocks in the function performing the SSA rename algorithm
646193323Sed  // and inserting the phi nodes we marked as necessary
647193323Sed  std::vector<RenamePassData> RenamePassWorkList;
648341825Sdim  RenamePassWorkList.emplace_back(&F.front(), nullptr, std::move(Values),
649341825Sdim                                  std::move(Locations));
650202375Srdivacky  do {
651327952Sdim    RenamePassData RPD = std::move(RenamePassWorkList.back());
652193323Sed    RenamePassWorkList.pop_back();
653193323Sed    // RenamePass may add new worklist entries.
654341825Sdim    RenamePass(RPD.BB, RPD.Pred, RPD.Values, RPD.Locations, RenamePassWorkList);
655202375Srdivacky  } while (!RenamePassWorkList.empty());
656261991Sdim
657193323Sed  // The renamer uses the Visited set to avoid infinite loops.  Clear it now.
658193323Sed  Visited.clear();
659193323Sed
660193323Sed  // Remove the allocas themselves from the function.
661327952Sdim  for (Instruction *A : Allocas) {
662193323Sed    // If there are any uses of the alloca instructions left, they must be in
663218893Sdim    // unreachable basic blocks that were not processed by walking the dominator
664218893Sdim    // tree. Just delete the users now.
665193323Sed    if (!A->use_empty())
666193323Sed      A->replaceAllUsesWith(UndefValue::get(A->getType()));
667193323Sed    A->eraseFromParent();
668193323Sed  }
669193323Sed
670203954Srdivacky  // Remove alloca's dbg.declare instrinsics from the function.
671327952Sdim  for (auto &Declares : AllocaDbgDeclares)
672327952Sdim    for (auto *DII : Declares)
673327952Sdim      DII->eraseFromParent();
674203954Srdivacky
675193323Sed  // Loop over all of the PHI nodes and see if there are any that we can get
676193323Sed  // rid of because they merge all of the same incoming values.  This can
677193323Sed  // happen due to undef values coming into the PHI nodes.  This process is
678193323Sed  // iterative, because eliminating one PHI node can cause others to be removed.
679193323Sed  bool EliminatedAPHI = true;
680193323Sed  while (EliminatedAPHI) {
681193323Sed    EliminatedAPHI = false;
682261991Sdim
683243830Sdim    // Iterating over NewPhiNodes is deterministic, so it is safe to try to
684243830Sdim    // simplify and RAUW them as we go.  If it was not, we could add uses to
685276479Sdim    // the values we replace with in a non-deterministic order, thus creating
686276479Sdim    // non-deterministic def->use chains.
687261991Sdim    for (DenseMap<std::pair<unsigned, unsigned>, PHINode *>::iterator
688261991Sdim             I = NewPhiNodes.begin(),
689261991Sdim             E = NewPhiNodes.end();
690261991Sdim         I != E;) {
691193323Sed      PHINode *PN = I->second;
692218893Sdim
693193323Sed      // If this PHI node merges one value and/or undefs, get the value.
694321369Sdim      if (Value *V = SimplifyInstruction(PN, SQ)) {
695198090Srdivacky        PN->replaceAllUsesWith(V);
696198090Srdivacky        PN->eraseFromParent();
697198090Srdivacky        NewPhiNodes.erase(I++);
698198090Srdivacky        EliminatedAPHI = true;
699198090Srdivacky        continue;
700193323Sed      }
701193323Sed      ++I;
702193323Sed    }
703193323Sed  }
704261991Sdim
705193323Sed  // At this point, the renamer has added entries to PHI nodes for all reachable
706193323Sed  // code.  Unfortunately, there may be unreachable blocks which the renamer
707193323Sed  // hasn't traversed.  If this is the case, the PHI nodes may not
708193323Sed  // have incoming values for all predecessors.  Loop over all PHI nodes we have
709193323Sed  // created, inserting undef values if they are missing any incoming values.
710261991Sdim  for (DenseMap<std::pair<unsigned, unsigned>, PHINode *>::iterator
711261991Sdim           I = NewPhiNodes.begin(),
712261991Sdim           E = NewPhiNodes.end();
713261991Sdim       I != E; ++I) {
714193323Sed    // We want to do this once per basic block.  As such, only process a block
715193323Sed    // when we find the PHI that is the first entry in the block.
716193323Sed    PHINode *SomePHI = I->second;
717193323Sed    BasicBlock *BB = SomePHI->getParent();
718193323Sed    if (&BB->front() != SomePHI)
719193323Sed      continue;
720193323Sed
721193323Sed    // Only do work here if there the PHI nodes are missing incoming values.  We
722193323Sed    // know that all PHI nodes that were inserted in a block will have the same
723193323Sed    // number of incoming values, so we can just check any of them.
724193323Sed    if (SomePHI->getNumIncomingValues() == getNumPreds(BB))
725193323Sed      continue;
726193323Sed
727193323Sed    // Get the preds for BB.
728261991Sdim    SmallVector<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB));
729261991Sdim
730193323Sed    // Ok, now we know that all of the PHI nodes are missing entries for some
731193323Sed    // basic blocks.  Start by sorting the incoming predecessors for efficient
732193323Sed    // access.
733344779Sdim    auto CompareBBNumbers = [this](BasicBlock *A, BasicBlock *B) {
734353358Sdim      return BBNumbers.find(A)->second < BBNumbers.find(B)->second;
735344779Sdim    };
736344779Sdim    llvm::sort(Preds, CompareBBNumbers);
737261991Sdim
738193323Sed    // Now we loop through all BB's which have entries in SomePHI and remove
739193323Sed    // them from the Preds list.
740193323Sed    for (unsigned i = 0, e = SomePHI->getNumIncomingValues(); i != e; ++i) {
741193323Sed      // Do a log(n) search of the Preds list for the entry we want.
742353358Sdim      SmallVectorImpl<BasicBlock *>::iterator EntIt = llvm::lower_bound(
743353358Sdim          Preds, SomePHI->getIncomingBlock(i), CompareBBNumbers);
744261991Sdim      assert(EntIt != Preds.end() && *EntIt == SomePHI->getIncomingBlock(i) &&
745193323Sed             "PHI node has entry for a block which is not a predecessor!");
746193323Sed
747193323Sed      // Remove the entry
748193323Sed      Preds.erase(EntIt);
749193323Sed    }
750193323Sed
751193323Sed    // At this point, the blocks left in the preds list must have dummy
752193323Sed    // entries inserted into every PHI nodes for the block.  Update all the phi
753193323Sed    // nodes in this block that we are inserting (there could be phis before
754193323Sed    // mem2reg runs).
755193323Sed    unsigned NumBadPreds = SomePHI->getNumIncomingValues();
756193323Sed    BasicBlock::iterator BBI = BB->begin();
757193323Sed    while ((SomePHI = dyn_cast<PHINode>(BBI++)) &&
758193323Sed           SomePHI->getNumIncomingValues() == NumBadPreds) {
759193323Sed      Value *UndefVal = UndefValue::get(SomePHI->getType());
760327952Sdim      for (BasicBlock *Pred : Preds)
761327952Sdim        SomePHI->addIncoming(UndefVal, Pred);
762193323Sed    }
763193323Sed  }
764261991Sdim
765193323Sed  NewPhiNodes.clear();
766193323Sed}
767193323Sed
768341825Sdim/// Determine which blocks the value is live in.
769261991Sdim///
770261991Sdim/// These are blocks which lead to uses.  Knowing this allows us to avoid
771261991Sdim/// inserting PHI nodes into blocks which don't lead to uses (thus, the
772261991Sdim/// inserted phi nodes would be dead).
773261991Sdimvoid PromoteMem2Reg::ComputeLiveInBlocks(
774261991Sdim    AllocaInst *AI, AllocaInfo &Info,
775280031Sdim    const SmallPtrSetImpl<BasicBlock *> &DefBlocks,
776280031Sdim    SmallPtrSetImpl<BasicBlock *> &LiveInBlocks) {
777193323Sed  // To determine liveness, we must iterate through the predecessors of blocks
778193323Sed  // where the def is live.  Blocks are added to the worklist if we need to
779193323Sed  // check their predecessors.  Start with all the using blocks.
780261991Sdim  SmallVector<BasicBlock *, 64> LiveInBlockWorklist(Info.UsingBlocks.begin(),
781261991Sdim                                                    Info.UsingBlocks.end());
782261991Sdim
783193323Sed  // If any of the using blocks is also a definition block, check to see if the
784193323Sed  // definition occurs before or after the use.  If it happens before the use,
785193323Sed  // the value isn't really live-in.
786193323Sed  for (unsigned i = 0, e = LiveInBlockWorklist.size(); i != e; ++i) {
787193323Sed    BasicBlock *BB = LiveInBlockWorklist[i];
788261991Sdim    if (!DefBlocks.count(BB))
789261991Sdim      continue;
790261991Sdim
791193323Sed    // Okay, this is a block that both uses and defines the value.  If the first
792193323Sed    // reference to the alloca is a def (store), then we know it isn't live-in.
793261991Sdim    for (BasicBlock::iterator I = BB->begin();; ++I) {
794193323Sed      if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
795261991Sdim        if (SI->getOperand(1) != AI)
796261991Sdim          continue;
797261991Sdim
798193323Sed        // We found a store to the alloca before a load.  The alloca is not
799193323Sed        // actually live-in here.
800193323Sed        LiveInBlockWorklist[i] = LiveInBlockWorklist.back();
801193323Sed        LiveInBlockWorklist.pop_back();
802309124Sdim        --i;
803309124Sdim        --e;
804193323Sed        break;
805198090Srdivacky      }
806261991Sdim
807353358Sdim      if (LoadInst *LI = dyn_cast<LoadInst>(I))
808193323Sed        // Okay, we found a load before a store to the alloca.  It is actually
809193323Sed        // live into this block.
810353358Sdim        if (LI->getOperand(0) == AI)
811353358Sdim          break;
812193323Sed    }
813193323Sed  }
814261991Sdim
815193323Sed  // Now that we have a set of blocks where the phi is live-in, recursively add
816193323Sed  // their predecessors until we find the full region the value is live.
817193323Sed  while (!LiveInBlockWorklist.empty()) {
818193323Sed    BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
819261991Sdim
820193323Sed    // The block really is live in here, insert it into the set.  If already in
821193323Sed    // the set, then it has already been processed.
822280031Sdim    if (!LiveInBlocks.insert(BB).second)
823193323Sed      continue;
824261991Sdim
825193323Sed    // Since the value is live into BB, it is either defined in a predecessor or
826193323Sed    // live into it to.  Add the preds to the worklist unless they are a
827193323Sed    // defining block.
828327952Sdim    for (BasicBlock *P : predecessors(BB)) {
829193323Sed      // The value is not live into a predecessor if it defines the value.
830193323Sed      if (DefBlocks.count(P))
831193323Sed        continue;
832261991Sdim
833193323Sed      // Otherwise it is, add to the worklist.
834193323Sed      LiveInBlockWorklist.push_back(P);
835193323Sed    }
836193323Sed  }
837193323Sed}
838193323Sed
839341825Sdim/// Queue a phi-node to be added to a basic-block for a specific Alloca.
840193323Sed///
841261991Sdim/// Returns true if there wasn't already a phi-node for that variable
842193323Sedbool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo,
843218893Sdim                                  unsigned &Version) {
844193323Sed  // Look up the basic-block in question.
845243830Sdim  PHINode *&PN = NewPhiNodes[std::make_pair(BBNumbers[BB], AllocaNo)];
846193323Sed
847193323Sed  // If the BB already has a phi node added for the i'th alloca then we're done!
848261991Sdim  if (PN)
849261991Sdim    return false;
850193323Sed
851193323Sed  // Create a PhiNode using the dereferenced type... and add the phi-node to the
852193323Sed  // BasicBlock.
853221345Sdim  PN = PHINode::Create(Allocas[AllocaNo]->getAllocatedType(), getNumPreds(BB),
854261991Sdim                       Allocas[AllocaNo]->getName() + "." + Twine(Version++),
855296417Sdim                       &BB->front());
856193323Sed  ++NumPHIInsert;
857193323Sed  PhiToAllocaMap[PN] = AllocaNo;
858193323Sed  return true;
859193323Sed}
860193323Sed
861341825Sdim/// Update the debug location of a phi. \p ApplyMergedLoc indicates whether to
862341825Sdim/// create a merged location incorporating \p DL, or to set \p DL directly.
863341825Sdimstatic void updateForIncomingValueLocation(PHINode *PN, DebugLoc DL,
864341825Sdim                                           bool ApplyMergedLoc) {
865341825Sdim  if (ApplyMergedLoc)
866341825Sdim    PN->applyMergedLocation(PN->getDebugLoc(), DL);
867341825Sdim  else
868341825Sdim    PN->setDebugLoc(DL);
869341825Sdim}
870341825Sdim
871341825Sdim/// Recursively traverse the CFG of the function, renaming loads and
872261991Sdim/// stores to the allocas which we are promoting.
873261991Sdim///
874261991Sdim/// IncomingVals indicates what value each Alloca contains on exit from the
875261991Sdim/// predecessor block Pred.
876193323Sedvoid PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
877193323Sed                                RenamePassData::ValVector &IncomingVals,
878341825Sdim                                RenamePassData::LocationVector &IncomingLocs,
879193323Sed                                std::vector<RenamePassData> &Worklist) {
880193323SedNextIteration:
881193323Sed  // If we are inserting any phi nodes into this BB, they will already be in the
882193323Sed  // block.
883193323Sed  if (PHINode *APN = dyn_cast<PHINode>(BB->begin())) {
884193323Sed    // If we have PHI nodes to update, compute the number of edges from Pred to
885193323Sed    // BB.
886193323Sed    if (PhiToAllocaMap.count(APN)) {
887193323Sed      // We want to be able to distinguish between PHI nodes being inserted by
888193323Sed      // this invocation of mem2reg from those phi nodes that already existed in
889193323Sed      // the IR before mem2reg was run.  We determine that APN is being inserted
890193323Sed      // because it is missing incoming edges.  All other PHI nodes being
891193323Sed      // inserted by this pass of mem2reg will have the same number of incoming
892193323Sed      // operands so far.  Remember this count.
893193323Sed      unsigned NewPHINumOperands = APN->getNumOperands();
894261991Sdim
895261991Sdim      unsigned NumEdges = std::count(succ_begin(Pred), succ_end(Pred), BB);
896193323Sed      assert(NumEdges && "Must be at least one edge from Pred to BB!");
897261991Sdim
898193323Sed      // Add entries for all the phis.
899193323Sed      BasicBlock::iterator PNI = BB->begin();
900193323Sed      do {
901193323Sed        unsigned AllocaNo = PhiToAllocaMap[APN];
902261991Sdim
903341825Sdim        // Update the location of the phi node.
904341825Sdim        updateForIncomingValueLocation(APN, IncomingLocs[AllocaNo],
905341825Sdim                                       APN->getNumIncomingValues() > 0);
906341825Sdim
907193323Sed        // Add N incoming values to the PHI node.
908193323Sed        for (unsigned i = 0; i != NumEdges; ++i)
909193323Sed          APN->addIncoming(IncomingVals[AllocaNo], Pred);
910261991Sdim
911193323Sed        // The currently active variable for this block is now the PHI.
912193323Sed        IncomingVals[AllocaNo] = APN;
913344779Sdim        for (DbgVariableIntrinsic *DII : AllocaDbgDeclares[AllocaNo])
914327952Sdim          ConvertDebugDeclareToDebugValue(DII, APN, DIB);
915261991Sdim
916193323Sed        // Get the next phi node.
917193323Sed        ++PNI;
918193323Sed        APN = dyn_cast<PHINode>(PNI);
919276479Sdim        if (!APN)
920261991Sdim          break;
921261991Sdim
922193323Sed        // Verify that it is missing entries.  If not, it is not being inserted
923193323Sed        // by this mem2reg invocation so we want to ignore it.
924193323Sed      } while (APN->getNumOperands() == NewPHINumOperands);
925193323Sed    }
926193323Sed  }
927261991Sdim
928193323Sed  // Don't revisit blocks.
929280031Sdim  if (!Visited.insert(BB).second)
930261991Sdim    return;
931193323Sed
932344779Sdim  for (BasicBlock::iterator II = BB->begin(); !II->isTerminator();) {
933296417Sdim    Instruction *I = &*II++; // get the instruction, increment iterator
934193323Sed
935193323Sed    if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
936193323Sed      AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand());
937261991Sdim      if (!Src)
938261991Sdim        continue;
939193323Sed
940261991Sdim      DenseMap<AllocaInst *, unsigned>::iterator AI = AllocaLookup.find(Src);
941261991Sdim      if (AI == AllocaLookup.end())
942261991Sdim        continue;
943261991Sdim
944193323Sed      Value *V = IncomingVals[AI->second];
945193323Sed
946321369Sdim      // If the load was marked as nonnull we don't want to lose
947321369Sdim      // that information when we erase this Load. So we preserve
948321369Sdim      // it with an assume.
949321369Sdim      if (AC && LI->getMetadata(LLVMContext::MD_nonnull) &&
950327952Sdim          !isKnownNonZero(V, SQ.DL, 0, AC, LI, &DT))
951321369Sdim        addAssumeNonNull(AC, LI);
952321369Sdim
953193323Sed      // Anything using the load now uses the current value.
954193323Sed      LI->replaceAllUsesWith(V);
955193323Sed      BB->getInstList().erase(LI);
956193323Sed    } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
957193323Sed      // Delete this instruction and mark the name as the current holder of the
958193323Sed      // value
959193323Sed      AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand());
960261991Sdim      if (!Dest)
961261991Sdim        continue;
962261991Sdim
963218893Sdim      DenseMap<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest);
964193323Sed      if (ai == AllocaLookup.end())
965193323Sed        continue;
966261991Sdim
967193323Sed      // what value were we writing?
968341825Sdim      unsigned AllocaNo = ai->second;
969341825Sdim      IncomingVals[AllocaNo] = SI->getOperand(0);
970341825Sdim
971202878Srdivacky      // Record debuginfo for the store before removing it.
972341825Sdim      IncomingLocs[AllocaNo] = SI->getDebugLoc();
973344779Sdim      for (DbgVariableIntrinsic *DII : AllocaDbgDeclares[ai->second])
974327952Sdim        ConvertDebugDeclareToDebugValue(DII, SI, DIB);
975193323Sed      BB->getInstList().erase(SI);
976193323Sed    }
977193323Sed  }
978193323Sed
979193323Sed  // 'Recurse' to our successors.
980193323Sed  succ_iterator I = succ_begin(BB), E = succ_end(BB);
981261991Sdim  if (I == E)
982261991Sdim    return;
983193323Sed
984193323Sed  // Keep track of the successors so we don't visit the same successor twice
985261991Sdim  SmallPtrSet<BasicBlock *, 8> VisitedSuccs;
986193323Sed
987193323Sed  // Handle the first successor without using the worklist.
988193323Sed  VisitedSuccs.insert(*I);
989193323Sed  Pred = BB;
990193323Sed  BB = *I;
991193323Sed  ++I;
992193323Sed
993193323Sed  for (; I != E; ++I)
994280031Sdim    if (VisitedSuccs.insert(*I).second)
995341825Sdim      Worklist.emplace_back(*I, Pred, IncomingVals, IncomingLocs);
996193323Sed
997193323Sed  goto NextIteration;
998193323Sed}
999193323Sed
1000261991Sdimvoid llvm::PromoteMemToReg(ArrayRef<AllocaInst *> Allocas, DominatorTree &DT,
1001321369Sdim                           AssumptionCache *AC) {
1002193323Sed  // If there is nothing to do, bail out...
1003261991Sdim  if (Allocas.empty())
1004261991Sdim    return;
1005193323Sed
1006321369Sdim  PromoteMem2Reg(Allocas, DT, AC).run();
1007193323Sed}
1008