1193323Sed//===- PromoteMemoryToRegister.cpp - Convert allocas to registers ---------===//
2193323Sed//
3193323Sed//                     The LLVM Compiler Infrastructure
4193323Sed//
5193323Sed// This file is distributed under the University of Illinois Open Source
6193323Sed// License. See LICENSE.TXT for details.
7193323Sed//
8193323Sed//===----------------------------------------------------------------------===//
9193323Sed//
10193323Sed// This file promotes memory references to be register references.  It promotes
11193323Sed// alloca instructions which only have loads and stores as uses.  An alloca is
12218893Sdim// transformed by using iterated dominator frontiers to place PHI nodes, then
13218893Sdim// traversing the function in depth-first order to rewrite loads and stores as
14218893Sdim// appropriate.
15193323Sed//
16218893Sdim// The algorithm used here is based on:
17218893Sdim//
18218893Sdim//   Sreedhar and Gao. A linear time algorithm for placing phi-nodes.
19218893Sdim//   In Proceedings of the 22nd ACM SIGPLAN-SIGACT Symposium on Principles of
20218893Sdim//   Programming Languages
21218893Sdim//   POPL '95. ACM, New York, NY, 62-73.
22218893Sdim//
23218893Sdim// It has been modified to not explicitly use the DJ graph data structure and to
24218893Sdim// directly compute pruned SSA using per-variable liveness information.
25218893Sdim//
26193323Sed//===----------------------------------------------------------------------===//
27193323Sed
28193323Sed#define DEBUG_TYPE "mem2reg"
29193323Sed#include "llvm/Transforms/Utils/PromoteMemToReg.h"
30263509Sdim#include "llvm/ADT/ArrayRef.h"
31193323Sed#include "llvm/ADT/DenseMap.h"
32252723Sdim#include "llvm/ADT/STLExtras.h"
33193323Sed#include "llvm/ADT/SmallPtrSet.h"
34193323Sed#include "llvm/ADT/SmallVector.h"
35193323Sed#include "llvm/ADT/Statistic.h"
36252723Sdim#include "llvm/Analysis/AliasSetTracker.h"
37252723Sdim#include "llvm/Analysis/Dominators.h"
38252723Sdim#include "llvm/Analysis/InstructionSimplify.h"
39252723Sdim#include "llvm/Analysis/ValueTracking.h"
40252723Sdim#include "llvm/DIBuilder.h"
41252723Sdim#include "llvm/DebugInfo.h"
42252723Sdim#include "llvm/IR/Constants.h"
43252723Sdim#include "llvm/IR/DerivedTypes.h"
44252723Sdim#include "llvm/IR/Function.h"
45252723Sdim#include "llvm/IR/Instructions.h"
46252723Sdim#include "llvm/IR/IntrinsicInst.h"
47252723Sdim#include "llvm/IR/Metadata.h"
48193323Sed#include "llvm/Support/CFG.h"
49252723Sdim#include "llvm/Transforms/Utils/Local.h"
50193323Sed#include <algorithm>
51218893Sdim#include <queue>
52193323Sedusing namespace llvm;
53193323Sed
54193323SedSTATISTIC(NumLocalPromoted, "Number of alloca's promoted within one block");
55193323SedSTATISTIC(NumSingleStore,   "Number of alloca's promoted with a single store");
56193323SedSTATISTIC(NumDeadAlloca,    "Number of dead alloca's removed");
57193323SedSTATISTIC(NumPHIInsert,     "Number of PHI nodes inserted");
58193323Sed
59193323Sedbool llvm::isAllocaPromotable(const AllocaInst *AI) {
60193323Sed  // FIXME: If the memory unit is of pointer or integer type, we can permit
61193323Sed  // assignments to subsections of the memory unit.
62193323Sed
63193323Sed  // Only allow direct and non-volatile loads and stores...
64206083Srdivacky  for (Value::const_use_iterator UI = AI->use_begin(), UE = AI->use_end();
65263509Sdim       UI != UE; ++UI) { // Loop over all of the uses of the alloca
66210299Sed    const User *U = *UI;
67210299Sed    if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
68226890Sdim      // Note that atomic loads can be transformed; atomic semantics do
69226890Sdim      // not have any meaning for a local alloca.
70193323Sed      if (LI->isVolatile())
71193323Sed        return false;
72210299Sed    } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
73193323Sed      if (SI->getOperand(0) == AI)
74263509Sdim        return false; // Don't allow a store OF the AI, only INTO the AI.
75226890Sdim      // Note that atomic stores can be transformed; atomic semantics do
76226890Sdim      // not have any meaning for a local alloca.
77193323Sed      if (SI->isVolatile())
78193323Sed        return false;
79224145Sdim    } else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
80224145Sdim      if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
81224145Sdim          II->getIntrinsicID() != Intrinsic::lifetime_end)
82224145Sdim        return false;
83224145Sdim    } else if (const BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
84224145Sdim      if (BCI->getType() != Type::getInt8PtrTy(U->getContext()))
85224145Sdim        return false;
86224145Sdim      if (!onlyUsedByLifetimeMarkers(BCI))
87224145Sdim        return false;
88224145Sdim    } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
89224145Sdim      if (GEPI->getType() != Type::getInt8PtrTy(U->getContext()))
90224145Sdim        return false;
91224145Sdim      if (!GEPI->hasAllZeroIndices())
92224145Sdim        return false;
93224145Sdim      if (!onlyUsedByLifetimeMarkers(GEPI))
94224145Sdim        return false;
95193323Sed    } else {
96193323Sed      return false;
97193323Sed    }
98210299Sed  }
99193323Sed
100193323Sed  return true;
101193323Sed}
102193323Sed
103193323Sednamespace {
104193323Sed
105263509Sdimstruct AllocaInfo {
106263509Sdim  SmallVector<BasicBlock *, 32> DefiningBlocks;
107263509Sdim  SmallVector<BasicBlock *, 32> UsingBlocks;
108263509Sdim
109263509Sdim  StoreInst *OnlyStore;
110263509Sdim  BasicBlock *OnlyBlock;
111263509Sdim  bool OnlyUsedInOneBlock;
112263509Sdim
113263509Sdim  Value *AllocaPointerVal;
114263509Sdim  DbgDeclareInst *DbgDeclare;
115263509Sdim
116263509Sdim  void clear() {
117263509Sdim    DefiningBlocks.clear();
118263509Sdim    UsingBlocks.clear();
119263509Sdim    OnlyStore = 0;
120263509Sdim    OnlyBlock = 0;
121263509Sdim    OnlyUsedInOneBlock = true;
122263509Sdim    AllocaPointerVal = 0;
123263509Sdim    DbgDeclare = 0;
124263509Sdim  }
125263509Sdim
126263509Sdim  /// Scan the uses of the specified alloca, filling in the AllocaInfo used
127263509Sdim  /// by the rest of the pass to reason about the uses of this alloca.
128263509Sdim  void AnalyzeAlloca(AllocaInst *AI) {
129263509Sdim    clear();
130263509Sdim
131263509Sdim    // As we scan the uses of the alloca instruction, keep track of stores,
132263509Sdim    // and decide whether all of the loads and stores to the alloca are within
133263509Sdim    // the same basic block.
134263509Sdim    for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
135263509Sdim         UI != E;) {
136263509Sdim      Instruction *User = cast<Instruction>(*UI++);
137263509Sdim
138263509Sdim      if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
139263509Sdim        // Remember the basic blocks which define new values for the alloca
140263509Sdim        DefiningBlocks.push_back(SI->getParent());
141263509Sdim        AllocaPointerVal = SI->getOperand(0);
142263509Sdim        OnlyStore = SI;
143263509Sdim      } else {
144263509Sdim        LoadInst *LI = cast<LoadInst>(User);
145263509Sdim        // Otherwise it must be a load instruction, keep track of variable
146263509Sdim        // reads.
147263509Sdim        UsingBlocks.push_back(LI->getParent());
148263509Sdim        AllocaPointerVal = LI;
149263509Sdim      }
150263509Sdim
151263509Sdim      if (OnlyUsedInOneBlock) {
152263509Sdim        if (OnlyBlock == 0)
153263509Sdim          OnlyBlock = User->getParent();
154263509Sdim        else if (OnlyBlock != User->getParent())
155263509Sdim          OnlyUsedInOneBlock = false;
156263509Sdim      }
157193323Sed    }
158263509Sdim
159263509Sdim    DbgDeclare = FindAllocaDbgDeclare(AI);
160263509Sdim  }
161263509Sdim};
162263509Sdim
163263509Sdim// Data package used by RenamePass()
164263509Sdimclass RenamePassData {
165263509Sdimpublic:
166263509Sdim  typedef std::vector<Value *> ValVector;
167263509Sdim
168263509Sdim  RenamePassData() : BB(NULL), Pred(NULL), Values() {}
169263509Sdim  RenamePassData(BasicBlock *B, BasicBlock *P, const ValVector &V)
170263509Sdim      : BB(B), Pred(P), Values(V) {}
171263509Sdim  BasicBlock *BB;
172263509Sdim  BasicBlock *Pred;
173263509Sdim  ValVector Values;
174263509Sdim
175263509Sdim  void swap(RenamePassData &RHS) {
176263509Sdim    std::swap(BB, RHS.BB);
177263509Sdim    std::swap(Pred, RHS.Pred);
178263509Sdim    Values.swap(RHS.Values);
179263509Sdim  }
180263509Sdim};
181263509Sdim
182263509Sdim/// \brief This assigns and keeps a per-bb relative ordering of load/store
183263509Sdim/// instructions in the block that directly load or store an alloca.
184263509Sdim///
185263509Sdim/// This functionality is important because it avoids scanning large basic
186263509Sdim/// blocks multiple times when promoting many allocas in the same block.
187263509Sdimclass LargeBlockInfo {
188263509Sdim  /// \brief For each instruction that we track, keep the index of the
189263509Sdim  /// instruction.
190193323Sed  ///
191263509Sdim  /// The index starts out as the number of the instruction from the start of
192263509Sdim  /// the block.
193263509Sdim  DenseMap<const Instruction *, unsigned> InstNumbers;
194263509Sdim
195263509Sdimpublic:
196263509Sdim
197263509Sdim  /// This code only looks at accesses to allocas.
198263509Sdim  static bool isInterestingInstruction(const Instruction *I) {
199263509Sdim    return (isa<LoadInst>(I) && isa<AllocaInst>(I->getOperand(0))) ||
200263509Sdim           (isa<StoreInst>(I) && isa<AllocaInst>(I->getOperand(1)));
201263509Sdim  }
202263509Sdim
203263509Sdim  /// Get or calculate the index of the specified instruction.
204263509Sdim  unsigned getInstructionIndex(const Instruction *I) {
205263509Sdim    assert(isInterestingInstruction(I) &&
206263509Sdim           "Not a load/store to/from an alloca?");
207263509Sdim
208263509Sdim    // If we already have this instruction number, return it.
209263509Sdim    DenseMap<const Instruction *, unsigned>::iterator It = InstNumbers.find(I);
210263509Sdim    if (It != InstNumbers.end())
211193323Sed      return It->second;
212193323Sed
213263509Sdim    // Scan the whole block to get the instruction.  This accumulates
214263509Sdim    // information for every interesting instruction in the block, in order to
215263509Sdim    // avoid gratuitus rescans.
216263509Sdim    const BasicBlock *BB = I->getParent();
217263509Sdim    unsigned InstNo = 0;
218263509Sdim    for (BasicBlock::const_iterator BBI = BB->begin(), E = BB->end(); BBI != E;
219263509Sdim         ++BBI)
220263509Sdim      if (isInterestingInstruction(BBI))
221263509Sdim        InstNumbers[BBI] = InstNo++;
222263509Sdim    It = InstNumbers.find(I);
223193323Sed
224263509Sdim    assert(It != InstNumbers.end() && "Didn't insert instruction?");
225263509Sdim    return It->second;
226263509Sdim  }
227193323Sed
228263509Sdim  void deleteValue(const Instruction *I) { InstNumbers.erase(I); }
229193323Sed
230263509Sdim  void clear() { InstNumbers.clear(); }
231263509Sdim};
232203954Srdivacky
233263509Sdimstruct PromoteMem2Reg {
234263509Sdim  /// The alloca instructions being promoted.
235263509Sdim  std::vector<AllocaInst *> Allocas;
236263509Sdim  DominatorTree &DT;
237263509Sdim  DIBuilder DIB;
238193323Sed
239263509Sdim  /// An AliasSetTracker object to update.  If null, don't update it.
240263509Sdim  AliasSetTracker *AST;
241193323Sed
242263509Sdim  /// Reverse mapping of Allocas.
243263509Sdim  DenseMap<AllocaInst *, unsigned> AllocaLookup;
244218893Sdim
245263509Sdim  /// \brief The PhiNodes we're adding.
246263509Sdim  ///
247263509Sdim  /// That map is used to simplify some Phi nodes as we iterate over it, so
248263509Sdim  /// it should have deterministic iterators.  We could use a MapVector, but
249263509Sdim  /// since we already maintain a map from BasicBlock* to a stable numbering
250263509Sdim  /// (BBNumbers), the DenseMap is more efficient (also supports removal).
251263509Sdim  DenseMap<std::pair<unsigned, unsigned>, PHINode *> NewPhiNodes;
252193323Sed
253263509Sdim  /// For each PHI node, keep track of which entry in Allocas it corresponds
254263509Sdim  /// to.
255263509Sdim  DenseMap<PHINode *, unsigned> PhiToAllocaMap;
256193323Sed
257263509Sdim  /// If we are updating an AliasSetTracker, then for each alloca that is of
258263509Sdim  /// pointer type, we keep track of what to copyValue to the inserted PHI
259263509Sdim  /// nodes here.
260263509Sdim  std::vector<Value *> PointerAllocaValues;
261193323Sed
262263509Sdim  /// For each alloca, we keep track of the dbg.declare intrinsic that
263263509Sdim  /// describes it, if any, so that we can convert it to a dbg.value
264263509Sdim  /// intrinsic if the alloca gets promoted.
265263509Sdim  SmallVector<DbgDeclareInst *, 8> AllocaDbgDeclares;
266193323Sed
267263509Sdim  /// The set of basic blocks the renamer has already visited.
268263509Sdim  ///
269263509Sdim  SmallPtrSet<BasicBlock *, 16> Visited;
270193323Sed
271263509Sdim  /// Contains a stable numbering of basic blocks to avoid non-determinstic
272263509Sdim  /// behavior.
273263509Sdim  DenseMap<BasicBlock *, unsigned> BBNumbers;
274193323Sed
275263509Sdim  /// Maps DomTreeNodes to their level in the dominator tree.
276263509Sdim  DenseMap<DomTreeNode *, unsigned> DomLevels;
277202878Srdivacky
278263509Sdim  /// Lazily compute the number of predecessors a block has.
279263509Sdim  DenseMap<const BasicBlock *, unsigned> BBNumPreds;
280218893Sdim
281263509Sdimpublic:
282263509Sdim  PromoteMem2Reg(ArrayRef<AllocaInst *> Allocas, DominatorTree &DT,
283263509Sdim                 AliasSetTracker *AST)
284263509Sdim      : Allocas(Allocas.begin(), Allocas.end()), DT(DT),
285263509Sdim        DIB(*DT.getRoot()->getParent()->getParent()), AST(AST) {}
286218893Sdim
287263509Sdim  void run();
288193323Sed
289263509Sdimprivate:
290263509Sdim  void RemoveFromAllocasList(unsigned &AllocaIdx) {
291263509Sdim    Allocas[AllocaIdx] = Allocas.back();
292263509Sdim    Allocas.pop_back();
293263509Sdim    --AllocaIdx;
294263509Sdim  }
295263509Sdim
296263509Sdim  unsigned getNumPreds(const BasicBlock *BB) {
297263509Sdim    unsigned &NP = BBNumPreds[BB];
298263509Sdim    if (NP == 0)
299263509Sdim      NP = std::distance(pred_begin(BB), pred_end(BB)) + 1;
300263509Sdim    return NP - 1;
301263509Sdim  }
302263509Sdim
303263509Sdim  void DetermineInsertionPoint(AllocaInst *AI, unsigned AllocaNum,
304263509Sdim                               AllocaInfo &Info);
305263509Sdim  void ComputeLiveInBlocks(AllocaInst *AI, AllocaInfo &Info,
306263509Sdim                           const SmallPtrSet<BasicBlock *, 32> &DefBlocks,
307263509Sdim                           SmallPtrSet<BasicBlock *, 32> &LiveInBlocks);
308263509Sdim  void RenamePass(BasicBlock *BB, BasicBlock *Pred,
309263509Sdim                  RenamePassData::ValVector &IncVals,
310263509Sdim                  std::vector<RenamePassData> &Worklist);
311263509Sdim  bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx, unsigned &Version);
312263509Sdim};
313263509Sdim
314263509Sdim} // end of anonymous namespace
315263509Sdim
316224145Sdimstatic void removeLifetimeIntrinsicUsers(AllocaInst *AI) {
317224145Sdim  // Knowing that this alloca is promotable, we know that it's safe to kill all
318224145Sdim  // instructions except for load and store.
319193323Sed
320224145Sdim  for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
321224145Sdim       UI != UE;) {
322224145Sdim    Instruction *I = cast<Instruction>(*UI);
323224145Sdim    ++UI;
324224145Sdim    if (isa<LoadInst>(I) || isa<StoreInst>(I))
325224145Sdim      continue;
326224145Sdim
327224145Sdim    if (!I->getType()->isVoidTy()) {
328224145Sdim      // The only users of this bitcast/GEP instruction are lifetime intrinsics.
329224145Sdim      // Follow the use/def chain to erase them now instead of leaving it for
330224145Sdim      // dead code elimination later.
331224145Sdim      for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
332224145Sdim           UI != UE;) {
333224145Sdim        Instruction *Inst = cast<Instruction>(*UI);
334224145Sdim        ++UI;
335224145Sdim        Inst->eraseFromParent();
336224145Sdim      }
337224145Sdim    }
338224145Sdim    I->eraseFromParent();
339224145Sdim  }
340224145Sdim}
341224145Sdim
342263509Sdim/// \brief Rewrite as many loads as possible given a single store.
343263509Sdim///
344263509Sdim/// When there is only a single store, we can use the domtree to trivially
345263509Sdim/// replace all of the dominated loads with the stored value. Do so, and return
346263509Sdim/// true if this has successfully promoted the alloca entirely. If this returns
347263509Sdim/// false there were some loads which were not dominated by the single store
348263509Sdim/// and thus must be phi-ed with undef. We fall back to the standard alloca
349263509Sdim/// promotion algorithm in that case.
350263509Sdimstatic bool rewriteSingleStoreAlloca(AllocaInst *AI, AllocaInfo &Info,
351263509Sdim                                     LargeBlockInfo &LBI,
352263509Sdim                                     DominatorTree &DT,
353263509Sdim                                     AliasSetTracker *AST) {
354263509Sdim  StoreInst *OnlyStore = Info.OnlyStore;
355263509Sdim  bool StoringGlobalVal = !isa<Instruction>(OnlyStore->getOperand(0));
356263509Sdim  BasicBlock *StoreBB = OnlyStore->getParent();
357263509Sdim  int StoreIndex = -1;
358263509Sdim
359263509Sdim  // Clear out UsingBlocks.  We will reconstruct it here if needed.
360263509Sdim  Info.UsingBlocks.clear();
361263509Sdim
362263509Sdim  for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end(); UI != E;) {
363263509Sdim    Instruction *UserInst = cast<Instruction>(*UI++);
364263509Sdim    if (!isa<LoadInst>(UserInst)) {
365263509Sdim      assert(UserInst == OnlyStore && "Should only have load/stores");
366263509Sdim      continue;
367263509Sdim    }
368263509Sdim    LoadInst *LI = cast<LoadInst>(UserInst);
369263509Sdim
370263509Sdim    // Okay, if we have a load from the alloca, we want to replace it with the
371263509Sdim    // only value stored to the alloca.  We can do this if the value is
372263509Sdim    // dominated by the store.  If not, we use the rest of the mem2reg machinery
373263509Sdim    // to insert the phi nodes as needed.
374263509Sdim    if (!StoringGlobalVal) { // Non-instructions are always dominated.
375263509Sdim      if (LI->getParent() == StoreBB) {
376263509Sdim        // If we have a use that is in the same block as the store, compare the
377263509Sdim        // indices of the two instructions to see which one came first.  If the
378263509Sdim        // load came before the store, we can't handle it.
379263509Sdim        if (StoreIndex == -1)
380263509Sdim          StoreIndex = LBI.getInstructionIndex(OnlyStore);
381263509Sdim
382263509Sdim        if (unsigned(StoreIndex) > LBI.getInstructionIndex(LI)) {
383263509Sdim          // Can't handle this load, bail out.
384263509Sdim          Info.UsingBlocks.push_back(StoreBB);
385263509Sdim          continue;
386263509Sdim        }
387263509Sdim
388263509Sdim      } else if (LI->getParent() != StoreBB &&
389263509Sdim                 !DT.dominates(StoreBB, LI->getParent())) {
390263509Sdim        // If the load and store are in different blocks, use BB dominance to
391263509Sdim        // check their relationships.  If the store doesn't dom the use, bail
392263509Sdim        // out.
393263509Sdim        Info.UsingBlocks.push_back(LI->getParent());
394263509Sdim        continue;
395263509Sdim      }
396263509Sdim    }
397263509Sdim
398263509Sdim    // Otherwise, we *can* safely rewrite this load.
399263509Sdim    Value *ReplVal = OnlyStore->getOperand(0);
400263509Sdim    // If the replacement value is the load, this must occur in unreachable
401263509Sdim    // code.
402263509Sdim    if (ReplVal == LI)
403263509Sdim      ReplVal = UndefValue::get(LI->getType());
404263509Sdim    LI->replaceAllUsesWith(ReplVal);
405263509Sdim    if (AST && LI->getType()->isPointerTy())
406263509Sdim      AST->deleteValue(LI);
407263509Sdim    LI->eraseFromParent();
408263509Sdim    LBI.deleteValue(LI);
409263509Sdim  }
410263509Sdim
411263509Sdim  // Finally, after the scan, check to see if the store is all that is left.
412263509Sdim  if (!Info.UsingBlocks.empty())
413263509Sdim    return false; // If not, we'll have to fall back for the remainder.
414263509Sdim
415263509Sdim  // Record debuginfo for the store and remove the declaration's
416263509Sdim  // debuginfo.
417263509Sdim  if (DbgDeclareInst *DDI = Info.DbgDeclare) {
418263509Sdim    DIBuilder DIB(*AI->getParent()->getParent()->getParent());
419263509Sdim    ConvertDebugDeclareToDebugValue(DDI, Info.OnlyStore, DIB);
420263509Sdim    DDI->eraseFromParent();
421263509Sdim    LBI.deleteValue(DDI);
422263509Sdim  }
423263509Sdim  // Remove the (now dead) store and alloca.
424263509Sdim  Info.OnlyStore->eraseFromParent();
425263509Sdim  LBI.deleteValue(Info.OnlyStore);
426263509Sdim
427263509Sdim  if (AST)
428263509Sdim    AST->deleteValue(AI);
429263509Sdim  AI->eraseFromParent();
430263509Sdim  LBI.deleteValue(AI);
431263509Sdim  return true;
432263509Sdim}
433263509Sdim
434263509Sdim/// Many allocas are only used within a single basic block.  If this is the
435263509Sdim/// case, avoid traversing the CFG and inserting a lot of potentially useless
436263509Sdim/// PHI nodes by just performing a single linear pass over the basic block
437263509Sdim/// using the Alloca.
438263509Sdim///
439263509Sdim/// If we cannot promote this alloca (because it is read before it is written),
440263509Sdim/// return true.  This is necessary in cases where, due to control flow, the
441263509Sdim/// alloca is potentially undefined on some control flow paths.  e.g. code like
442263509Sdim/// this is potentially correct:
443263509Sdim///
444263509Sdim///   for (...) { if (c) { A = undef; undef = B; } }
445263509Sdim///
446263509Sdim/// ... so long as A is not used before undef is set.
447263509Sdimstatic void promoteSingleBlockAlloca(AllocaInst *AI, const AllocaInfo &Info,
448263509Sdim                                     LargeBlockInfo &LBI,
449263509Sdim                                     AliasSetTracker *AST) {
450263509Sdim  // The trickiest case to handle is when we have large blocks. Because of this,
451263509Sdim  // this code is optimized assuming that large blocks happen.  This does not
452263509Sdim  // significantly pessimize the small block case.  This uses LargeBlockInfo to
453263509Sdim  // make it efficient to get the index of various operations in the block.
454263509Sdim
455263509Sdim  // Walk the use-def list of the alloca, getting the locations of all stores.
456263509Sdim  typedef SmallVector<std::pair<unsigned, StoreInst *>, 64> StoresByIndexTy;
457263509Sdim  StoresByIndexTy StoresByIndex;
458263509Sdim
459263509Sdim  for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end(); UI != E;
460263509Sdim       ++UI)
461263509Sdim    if (StoreInst *SI = dyn_cast<StoreInst>(*UI))
462263509Sdim      StoresByIndex.push_back(std::make_pair(LBI.getInstructionIndex(SI), SI));
463263509Sdim
464263509Sdim  // Sort the stores by their index, making it efficient to do a lookup with a
465263509Sdim  // binary search.
466263509Sdim  std::sort(StoresByIndex.begin(), StoresByIndex.end(), less_first());
467263509Sdim
468263509Sdim  // Walk all of the loads from this alloca, replacing them with the nearest
469263509Sdim  // store above them, if any.
470263509Sdim  for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end(); UI != E;) {
471263509Sdim    LoadInst *LI = dyn_cast<LoadInst>(*UI++);
472263509Sdim    if (!LI)
473263509Sdim      continue;
474263509Sdim
475263509Sdim    unsigned LoadIdx = LBI.getInstructionIndex(LI);
476263509Sdim
477263509Sdim    // Find the nearest store that has a lower index than this load.
478263509Sdim    StoresByIndexTy::iterator I =
479263509Sdim        std::lower_bound(StoresByIndex.begin(), StoresByIndex.end(),
480263509Sdim                         std::make_pair(LoadIdx, static_cast<StoreInst *>(0)),
481263509Sdim                         less_first());
482263509Sdim
483263509Sdim    if (I == StoresByIndex.begin())
484263509Sdim      // If there is no store before this load, the load takes the undef value.
485263509Sdim      LI->replaceAllUsesWith(UndefValue::get(LI->getType()));
486263509Sdim    else
487263509Sdim      // Otherwise, there was a store before this load, the load takes its value.
488263509Sdim      LI->replaceAllUsesWith(llvm::prior(I)->second->getOperand(0));
489263509Sdim
490263509Sdim    if (AST && LI->getType()->isPointerTy())
491263509Sdim      AST->deleteValue(LI);
492263509Sdim    LI->eraseFromParent();
493263509Sdim    LBI.deleteValue(LI);
494263509Sdim  }
495263509Sdim
496263509Sdim  // Remove the (now dead) stores and alloca.
497263509Sdim  while (!AI->use_empty()) {
498263509Sdim    StoreInst *SI = cast<StoreInst>(AI->use_back());
499263509Sdim    // Record debuginfo for the store before removing it.
500263509Sdim    if (DbgDeclareInst *DDI = Info.DbgDeclare) {
501263509Sdim      DIBuilder DIB(*AI->getParent()->getParent()->getParent());
502263509Sdim      ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
503263509Sdim    }
504263509Sdim    SI->eraseFromParent();
505263509Sdim    LBI.deleteValue(SI);
506263509Sdim  }
507263509Sdim
508263509Sdim  if (AST)
509263509Sdim    AST->deleteValue(AI);
510263509Sdim  AI->eraseFromParent();
511263509Sdim  LBI.deleteValue(AI);
512263509Sdim
513263509Sdim  // The alloca's debuginfo can be removed as well.
514263509Sdim  if (DbgDeclareInst *DDI = Info.DbgDeclare) {
515263509Sdim    DDI->eraseFromParent();
516263509Sdim    LBI.deleteValue(DDI);
517263509Sdim  }
518263509Sdim
519263509Sdim  ++NumLocalPromoted;
520263509Sdim}
521263509Sdim
522193323Sedvoid PromoteMem2Reg::run() {
523218893Sdim  Function &F = *DT.getRoot()->getParent();
524193323Sed
525263509Sdim  if (AST)
526263509Sdim    PointerAllocaValues.resize(Allocas.size());
527203954Srdivacky  AllocaDbgDeclares.resize(Allocas.size());
528193323Sed
529193323Sed  AllocaInfo Info;
530193323Sed  LargeBlockInfo LBI;
531193323Sed
532193323Sed  for (unsigned AllocaNum = 0; AllocaNum != Allocas.size(); ++AllocaNum) {
533193323Sed    AllocaInst *AI = Allocas[AllocaNum];
534193323Sed
535263509Sdim    assert(isAllocaPromotable(AI) && "Cannot promote non-promotable alloca!");
536193323Sed    assert(AI->getParent()->getParent() == &F &&
537193323Sed           "All allocas should be in the same function, which is same as DF!");
538193323Sed
539224145Sdim    removeLifetimeIntrinsicUsers(AI);
540224145Sdim
541193323Sed    if (AI->use_empty()) {
542193323Sed      // If there are no uses of the alloca, just delete it now.
543263509Sdim      if (AST)
544263509Sdim        AST->deleteValue(AI);
545193323Sed      AI->eraseFromParent();
546193323Sed
547193323Sed      // Remove the alloca from the Allocas list, since it has been processed
548193323Sed      RemoveFromAllocasList(AllocaNum);
549193323Sed      ++NumDeadAlloca;
550193323Sed      continue;
551193323Sed    }
552263509Sdim
553193323Sed    // Calculate the set of read and write-locations for each alloca.  This is
554193323Sed    // analogous to finding the 'uses' and 'definitions' of each variable.
555193323Sed    Info.AnalyzeAlloca(AI);
556193323Sed
557193323Sed    // If there is only a single store to this value, replace any loads of
558193323Sed    // it that are directly dominated by the definition with the value stored.
559193323Sed    if (Info.DefiningBlocks.size() == 1) {
560263509Sdim      if (rewriteSingleStoreAlloca(AI, Info, LBI, DT, AST)) {
561193323Sed        // The alloca has been processed, move on.
562193323Sed        RemoveFromAllocasList(AllocaNum);
563193323Sed        ++NumSingleStore;
564193323Sed        continue;
565193323Sed      }
566193323Sed    }
567263509Sdim
568193323Sed    // If the alloca is only read and written in one basic block, just perform a
569193323Sed    // linear sweep over the block to eliminate it.
570193323Sed    if (Info.OnlyUsedInOneBlock) {
571263509Sdim      promoteSingleBlockAlloca(AI, Info, LBI, AST);
572203954Srdivacky
573263509Sdim      // The alloca has been processed, move on.
574263509Sdim      RemoveFromAllocasList(AllocaNum);
575263509Sdim      continue;
576193323Sed    }
577218893Sdim
578218893Sdim    // If we haven't computed dominator tree levels, do so now.
579218893Sdim    if (DomLevels.empty()) {
580263509Sdim      SmallVector<DomTreeNode *, 32> Worklist;
581218893Sdim
582218893Sdim      DomTreeNode *Root = DT.getRootNode();
583218893Sdim      DomLevels[Root] = 0;
584218893Sdim      Worklist.push_back(Root);
585218893Sdim
586218893Sdim      while (!Worklist.empty()) {
587218893Sdim        DomTreeNode *Node = Worklist.pop_back_val();
588218893Sdim        unsigned ChildLevel = DomLevels[Node] + 1;
589218893Sdim        for (DomTreeNode::iterator CI = Node->begin(), CE = Node->end();
590218893Sdim             CI != CE; ++CI) {
591218893Sdim          DomLevels[*CI] = ChildLevel;
592218893Sdim          Worklist.push_back(*CI);
593218893Sdim        }
594218893Sdim      }
595218893Sdim    }
596218893Sdim
597193323Sed    // If we haven't computed a numbering for the BB's in the function, do so
598193323Sed    // now.
599193323Sed    if (BBNumbers.empty()) {
600193323Sed      unsigned ID = 0;
601193323Sed      for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
602193323Sed        BBNumbers[I] = ID++;
603193323Sed    }
604193323Sed
605193323Sed    // If we have an AST to keep updated, remember some pointer value that is
606193323Sed    // stored into the alloca.
607193323Sed    if (AST)
608193323Sed      PointerAllocaValues[AllocaNum] = Info.AllocaPointerVal;
609263509Sdim
610203954Srdivacky    // Remember the dbg.declare intrinsic describing this alloca, if any.
611263509Sdim    if (Info.DbgDeclare)
612263509Sdim      AllocaDbgDeclares[AllocaNum] = Info.DbgDeclare;
613263509Sdim
614193323Sed    // Keep the reverse mapping of the 'Allocas' array for the rename pass.
615193323Sed    AllocaLookup[Allocas[AllocaNum]] = AllocaNum;
616193323Sed
617193323Sed    // At this point, we're committed to promoting the alloca using IDF's, and
618193323Sed    // the standard SSA construction algorithm.  Determine which blocks need PHI
619193323Sed    // nodes and see if we can optimize out some work by avoiding insertion of
620193323Sed    // dead phi nodes.
621193323Sed    DetermineInsertionPoint(AI, AllocaNum, Info);
622193323Sed  }
623193323Sed
624193323Sed  if (Allocas.empty())
625193323Sed    return; // All of the allocas must have been trivial!
626193323Sed
627193323Sed  LBI.clear();
628263509Sdim
629193323Sed  // Set the incoming values for the basic block to be null values for all of
630193323Sed  // the alloca's.  We do this in case there is a load of a value that has not
631193323Sed  // been stored yet.  In this case, it will get this null value.
632193323Sed  //
633193323Sed  RenamePassData::ValVector Values(Allocas.size());
634193323Sed  for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
635193323Sed    Values[i] = UndefValue::get(Allocas[i]->getAllocatedType());
636193323Sed
637193323Sed  // Walks all basic blocks in the function performing the SSA rename algorithm
638193323Sed  // and inserting the phi nodes we marked as necessary
639193323Sed  //
640193323Sed  std::vector<RenamePassData> RenamePassWorkList;
641193323Sed  RenamePassWorkList.push_back(RenamePassData(F.begin(), 0, Values));
642202375Srdivacky  do {
643193323Sed    RenamePassData RPD;
644193323Sed    RPD.swap(RenamePassWorkList.back());
645193323Sed    RenamePassWorkList.pop_back();
646193323Sed    // RenamePass may add new worklist entries.
647193323Sed    RenamePass(RPD.BB, RPD.Pred, RPD.Values, RenamePassWorkList);
648202375Srdivacky  } while (!RenamePassWorkList.empty());
649263509Sdim
650193323Sed  // The renamer uses the Visited set to avoid infinite loops.  Clear it now.
651193323Sed  Visited.clear();
652193323Sed
653193323Sed  // Remove the allocas themselves from the function.
654193323Sed  for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
655193323Sed    Instruction *A = Allocas[i];
656193323Sed
657193323Sed    // If there are any uses of the alloca instructions left, they must be in
658218893Sdim    // unreachable basic blocks that were not processed by walking the dominator
659218893Sdim    // tree. Just delete the users now.
660193323Sed    if (!A->use_empty())
661193323Sed      A->replaceAllUsesWith(UndefValue::get(A->getType()));
662263509Sdim    if (AST)
663263509Sdim      AST->deleteValue(A);
664193323Sed    A->eraseFromParent();
665193323Sed  }
666193323Sed
667203954Srdivacky  // Remove alloca's dbg.declare instrinsics from the function.
668203954Srdivacky  for (unsigned i = 0, e = AllocaDbgDeclares.size(); i != e; ++i)
669203954Srdivacky    if (DbgDeclareInst *DDI = AllocaDbgDeclares[i])
670203954Srdivacky      DDI->eraseFromParent();
671203954Srdivacky
672193323Sed  // Loop over all of the PHI nodes and see if there are any that we can get
673193323Sed  // rid of because they merge all of the same incoming values.  This can
674193323Sed  // happen due to undef values coming into the PHI nodes.  This process is
675193323Sed  // iterative, because eliminating one PHI node can cause others to be removed.
676193323Sed  bool EliminatedAPHI = true;
677193323Sed  while (EliminatedAPHI) {
678193323Sed    EliminatedAPHI = false;
679263509Sdim
680245431Sdim    // Iterating over NewPhiNodes is deterministic, so it is safe to try to
681245431Sdim    // simplify and RAUW them as we go.  If it was not, we could add uses to
682245431Sdim    // the values we replace with in a non deterministic order, thus creating
683245431Sdim    // non deterministic def->use chains.
684263509Sdim    for (DenseMap<std::pair<unsigned, unsigned>, PHINode *>::iterator
685263509Sdim             I = NewPhiNodes.begin(),
686263509Sdim             E = NewPhiNodes.end();
687263509Sdim         I != E;) {
688193323Sed      PHINode *PN = I->second;
689218893Sdim
690193323Sed      // If this PHI node merges one value and/or undefs, get the value.
691235633Sdim      if (Value *V = SimplifyInstruction(PN, 0, 0, &DT)) {
692204642Srdivacky        if (AST && PN->getType()->isPointerTy())
693198090Srdivacky          AST->deleteValue(PN);
694198090Srdivacky        PN->replaceAllUsesWith(V);
695198090Srdivacky        PN->eraseFromParent();
696198090Srdivacky        NewPhiNodes.erase(I++);
697198090Srdivacky        EliminatedAPHI = true;
698198090Srdivacky        continue;
699193323Sed      }
700193323Sed      ++I;
701193323Sed    }
702193323Sed  }
703263509Sdim
704193323Sed  // At this point, the renamer has added entries to PHI nodes for all reachable
705193323Sed  // code.  Unfortunately, there may be unreachable blocks which the renamer
706193323Sed  // hasn't traversed.  If this is the case, the PHI nodes may not
707193323Sed  // have incoming values for all predecessors.  Loop over all PHI nodes we have
708193323Sed  // created, inserting undef values if they are missing any incoming values.
709193323Sed  //
710263509Sdim  for (DenseMap<std::pair<unsigned, unsigned>, PHINode *>::iterator
711263509Sdim           I = NewPhiNodes.begin(),
712263509Sdim           E = NewPhiNodes.end();
713263509Sdim       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.
728263509Sdim    SmallVector<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB));
729263509Sdim
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.
733193323Sed    std::sort(Preds.begin(), Preds.end());
734263509Sdim
735193323Sed    // Now we loop through all BB's which have entries in SomePHI and remove
736193323Sed    // them from the Preds list.
737193323Sed    for (unsigned i = 0, e = SomePHI->getNumIncomingValues(); i != e; ++i) {
738193323Sed      // Do a log(n) search of the Preds list for the entry we want.
739263509Sdim      SmallVectorImpl<BasicBlock *>::iterator EntIt = std::lower_bound(
740263509Sdim          Preds.begin(), Preds.end(), SomePHI->getIncomingBlock(i));
741263509Sdim      assert(EntIt != Preds.end() && *EntIt == SomePHI->getIncomingBlock(i) &&
742193323Sed             "PHI node has entry for a block which is not a predecessor!");
743193323Sed
744193323Sed      // Remove the entry
745193323Sed      Preds.erase(EntIt);
746193323Sed    }
747193323Sed
748193323Sed    // At this point, the blocks left in the preds list must have dummy
749193323Sed    // entries inserted into every PHI nodes for the block.  Update all the phi
750193323Sed    // nodes in this block that we are inserting (there could be phis before
751193323Sed    // mem2reg runs).
752193323Sed    unsigned NumBadPreds = SomePHI->getNumIncomingValues();
753193323Sed    BasicBlock::iterator BBI = BB->begin();
754193323Sed    while ((SomePHI = dyn_cast<PHINode>(BBI++)) &&
755193323Sed           SomePHI->getNumIncomingValues() == NumBadPreds) {
756193323Sed      Value *UndefVal = UndefValue::get(SomePHI->getType());
757193323Sed      for (unsigned pred = 0, e = Preds.size(); pred != e; ++pred)
758193323Sed        SomePHI->addIncoming(UndefVal, Preds[pred]);
759193323Sed    }
760193323Sed  }
761263509Sdim
762193323Sed  NewPhiNodes.clear();
763193323Sed}
764193323Sed
765263509Sdim/// \brief Determine which blocks the value is live in.
766263509Sdim///
767263509Sdim/// These are blocks which lead to uses.  Knowing this allows us to avoid
768263509Sdim/// inserting PHI nodes into blocks which don't lead to uses (thus, the
769263509Sdim/// inserted phi nodes would be dead).
770263509Sdimvoid PromoteMem2Reg::ComputeLiveInBlocks(
771263509Sdim    AllocaInst *AI, AllocaInfo &Info,
772263509Sdim    const SmallPtrSet<BasicBlock *, 32> &DefBlocks,
773263509Sdim    SmallPtrSet<BasicBlock *, 32> &LiveInBlocks) {
774193323Sed
775193323Sed  // To determine liveness, we must iterate through the predecessors of blocks
776193323Sed  // where the def is live.  Blocks are added to the worklist if we need to
777193323Sed  // check their predecessors.  Start with all the using blocks.
778263509Sdim  SmallVector<BasicBlock *, 64> LiveInBlockWorklist(Info.UsingBlocks.begin(),
779263509Sdim                                                    Info.UsingBlocks.end());
780263509Sdim
781193323Sed  // If any of the using blocks is also a definition block, check to see if the
782193323Sed  // definition occurs before or after the use.  If it happens before the use,
783193323Sed  // the value isn't really live-in.
784193323Sed  for (unsigned i = 0, e = LiveInBlockWorklist.size(); i != e; ++i) {
785193323Sed    BasicBlock *BB = LiveInBlockWorklist[i];
786263509Sdim    if (!DefBlocks.count(BB))
787263509Sdim      continue;
788263509Sdim
789193323Sed    // Okay, this is a block that both uses and defines the value.  If the first
790193323Sed    // reference to the alloca is a def (store), then we know it isn't live-in.
791263509Sdim    for (BasicBlock::iterator I = BB->begin();; ++I) {
792193323Sed      if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
793263509Sdim        if (SI->getOperand(1) != AI)
794263509Sdim          continue;
795263509Sdim
796193323Sed        // We found a store to the alloca before a load.  The alloca is not
797193323Sed        // actually live-in here.
798193323Sed        LiveInBlockWorklist[i] = LiveInBlockWorklist.back();
799193323Sed        LiveInBlockWorklist.pop_back();
800193323Sed        --i, --e;
801193323Sed        break;
802198090Srdivacky      }
803263509Sdim
804198090Srdivacky      if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
805263509Sdim        if (LI->getOperand(0) != AI)
806263509Sdim          continue;
807263509Sdim
808193323Sed        // Okay, we found a load before a store to the alloca.  It is actually
809193323Sed        // live into this block.
810193323Sed        break;
811193323Sed      }
812193323Sed    }
813193323Sed  }
814263509Sdim
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();
819263509Sdim
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.
822193323Sed    if (!LiveInBlocks.insert(BB))
823193323Sed      continue;
824263509Sdim
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.
828193323Sed    for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
829193323Sed      BasicBlock *P = *PI;
830263509Sdim
831193323Sed      // The value is not live into a predecessor if it defines the value.
832193323Sed      if (DefBlocks.count(P))
833193323Sed        continue;
834263509Sdim
835193323Sed      // Otherwise it is, add to the worklist.
836193323Sed      LiveInBlockWorklist.push_back(P);
837193323Sed    }
838193323Sed  }
839193323Sed}
840193323Sed
841263509Sdim/// At this point, we're committed to promoting the alloca using IDF's, and the
842263509Sdim/// standard SSA construction algorithm.  Determine which blocks need phi nodes
843263509Sdim/// and see if we can optimize out some work by avoiding insertion of dead phi
844263509Sdim/// nodes.
845193323Sedvoid PromoteMem2Reg::DetermineInsertionPoint(AllocaInst *AI, unsigned AllocaNum,
846193323Sed                                             AllocaInfo &Info) {
847193323Sed  // Unique the set of defining blocks for efficient lookup.
848263509Sdim  SmallPtrSet<BasicBlock *, 32> DefBlocks;
849193323Sed  DefBlocks.insert(Info.DefiningBlocks.begin(), Info.DefiningBlocks.end());
850193323Sed
851193323Sed  // Determine which blocks the value is live in.  These are blocks which lead
852193323Sed  // to uses.
853263509Sdim  SmallPtrSet<BasicBlock *, 32> LiveInBlocks;
854193323Sed  ComputeLiveInBlocks(AI, Info, DefBlocks, LiveInBlocks);
855193323Sed
856218893Sdim  // Use a priority queue keyed on dominator tree level so that inserted nodes
857218893Sdim  // are handled from the bottom of the dominator tree upwards.
858263509Sdim  typedef std::pair<DomTreeNode *, unsigned> DomTreeNodePair;
859218893Sdim  typedef std::priority_queue<DomTreeNodePair, SmallVector<DomTreeNodePair, 32>,
860263509Sdim                              less_second> IDFPriorityQueue;
861218893Sdim  IDFPriorityQueue PQ;
862218893Sdim
863263509Sdim  for (SmallPtrSet<BasicBlock *, 32>::const_iterator I = DefBlocks.begin(),
864263509Sdim                                                     E = DefBlocks.end();
865263509Sdim       I != E; ++I) {
866218893Sdim    if (DomTreeNode *Node = DT.getNode(*I))
867218893Sdim      PQ.push(std::make_pair(Node, DomLevels[Node]));
868218893Sdim  }
869218893Sdim
870263509Sdim  SmallVector<std::pair<unsigned, BasicBlock *>, 32> DFBlocks;
871263509Sdim  SmallPtrSet<DomTreeNode *, 32> Visited;
872263509Sdim  SmallVector<DomTreeNode *, 32> Worklist;
873218893Sdim  while (!PQ.empty()) {
874218893Sdim    DomTreeNodePair RootPair = PQ.top();
875218893Sdim    PQ.pop();
876218893Sdim    DomTreeNode *Root = RootPair.first;
877218893Sdim    unsigned RootLevel = RootPair.second;
878218893Sdim
879218893Sdim    // Walk all dominator tree children of Root, inspecting their CFG edges with
880218893Sdim    // targets elsewhere on the dominator tree. Only targets whose level is at
881218893Sdim    // most Root's level are added to the iterated dominance frontier of the
882218893Sdim    // definition set.
883218893Sdim
884218893Sdim    Worklist.clear();
885218893Sdim    Worklist.push_back(Root);
886218893Sdim
887218893Sdim    while (!Worklist.empty()) {
888218893Sdim      DomTreeNode *Node = Worklist.pop_back_val();
889218893Sdim      BasicBlock *BB = Node->getBlock();
890218893Sdim
891218893Sdim      for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE;
892218893Sdim           ++SI) {
893218893Sdim        DomTreeNode *SuccNode = DT.getNode(*SI);
894218893Sdim
895218893Sdim        // Quickly skip all CFG edges that are also dominator tree edges instead
896218893Sdim        // of catching them below.
897218893Sdim        if (SuccNode->getIDom() == Node)
898218893Sdim          continue;
899218893Sdim
900218893Sdim        unsigned SuccLevel = DomLevels[SuccNode];
901218893Sdim        if (SuccLevel > RootLevel)
902218893Sdim          continue;
903218893Sdim
904218893Sdim        if (!Visited.insert(SuccNode))
905218893Sdim          continue;
906218893Sdim
907218893Sdim        BasicBlock *SuccBB = SuccNode->getBlock();
908218893Sdim        if (!LiveInBlocks.count(SuccBB))
909218893Sdim          continue;
910218893Sdim
911218893Sdim        DFBlocks.push_back(std::make_pair(BBNumbers[SuccBB], SuccBB));
912218893Sdim        if (!DefBlocks.count(SuccBB))
913218893Sdim          PQ.push(std::make_pair(SuccNode, SuccLevel));
914218893Sdim      }
915218893Sdim
916218893Sdim      for (DomTreeNode::iterator CI = Node->begin(), CE = Node->end(); CI != CE;
917218893Sdim           ++CI) {
918218893Sdim        if (!Visited.count(*CI))
919218893Sdim          Worklist.push_back(*CI);
920218893Sdim      }
921193323Sed    }
922193323Sed  }
923218893Sdim
924218893Sdim  if (DFBlocks.size() > 1)
925218893Sdim    std::sort(DFBlocks.begin(), DFBlocks.end());
926218893Sdim
927218893Sdim  unsigned CurrentVersion = 0;
928218893Sdim  for (unsigned i = 0, e = DFBlocks.size(); i != e; ++i)
929218893Sdim    QueuePhiNode(DFBlocks[i].second, AllocaNum, CurrentVersion);
930193323Sed}
931193323Sed
932263509Sdim/// \brief Queue a phi-node to be added to a basic-block for a specific Alloca.
933193323Sed///
934263509Sdim/// Returns true if there wasn't already a phi-node for that variable
935193323Sedbool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo,
936218893Sdim                                  unsigned &Version) {
937193323Sed  // Look up the basic-block in question.
938245431Sdim  PHINode *&PN = NewPhiNodes[std::make_pair(BBNumbers[BB], AllocaNo)];
939193323Sed
940193323Sed  // If the BB already has a phi node added for the i'th alloca then we're done!
941263509Sdim  if (PN)
942263509Sdim    return false;
943193323Sed
944193323Sed  // Create a PhiNode using the dereferenced type... and add the phi-node to the
945193323Sed  // BasicBlock.
946221345Sdim  PN = PHINode::Create(Allocas[AllocaNo]->getAllocatedType(), getNumPreds(BB),
947263509Sdim                       Allocas[AllocaNo]->getName() + "." + Twine(Version++),
948198090Srdivacky                       BB->begin());
949193323Sed  ++NumPHIInsert;
950193323Sed  PhiToAllocaMap[PN] = AllocaNo;
951193323Sed
952204642Srdivacky  if (AST && PN->getType()->isPointerTy())
953193323Sed    AST->copyValue(PointerAllocaValues[AllocaNo], PN);
954193323Sed
955193323Sed  return true;
956193323Sed}
957193323Sed
958263509Sdim/// \brief Recursively traverse the CFG of the function, renaming loads and
959263509Sdim/// stores to the allocas which we are promoting.
960263509Sdim///
961263509Sdim/// IncomingVals indicates what value each Alloca contains on exit from the
962263509Sdim/// predecessor block Pred.
963193323Sedvoid PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
964193323Sed                                RenamePassData::ValVector &IncomingVals,
965193323Sed                                std::vector<RenamePassData> &Worklist) {
966193323SedNextIteration:
967193323Sed  // If we are inserting any phi nodes into this BB, they will already be in the
968193323Sed  // block.
969193323Sed  if (PHINode *APN = dyn_cast<PHINode>(BB->begin())) {
970193323Sed    // If we have PHI nodes to update, compute the number of edges from Pred to
971193323Sed    // BB.
972193323Sed    if (PhiToAllocaMap.count(APN)) {
973193323Sed      // We want to be able to distinguish between PHI nodes being inserted by
974193323Sed      // this invocation of mem2reg from those phi nodes that already existed in
975193323Sed      // the IR before mem2reg was run.  We determine that APN is being inserted
976193323Sed      // because it is missing incoming edges.  All other PHI nodes being
977193323Sed      // inserted by this pass of mem2reg will have the same number of incoming
978193323Sed      // operands so far.  Remember this count.
979193323Sed      unsigned NewPHINumOperands = APN->getNumOperands();
980263509Sdim
981263509Sdim      unsigned NumEdges = std::count(succ_begin(Pred), succ_end(Pred), BB);
982193323Sed      assert(NumEdges && "Must be at least one edge from Pred to BB!");
983263509Sdim
984193323Sed      // Add entries for all the phis.
985193323Sed      BasicBlock::iterator PNI = BB->begin();
986193323Sed      do {
987193323Sed        unsigned AllocaNo = PhiToAllocaMap[APN];
988263509Sdim
989193323Sed        // Add N incoming values to the PHI node.
990193323Sed        for (unsigned i = 0; i != NumEdges; ++i)
991193323Sed          APN->addIncoming(IncomingVals[AllocaNo], Pred);
992263509Sdim
993193323Sed        // The currently active variable for this block is now the PHI.
994193323Sed        IncomingVals[AllocaNo] = APN;
995263509Sdim
996193323Sed        // Get the next phi node.
997193323Sed        ++PNI;
998193323Sed        APN = dyn_cast<PHINode>(PNI);
999263509Sdim        if (APN == 0)
1000263509Sdim          break;
1001263509Sdim
1002193323Sed        // Verify that it is missing entries.  If not, it is not being inserted
1003193323Sed        // by this mem2reg invocation so we want to ignore it.
1004193323Sed      } while (APN->getNumOperands() == NewPHINumOperands);
1005193323Sed    }
1006193323Sed  }
1007263509Sdim
1008193323Sed  // Don't revisit blocks.
1009263509Sdim  if (!Visited.insert(BB))
1010263509Sdim    return;
1011193323Sed
1012263509Sdim  for (BasicBlock::iterator II = BB->begin(); !isa<TerminatorInst>(II);) {
1013193323Sed    Instruction *I = II++; // get the instruction, increment iterator
1014193323Sed
1015193323Sed    if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1016193323Sed      AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand());
1017263509Sdim      if (!Src)
1018263509Sdim        continue;
1019193323Sed
1020263509Sdim      DenseMap<AllocaInst *, unsigned>::iterator AI = AllocaLookup.find(Src);
1021263509Sdim      if (AI == AllocaLookup.end())
1022263509Sdim        continue;
1023263509Sdim
1024193323Sed      Value *V = IncomingVals[AI->second];
1025193323Sed
1026193323Sed      // Anything using the load now uses the current value.
1027193323Sed      LI->replaceAllUsesWith(V);
1028204642Srdivacky      if (AST && LI->getType()->isPointerTy())
1029193323Sed        AST->deleteValue(LI);
1030193323Sed      BB->getInstList().erase(LI);
1031193323Sed    } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1032193323Sed      // Delete this instruction and mark the name as the current holder of the
1033193323Sed      // value
1034193323Sed      AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand());
1035263509Sdim      if (!Dest)
1036263509Sdim        continue;
1037263509Sdim
1038218893Sdim      DenseMap<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest);
1039193323Sed      if (ai == AllocaLookup.end())
1040193323Sed        continue;
1041263509Sdim
1042193323Sed      // what value were we writing?
1043193323Sed      IncomingVals[ai->second] = SI->getOperand(0);
1044202878Srdivacky      // Record debuginfo for the store before removing it.
1045263509Sdim      if (DbgDeclareInst *DDI = AllocaDbgDeclares[ai->second])
1046263509Sdim        ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1047193323Sed      BB->getInstList().erase(SI);
1048193323Sed    }
1049193323Sed  }
1050193323Sed
1051193323Sed  // 'Recurse' to our successors.
1052193323Sed  succ_iterator I = succ_begin(BB), E = succ_end(BB);
1053263509Sdim  if (I == E)
1054263509Sdim    return;
1055193323Sed
1056193323Sed  // Keep track of the successors so we don't visit the same successor twice
1057263509Sdim  SmallPtrSet<BasicBlock *, 8> VisitedSuccs;
1058193323Sed
1059193323Sed  // Handle the first successor without using the worklist.
1060193323Sed  VisitedSuccs.insert(*I);
1061193323Sed  Pred = BB;
1062193323Sed  BB = *I;
1063193323Sed  ++I;
1064193323Sed
1065193323Sed  for (; I != E; ++I)
1066193323Sed    if (VisitedSuccs.insert(*I))
1067193323Sed      Worklist.push_back(RenamePassData(*I, Pred, IncomingVals));
1068193323Sed
1069193323Sed  goto NextIteration;
1070193323Sed}
1071193323Sed
1072263509Sdimvoid llvm::PromoteMemToReg(ArrayRef<AllocaInst *> Allocas, DominatorTree &DT,
1073263509Sdim                           AliasSetTracker *AST) {
1074193323Sed  // If there is nothing to do, bail out...
1075263509Sdim  if (Allocas.empty())
1076263509Sdim    return;
1077193323Sed
1078218893Sdim  PromoteMem2Reg(Allocas, DT, AST).run();
1079193323Sed}
1080