blob: 523d548540d651d46980b12cd4ab604ee146d365 [file] [log] [blame]
Chris Lattnerafa060e2003-10-05 04:26:39 +00001//===- PromoteMemoryToRegister.cpp - Convert allocas to registers ---------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerd3db0222002-02-12 17:16:22 +00009//
Gordon Henriksenc86b6772007-11-04 16:15:04 +000010// This file promotes memory references to be register references. It promotes
Chris Lattnera744b772004-09-19 18:51:51 +000011// alloca instructions which only have loads and stores as uses. An alloca is
12// transformed by using dominator frontiers to place PHI nodes, then traversing
13// the function in depth-first order to rewrite loads and stores as appropriate.
14// This is just the standard SSA construction algorithm to construct "pruned"
15// SSA form.
Chris Lattnerd3db0222002-02-12 17:16:22 +000016//
17//===----------------------------------------------------------------------===//
18
Chris Lattnerbbe10402007-08-04 01:41:18 +000019#define DEBUG_TYPE "mem2reg"
Chris Lattnerd99bf492003-02-22 23:57:48 +000020#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Chris Lattnerb20724d2004-10-16 18:10:06 +000021#include "llvm/Constants.h"
Chris Lattner62e29b52004-09-15 01:02:54 +000022#include "llvm/DerivedTypes.h"
23#include "llvm/Function.h"
24#include "llvm/Instructions.h"
25#include "llvm/Analysis/Dominators.h"
26#include "llvm/Analysis/AliasSetTracker.h"
Chris Lattnerd3874042007-02-05 23:37:20 +000027#include "llvm/ADT/DenseMap.h"
Chris Lattnerc8376152007-02-05 22:13:11 +000028#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner40b65552007-02-05 21:58:48 +000029#include "llvm/ADT/SmallVector.h"
Chris Lattnerbbe10402007-08-04 01:41:18 +000030#include "llvm/ADT/Statistic.h"
Chris Lattner62e29b52004-09-15 01:02:54 +000031#include "llvm/ADT/StringExtras.h"
Chris Lattner393689a2003-04-18 19:25:22 +000032#include "llvm/Support/CFG.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000033#include "llvm/Support/Compiler.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000034#include <algorithm>
Chris Lattnerf7703df2004-01-09 06:12:26 +000035using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000036
Chris Lattnerbbe10402007-08-04 01:41:18 +000037STATISTIC(NumLocalPromoted, "Number of alloca's promoted within one block");
38STATISTIC(NumSingleStore, "Number of alloca's promoted with a single store");
39STATISTIC(NumDeadAlloca, "Number of dead alloca's removed");
Chris Lattnerf12f8de2007-08-04 22:50:14 +000040STATISTIC(NumPHIInsert, "Number of PHI nodes inserted");
Chris Lattnerbbe10402007-08-04 01:41:18 +000041
Chris Lattner76c1b972007-09-17 18:34:04 +000042// Provide DenseMapInfo for all pointers.
Chris Lattnerdfb22c32007-02-07 01:15:04 +000043namespace llvm {
44template<>
Chris Lattner76c1b972007-09-17 18:34:04 +000045struct DenseMapInfo<std::pair<BasicBlock*, unsigned> > {
46 typedef std::pair<BasicBlock*, unsigned> EltTy;
47 static inline EltTy getEmptyKey() {
48 return EltTy(reinterpret_cast<BasicBlock*>(-1), ~0U);
Chris Lattnerdfb22c32007-02-07 01:15:04 +000049 }
Chris Lattner76c1b972007-09-17 18:34:04 +000050 static inline EltTy getTombstoneKey() {
51 return EltTy(reinterpret_cast<BasicBlock*>(-2), 0U);
Chris Lattnerdfb22c32007-02-07 01:15:04 +000052 }
53 static unsigned getHashValue(const std::pair<BasicBlock*, unsigned> &Val) {
Chris Lattner76c1b972007-09-17 18:34:04 +000054 return DenseMapInfo<void*>::getHashValue(Val.first) + Val.second*2;
55 }
56 static bool isEqual(const EltTy &LHS, const EltTy &RHS) {
57 return LHS == RHS;
Chris Lattnerdfb22c32007-02-07 01:15:04 +000058 }
59 static bool isPod() { return true; }
60};
61}
62
Chris Lattnerd99bf492003-02-22 23:57:48 +000063/// isAllocaPromotable - Return true if this alloca is legal for promotion.
Chris Lattnera744b772004-09-19 18:51:51 +000064/// This is true if there are only loads and stores to the alloca.
Chris Lattnerd99bf492003-02-22 23:57:48 +000065///
Devang Patel41968df2007-04-25 17:15:20 +000066bool llvm::isAllocaPromotable(const AllocaInst *AI) {
Chris Lattnerfb743a92003-03-03 17:25:18 +000067 // FIXME: If the memory unit is of pointer or integer type, we can permit
68 // assignments to subsections of the memory unit.
69
Anton Korobeynikov9f528e62007-08-26 21:43:30 +000070 // Only allow direct and non-volatile loads and stores...
Chris Lattnerb9ddce62002-04-28 19:12:38 +000071 for (Value::use_const_iterator UI = AI->use_begin(), UE = AI->use_end();
Chris Lattnercc63f1c2002-08-22 23:37:20 +000072 UI != UE; ++UI) // Loop over all of the uses of the alloca
Anton Korobeynikov9f528e62007-08-26 21:43:30 +000073 if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
74 if (LI->isVolatile())
75 return false;
Chris Lattner2d11f162004-01-12 01:18:32 +000076 } else if (const StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
77 if (SI->getOperand(0) == AI)
78 return false; // Don't allow a store OF the AI, only INTO the AI.
Anton Korobeynikov9f528e62007-08-26 21:43:30 +000079 if (SI->isVolatile())
80 return false;
Chris Lattner2d11f162004-01-12 01:18:32 +000081 } else {
Chris Lattnera744b772004-09-19 18:51:51 +000082 return false; // Not a load or store.
Chris Lattner2d11f162004-01-12 01:18:32 +000083 }
Misha Brukmanfd939082005-04-21 23:48:37 +000084
Chris Lattnerb9ddce62002-04-28 19:12:38 +000085 return true;
Chris Lattner0adb9f92002-04-28 18:54:01 +000086}
Chris Lattner9f4eb012002-04-28 18:27:55 +000087
Chris Lattnerd99bf492003-02-22 23:57:48 +000088namespace {
Chris Lattner5dd75b42007-08-04 01:47:41 +000089 struct AllocaInfo;
Devang Patela5b7dc52007-03-09 23:39:14 +000090
91 // Data package used by RenamePass()
92 class VISIBILITY_HIDDEN RenamePassData {
93 public:
Chris Lattner483ce142007-08-04 01:19:38 +000094 typedef std::vector<Value *> ValVector;
95
Chris Lattner63cdcaa2007-08-04 01:07:49 +000096 RenamePassData() {}
Devang Patela5b7dc52007-03-09 23:39:14 +000097 RenamePassData(BasicBlock *B, BasicBlock *P,
Chris Lattner483ce142007-08-04 01:19:38 +000098 const ValVector &V) : BB(B), Pred(P), Values(V) {}
Devang Patela5b7dc52007-03-09 23:39:14 +000099 BasicBlock *BB;
100 BasicBlock *Pred;
Chris Lattner483ce142007-08-04 01:19:38 +0000101 ValVector Values;
Chris Lattner63cdcaa2007-08-04 01:07:49 +0000102
103 void swap(RenamePassData &RHS) {
104 std::swap(BB, RHS.BB);
105 std::swap(Pred, RHS.Pred);
106 Values.swap(RHS.Values);
107 }
Devang Patela5b7dc52007-03-09 23:39:14 +0000108 };
109
Chris Lattner95255282006-06-28 23:17:24 +0000110 struct VISIBILITY_HIDDEN PromoteMem2Reg {
Chris Lattner62e29b52004-09-15 01:02:54 +0000111 /// Allocas - The alloca instructions being promoted.
112 ///
Chris Lattner24011be2003-10-05 20:54:03 +0000113 std::vector<AllocaInst*> Allocas;
Chris Lattner40b65552007-02-05 21:58:48 +0000114 SmallVector<AllocaInst*, 16> &RetryList;
Devang Patel326821e2007-06-07 21:57:03 +0000115 DominatorTree &DT;
Chris Lattnerd99bf492003-02-22 23:57:48 +0000116 DominanceFrontier &DF;
117
Chris Lattner62e29b52004-09-15 01:02:54 +0000118 /// AST - An AliasSetTracker object to update. If null, don't update it.
119 ///
120 AliasSetTracker *AST;
121
122 /// AllocaLookup - Reverse mapping of Allocas.
123 ///
Chris Lattner9e38fbf2003-10-05 03:16:07 +0000124 std::map<AllocaInst*, unsigned> AllocaLookup;
125
Chris Lattner62e29b52004-09-15 01:02:54 +0000126 /// NewPhiNodes - The PhiNodes we're adding.
127 ///
Chris Lattnerdfb22c32007-02-07 01:15:04 +0000128 DenseMap<std::pair<BasicBlock*, unsigned>, PHINode*> NewPhiNodes;
129
130 /// PhiToAllocaMap - For each PHI node, keep track of which entry in Allocas
131 /// it corresponds to.
132 DenseMap<PHINode*, unsigned> PhiToAllocaMap;
133
Chris Lattner62e29b52004-09-15 01:02:54 +0000134 /// PointerAllocaValues - If we are updating an AliasSetTracker, then for
135 /// each alloca that is of pointer type, we keep track of what to copyValue
136 /// to the inserted PHI nodes here.
137 ///
138 std::vector<Value*> PointerAllocaValues;
139
140 /// Visited - The set of basic blocks the renamer has already visited.
141 ///
Chris Lattnerc670f3d2007-02-05 22:15:21 +0000142 SmallPtrSet<BasicBlock*, 16> Visited;
Chris Lattnerd99bf492003-02-22 23:57:48 +0000143
Chris Lattner62e29b52004-09-15 01:02:54 +0000144 /// BBNumbers - Contains a stable numbering of basic blocks to avoid
145 /// non-determinstic behavior.
Chris Lattnerd3874042007-02-05 23:37:20 +0000146 DenseMap<BasicBlock*, unsigned> BBNumbers;
Chris Lattner63168d22004-06-19 07:40:14 +0000147
Chris Lattnere7b653d2007-08-04 20:24:50 +0000148 /// BBNumPreds - Lazily compute the number of predecessors a block has.
149 DenseMap<const BasicBlock*, unsigned> BBNumPreds;
Chris Lattnerd99bf492003-02-22 23:57:48 +0000150 public:
Chris Lattner6cfd1eb2005-06-30 07:29:44 +0000151 PromoteMem2Reg(const std::vector<AllocaInst*> &A,
Devang Patel326821e2007-06-07 21:57:03 +0000152 SmallVector<AllocaInst*, 16> &Retry, DominatorTree &dt,
Devang Patel68c01b32007-04-25 18:32:35 +0000153 DominanceFrontier &df, AliasSetTracker *ast)
Devang Patel326821e2007-06-07 21:57:03 +0000154 : Allocas(A), RetryList(Retry), DT(dt), DF(df), AST(ast) {}
Chris Lattnerd99bf492003-02-22 23:57:48 +0000155
156 void run();
157
Chris Lattnerfed40df2005-11-18 07:29:44 +0000158 /// properlyDominates - Return true if I1 properly dominates I2.
Chris Lattner7e40f632004-10-17 21:25:56 +0000159 ///
Chris Lattnerfed40df2005-11-18 07:29:44 +0000160 bool properlyDominates(Instruction *I1, Instruction *I2) const {
Chris Lattner28e792c2004-10-18 01:21:17 +0000161 if (InvokeInst *II = dyn_cast<InvokeInst>(I1))
162 I1 = II->getNormalDest()->begin();
Devang Patel326821e2007-06-07 21:57:03 +0000163 return DT.properlyDominates(I1->getParent(), I2->getParent());
Chris Lattnerfed40df2005-11-18 07:29:44 +0000164 }
165
Devang Patel326821e2007-06-07 21:57:03 +0000166 /// dominates - Return true if BB1 dominates BB2 using the DominatorTree.
Chris Lattnerfed40df2005-11-18 07:29:44 +0000167 ///
168 bool dominates(BasicBlock *BB1, BasicBlock *BB2) const {
Devang Patel326821e2007-06-07 21:57:03 +0000169 return DT.dominates(BB1, BB2);
Chris Lattner7e40f632004-10-17 21:25:56 +0000170 }
171
Chris Lattnerd99bf492003-02-22 23:57:48 +0000172 private:
Chris Lattnerbbe10402007-08-04 01:41:18 +0000173 void RemoveFromAllocasList(unsigned &AllocaIdx) {
174 Allocas[AllocaIdx] = Allocas.back();
175 Allocas.pop_back();
176 --AllocaIdx;
177 }
Chris Lattnere7b653d2007-08-04 20:24:50 +0000178
179 unsigned getNumPreds(const BasicBlock *BB) {
180 unsigned &NP = BBNumPreds[BB];
181 if (NP == 0)
182 NP = std::distance(pred_begin(BB), pred_end(BB))+1;
183 return NP-1;
184 }
185
Chris Lattner0ec8df32007-08-04 21:14:29 +0000186 void DetermineInsertionPoint(AllocaInst *AI, unsigned AllocaNum,
187 AllocaInfo &Info);
Chris Lattnerf12f8de2007-08-04 22:50:14 +0000188 void ComputeLiveInBlocks(AllocaInst *AI, AllocaInfo &Info,
189 const SmallPtrSet<BasicBlock*, 32> &DefBlocks,
190 SmallPtrSet<BasicBlock*, 32> &LiveInBlocks);
Chris Lattnerbbe10402007-08-04 01:41:18 +0000191
Chris Lattner5dd75b42007-08-04 01:47:41 +0000192 void RewriteSingleStoreAlloca(AllocaInst *AI, AllocaInfo &Info);
193
Chris Lattner6cfd1eb2005-06-30 07:29:44 +0000194 bool PromoteLocallyUsedAlloca(BasicBlock *BB, AllocaInst *AI);
Misha Brukmanfd939082005-04-21 23:48:37 +0000195 void PromoteLocallyUsedAllocas(BasicBlock *BB,
Chris Lattnere47f78e2004-02-03 22:34:12 +0000196 const std::vector<AllocaInst*> &AIs);
Chris Lattner24011be2003-10-05 20:54:03 +0000197
Chris Lattnerd99bf492003-02-22 23:57:48 +0000198 void RenamePass(BasicBlock *BB, BasicBlock *Pred,
Chris Lattner483ce142007-08-04 01:19:38 +0000199 RenamePassData::ValVector &IncVals,
Chris Lattnerac4aa4b2007-08-04 01:04:40 +0000200 std::vector<RenamePassData> &Worklist);
Chris Lattner69091be2003-10-05 22:19:20 +0000201 bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx, unsigned &Version,
Chris Lattner6a1a28d2007-02-05 23:11:37 +0000202 SmallPtrSet<PHINode*, 16> &InsertedPHINodes);
Chris Lattnerd99bf492003-02-22 23:57:48 +0000203 };
Chris Lattnerbbe10402007-08-04 01:41:18 +0000204
205 struct AllocaInfo {
206 std::vector<BasicBlock*> DefiningBlocks;
207 std::vector<BasicBlock*> UsingBlocks;
208
209 StoreInst *OnlyStore;
210 BasicBlock *OnlyBlock;
211 bool OnlyUsedInOneBlock;
212
213 Value *AllocaPointerVal;
214
215 void clear() {
216 DefiningBlocks.clear();
217 UsingBlocks.clear();
218 OnlyStore = 0;
219 OnlyBlock = 0;
220 OnlyUsedInOneBlock = true;
221 AllocaPointerVal = 0;
222 }
223
224 /// AnalyzeAlloca - Scan the uses of the specified alloca, filling in our
225 /// ivars.
226 void AnalyzeAlloca(AllocaInst *AI) {
227 clear();
228
229 // As we scan the uses of the alloca instruction, keep track of stores,
230 // and decide whether all of the loads and stores to the alloca are within
231 // the same basic block.
232 for (Value::use_iterator U = AI->use_begin(), E = AI->use_end();
Chris Lattnere7b653d2007-08-04 20:24:50 +0000233 U != E; ++U) {
Chris Lattnerbbe10402007-08-04 01:41:18 +0000234 Instruction *User = cast<Instruction>(*U);
235 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
236 // Remember the basic blocks which define new values for the alloca
237 DefiningBlocks.push_back(SI->getParent());
238 AllocaPointerVal = SI->getOperand(0);
239 OnlyStore = SI;
240 } else {
241 LoadInst *LI = cast<LoadInst>(User);
Chris Lattnere7b653d2007-08-04 20:24:50 +0000242 // Otherwise it must be a load instruction, keep track of variable
243 // reads.
Chris Lattnerbbe10402007-08-04 01:41:18 +0000244 UsingBlocks.push_back(LI->getParent());
245 AllocaPointerVal = LI;
246 }
247
248 if (OnlyUsedInOneBlock) {
249 if (OnlyBlock == 0)
250 OnlyBlock = User->getParent();
251 else if (OnlyBlock != User->getParent())
252 OnlyUsedInOneBlock = false;
253 }
254 }
255 }
256 };
Devang Patela5b7dc52007-03-09 23:39:14 +0000257
Chris Lattnerd99bf492003-02-22 23:57:48 +0000258} // end of anonymous namespace
Chris Lattnerd3db0222002-02-12 17:16:22 +0000259
Chris Lattner5dd75b42007-08-04 01:47:41 +0000260
Chris Lattnerd99bf492003-02-22 23:57:48 +0000261void PromoteMem2Reg::run() {
Chris Lattnerd99bf492003-02-22 23:57:48 +0000262 Function &F = *DF.getRoot()->getParent();
Chris Lattner0fa15712003-10-05 01:52:53 +0000263
Chris Lattnere47f78e2004-02-03 22:34:12 +0000264 // LocallyUsedAllocas - Keep track of all of the alloca instructions which are
265 // only used in a single basic block. These instructions can be efficiently
266 // promoted by performing a single linear scan over that one block. Since
267 // individual basic blocks are sometimes large, we group together all allocas
268 // that are live in a single basic block by the basic block they are live in.
269 std::map<BasicBlock*, std::vector<AllocaInst*> > LocallyUsedAllocas;
270
Chris Lattner62e29b52004-09-15 01:02:54 +0000271 if (AST) PointerAllocaValues.resize(Allocas.size());
Chris Lattner63168d22004-06-19 07:40:14 +0000272
Chris Lattnerbbe10402007-08-04 01:41:18 +0000273 AllocaInfo Info;
274
Chris Lattner69091be2003-10-05 22:19:20 +0000275 for (unsigned AllocaNum = 0; AllocaNum != Allocas.size(); ++AllocaNum) {
276 AllocaInst *AI = Allocas[AllocaNum];
Chris Lattner9e38fbf2003-10-05 03:16:07 +0000277
Devang Patel41968df2007-04-25 17:15:20 +0000278 assert(isAllocaPromotable(AI) &&
Chris Lattnerd99bf492003-02-22 23:57:48 +0000279 "Cannot promote non-promotable alloca!");
Chris Lattner69091be2003-10-05 22:19:20 +0000280 assert(AI->getParent()->getParent() == &F &&
Chris Lattnerd99bf492003-02-22 23:57:48 +0000281 "All allocas should be in the same function, which is same as DF!");
Chris Lattner9157f042003-10-05 02:37:36 +0000282
Chris Lattner24011be2003-10-05 20:54:03 +0000283 if (AI->use_empty()) {
284 // If there are no uses of the alloca, just delete it now.
Chris Lattner62e29b52004-09-15 01:02:54 +0000285 if (AST) AST->deleteValue(AI);
Chris Lattner634c76c2006-04-27 01:14:43 +0000286 AI->eraseFromParent();
Chris Lattner24011be2003-10-05 20:54:03 +0000287
288 // Remove the alloca from the Allocas list, since it has been processed
Chris Lattnerbbe10402007-08-04 01:41:18 +0000289 RemoveFromAllocasList(AllocaNum);
290 ++NumDeadAlloca;
Chris Lattner24011be2003-10-05 20:54:03 +0000291 continue;
292 }
Chris Lattnerbbe10402007-08-04 01:41:18 +0000293
Chris Lattner69091be2003-10-05 22:19:20 +0000294 // Calculate the set of read and write-locations for each alloca. This is
Chris Lattner2d11f162004-01-12 01:18:32 +0000295 // analogous to finding the 'uses' and 'definitions' of each variable.
Chris Lattnerbbe10402007-08-04 01:41:18 +0000296 Info.AnalyzeAlloca(AI);
Chris Lattner24011be2003-10-05 20:54:03 +0000297
Chris Lattner36ba5002005-11-18 07:31:42 +0000298 // If there is only a single store to this value, replace any loads of
299 // it that are directly dominated by the definition with the value stored.
Chris Lattnerbbe10402007-08-04 01:41:18 +0000300 if (Info.DefiningBlocks.size() == 1) {
Chris Lattner5dd75b42007-08-04 01:47:41 +0000301 RewriteSingleStoreAlloca(AI, Info);
Chris Lattner36ba5002005-11-18 07:31:42 +0000302
303 // Finally, after the scan, check to see if the store is all that is left.
Chris Lattnerbbe10402007-08-04 01:41:18 +0000304 if (Info.UsingBlocks.empty()) {
Chris Lattner4f63e762007-08-04 02:38:38 +0000305 // Remove the (now dead) store and alloca.
306 Info.OnlyStore->eraseFromParent();
307 if (AST) AST->deleteValue(AI);
308 AI->eraseFromParent();
309
Chris Lattner36ba5002005-11-18 07:31:42 +0000310 // The alloca has been processed, move on.
Chris Lattnerbbe10402007-08-04 01:41:18 +0000311 RemoveFromAllocasList(AllocaNum);
Chris Lattner4f63e762007-08-04 02:38:38 +0000312
313 ++NumSingleStore;
Chris Lattner36ba5002005-11-18 07:31:42 +0000314 continue;
315 }
316 }
317
Chris Lattnerfb312c72007-08-04 20:03:23 +0000318 // If the alloca is only read and written in one basic block, just perform a
319 // linear sweep over the block to eliminate it.
320 if (Info.OnlyUsedInOneBlock) {
321 LocallyUsedAllocas[Info.OnlyBlock].push_back(AI);
322
323 // Remove the alloca from the Allocas list, since it will be processed.
324 RemoveFromAllocasList(AllocaNum);
325 continue;
326 }
Chris Lattnerfed40df2005-11-18 07:29:44 +0000327
Chris Lattner63168d22004-06-19 07:40:14 +0000328 // If we haven't computed a numbering for the BB's in the function, do so
329 // now.
Chris Lattnerd3874042007-02-05 23:37:20 +0000330 if (BBNumbers.empty()) {
331 unsigned ID = 0;
332 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
333 BBNumbers[I] = ID++;
334 }
Chris Lattner63168d22004-06-19 07:40:14 +0000335
Chris Lattner0ec8df32007-08-04 21:14:29 +0000336 // If we have an AST to keep updated, remember some pointer value that is
337 // stored into the alloca.
338 if (AST)
339 PointerAllocaValues[AllocaNum] = Info.AllocaPointerVal;
340
341 // Keep the reverse mapping of the 'Allocas' array for the rename pass.
Chris Lattner69091be2003-10-05 22:19:20 +0000342 AllocaLookup[Allocas[AllocaNum]] = AllocaNum;
Chris Lattner0ec8df32007-08-04 21:14:29 +0000343
344 // At this point, we're committed to promoting the alloca using IDF's, and
345 // the standard SSA construction algorithm. Determine which blocks need phi
346 // nodes and see if we can optimize out some work by avoiding insertion of
347 // dead phi nodes.
348 DetermineInsertionPoint(AI, AllocaNum, Info);
Chris Lattner9f4eb012002-04-28 18:27:55 +0000349 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000350
Chris Lattnere47f78e2004-02-03 22:34:12 +0000351 // Process all allocas which are only used in a single basic block.
352 for (std::map<BasicBlock*, std::vector<AllocaInst*> >::iterator I =
353 LocallyUsedAllocas.begin(), E = LocallyUsedAllocas.end(); I != E; ++I){
Chris Lattner6cfd1eb2005-06-30 07:29:44 +0000354 const std::vector<AllocaInst*> &LocAllocas = I->second;
355 assert(!LocAllocas.empty() && "empty alloca list??");
Chris Lattnere47f78e2004-02-03 22:34:12 +0000356
357 // It's common for there to only be one alloca in the list. Handle it
358 // efficiently.
Chris Lattner6cfd1eb2005-06-30 07:29:44 +0000359 if (LocAllocas.size() == 1) {
360 // If we can do the quick promotion pass, do so now.
361 if (PromoteLocallyUsedAlloca(I->first, LocAllocas[0]))
362 RetryList.push_back(LocAllocas[0]); // Failed, retry later.
363 } else {
364 // Locally promote anything possible. Note that if this is unable to
365 // promote a particular alloca, it puts the alloca onto the Allocas vector
366 // for global processing.
367 PromoteLocallyUsedAllocas(I->first, LocAllocas);
368 }
Chris Lattnere47f78e2004-02-03 22:34:12 +0000369 }
370
Chris Lattner24011be2003-10-05 20:54:03 +0000371 if (Allocas.empty())
372 return; // All of the allocas must have been trivial!
Cameron Buschardt98a37c22002-03-27 23:17:37 +0000373
Chris Lattner5b5df172002-04-28 18:39:46 +0000374 // Set the incoming values for the basic block to be null values for all of
375 // the alloca's. We do this in case there is a load of a value that has not
376 // been stored yet. In this case, it will get this null value.
377 //
Chris Lattner483ce142007-08-04 01:19:38 +0000378 RenamePassData::ValVector Values(Allocas.size());
Chris Lattner5b5df172002-04-28 18:39:46 +0000379 for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
Chris Lattnerb20724d2004-10-16 18:10:06 +0000380 Values[i] = UndefValue::get(Allocas[i]->getAllocatedType());
Chris Lattner5b5df172002-04-28 18:39:46 +0000381
Chris Lattner9f4eb012002-04-28 18:27:55 +0000382 // Walks all basic blocks in the function performing the SSA rename algorithm
383 // and inserting the phi nodes we marked as necessary
384 //
Chris Lattnerac4aa4b2007-08-04 01:04:40 +0000385 std::vector<RenamePassData> RenamePassWorkList;
Devang Pateld64d3a12007-03-26 23:19:29 +0000386 RenamePassWorkList.push_back(RenamePassData(F.begin(), 0, Values));
Chris Lattner483ce142007-08-04 01:19:38 +0000387 while (!RenamePassWorkList.empty()) {
Chris Lattner63cdcaa2007-08-04 01:07:49 +0000388 RenamePassData RPD;
389 RPD.swap(RenamePassWorkList.back());
Devang Pateld64d3a12007-03-26 23:19:29 +0000390 RenamePassWorkList.pop_back();
Devang Patela5b7dc52007-03-09 23:39:14 +0000391 // RenamePass may add new worklist entries.
Chris Lattnerac4aa4b2007-08-04 01:04:40 +0000392 RenamePass(RPD.BB, RPD.Pred, RPD.Values, RenamePassWorkList);
Devang Patela5b7dc52007-03-09 23:39:14 +0000393 }
394
Chris Lattnerafa060e2003-10-05 04:26:39 +0000395 // The renamer uses the Visited set to avoid infinite loops. Clear it now.
Chris Lattner0fa15712003-10-05 01:52:53 +0000396 Visited.clear();
Cameron Buschardt98a37c22002-03-27 23:17:37 +0000397
Chris Lattner634c76c2006-04-27 01:14:43 +0000398 // Remove the allocas themselves from the function.
Chris Lattner0fa15712003-10-05 01:52:53 +0000399 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
400 Instruction *A = Allocas[i];
Cameron Buschardt98a37c22002-03-27 23:17:37 +0000401
Chris Lattner0fa15712003-10-05 01:52:53 +0000402 // If there are any uses of the alloca instructions left, they must be in
Chris Lattnerd4bd3eb2003-04-10 19:41:13 +0000403 // sections of dead code that were not processed on the dominance frontier.
404 // Just delete the users now.
405 //
Chris Lattner0fa15712003-10-05 01:52:53 +0000406 if (!A->use_empty())
Chris Lattnerb20724d2004-10-16 18:10:06 +0000407 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattner62e29b52004-09-15 01:02:54 +0000408 if (AST) AST->deleteValue(A);
Chris Lattner634c76c2006-04-27 01:14:43 +0000409 A->eraseFromParent();
Chris Lattner9f4eb012002-04-28 18:27:55 +0000410 }
Chris Lattnerafa060e2003-10-05 04:26:39 +0000411
Chris Lattner634c76c2006-04-27 01:14:43 +0000412
413 // Loop over all of the PHI nodes and see if there are any that we can get
414 // rid of because they merge all of the same incoming values. This can
415 // happen due to undef values coming into the PHI nodes. This process is
416 // iterative, because eliminating one PHI node can cause others to be removed.
417 bool EliminatedAPHI = true;
418 while (EliminatedAPHI) {
419 EliminatedAPHI = false;
420
Chris Lattnerdfb22c32007-02-07 01:15:04 +0000421 for (DenseMap<std::pair<BasicBlock*, unsigned>, PHINode*>::iterator I =
422 NewPhiNodes.begin(), E = NewPhiNodes.end(); I != E;) {
423 PHINode *PN = I->second;
424
425 // If this PHI node merges one value and/or undefs, get the value.
426 if (Value *V = PN->hasConstantValue(true)) {
427 if (!isa<Instruction>(V) ||
428 properlyDominates(cast<Instruction>(V), PN)) {
429 if (AST && isa<PointerType>(PN->getType()))
430 AST->deleteValue(PN);
431 PN->replaceAllUsesWith(V);
432 PN->eraseFromParent();
433 NewPhiNodes.erase(I++);
434 EliminatedAPHI = true;
435 continue;
Chris Lattner634c76c2006-04-27 01:14:43 +0000436 }
437 }
Chris Lattnerdfb22c32007-02-07 01:15:04 +0000438 ++I;
Chris Lattner634c76c2006-04-27 01:14:43 +0000439 }
440 }
441
Chris Lattnerafa060e2003-10-05 04:26:39 +0000442 // At this point, the renamer has added entries to PHI nodes for all reachable
Chris Lattnerc8376152007-02-05 22:13:11 +0000443 // code. Unfortunately, there may be unreachable blocks which the renamer
444 // hasn't traversed. If this is the case, the PHI nodes may not
Chris Lattnerafa060e2003-10-05 04:26:39 +0000445 // have incoming values for all predecessors. Loop over all PHI nodes we have
Chris Lattner7e40f632004-10-17 21:25:56 +0000446 // created, inserting undef values if they are missing any incoming values.
Chris Lattnerafa060e2003-10-05 04:26:39 +0000447 //
Chris Lattnerdfb22c32007-02-07 01:15:04 +0000448 for (DenseMap<std::pair<BasicBlock*, unsigned>, PHINode*>::iterator I =
Chris Lattnerafa060e2003-10-05 04:26:39 +0000449 NewPhiNodes.begin(), E = NewPhiNodes.end(); I != E; ++I) {
Chris Lattnerdfb22c32007-02-07 01:15:04 +0000450 // We want to do this once per basic block. As such, only process a block
451 // when we find the PHI that is the first entry in the block.
452 PHINode *SomePHI = I->second;
453 BasicBlock *BB = SomePHI->getParent();
454 if (&BB->front() != SomePHI)
455 continue;
Chris Lattnerafa060e2003-10-05 04:26:39 +0000456
Chris Lattnerafa060e2003-10-05 04:26:39 +0000457 // Only do work here if there the PHI nodes are missing incoming values. We
458 // know that all PHI nodes that were inserted in a block will have the same
Chris Lattnerdfb22c32007-02-07 01:15:04 +0000459 // number of incoming values, so we can just check any of them.
Chris Lattner127ed3c2007-08-04 21:06:15 +0000460 if (SomePHI->getNumIncomingValues() == getNumPreds(BB))
Chris Lattnerdfb22c32007-02-07 01:15:04 +0000461 continue;
Chris Lattner127ed3c2007-08-04 21:06:15 +0000462
463 // Get the preds for BB.
464 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
Chris Lattnerdfb22c32007-02-07 01:15:04 +0000465
466 // Ok, now we know that all of the PHI nodes are missing entries for some
467 // basic blocks. Start by sorting the incoming predecessors for efficient
468 // access.
469 std::sort(Preds.begin(), Preds.end());
470
471 // Now we loop through all BB's which have entries in SomePHI and remove
472 // them from the Preds list.
473 for (unsigned i = 0, e = SomePHI->getNumIncomingValues(); i != e; ++i) {
474 // Do a log(n) search of the Preds list for the entry we want.
475 SmallVector<BasicBlock*, 16>::iterator EntIt =
476 std::lower_bound(Preds.begin(), Preds.end(),
477 SomePHI->getIncomingBlock(i));
478 assert(EntIt != Preds.end() && *EntIt == SomePHI->getIncomingBlock(i)&&
479 "PHI node has entry for a block which is not a predecessor!");
Chris Lattnerafa060e2003-10-05 04:26:39 +0000480
Chris Lattnerdfb22c32007-02-07 01:15:04 +0000481 // Remove the entry
482 Preds.erase(EntIt);
483 }
Chris Lattnerafa060e2003-10-05 04:26:39 +0000484
Chris Lattnerdfb22c32007-02-07 01:15:04 +0000485 // At this point, the blocks left in the preds list must have dummy
486 // entries inserted into every PHI nodes for the block. Update all the phi
487 // nodes in this block that we are inserting (there could be phis before
488 // mem2reg runs).
489 unsigned NumBadPreds = SomePHI->getNumIncomingValues();
490 BasicBlock::iterator BBI = BB->begin();
491 while ((SomePHI = dyn_cast<PHINode>(BBI++)) &&
492 SomePHI->getNumIncomingValues() == NumBadPreds) {
493 Value *UndefVal = UndefValue::get(SomePHI->getType());
494 for (unsigned pred = 0, e = Preds.size(); pred != e; ++pred)
495 SomePHI->addIncoming(UndefVal, Preds[pred]);
Chris Lattnerafa060e2003-10-05 04:26:39 +0000496 }
497 }
Chris Lattnerdfb22c32007-02-07 01:15:04 +0000498
499 NewPhiNodes.clear();
Cameron Buschardt98a37c22002-03-27 23:17:37 +0000500}
501
Chris Lattner5dd75b42007-08-04 01:47:41 +0000502
Chris Lattnerf12f8de2007-08-04 22:50:14 +0000503/// ComputeLiveInBlocks - Determine which blocks the value is live in. These
504/// are blocks which lead to uses. Knowing this allows us to avoid inserting
505/// PHI nodes into blocks which don't lead to uses (thus, the inserted phi nodes
506/// would be dead).
507void PromoteMem2Reg::
508ComputeLiveInBlocks(AllocaInst *AI, AllocaInfo &Info,
509 const SmallPtrSet<BasicBlock*, 32> &DefBlocks,
510 SmallPtrSet<BasicBlock*, 32> &LiveInBlocks) {
511
512 // To determine liveness, we must iterate through the predecessors of blocks
513 // where the def is live. Blocks are added to the worklist if we need to
514 // check their predecessors. Start with all the using blocks.
515 SmallVector<BasicBlock*, 64> LiveInBlockWorklist;
516 LiveInBlockWorklist.insert(LiveInBlockWorklist.end(),
517 Info.UsingBlocks.begin(), Info.UsingBlocks.end());
518
519 // If any of the using blocks is also a definition block, check to see if the
520 // definition occurs before or after the use. If it happens before the use,
521 // the value isn't really live-in.
522 for (unsigned i = 0, e = LiveInBlockWorklist.size(); i != e; ++i) {
523 BasicBlock *BB = LiveInBlockWorklist[i];
524 if (!DefBlocks.count(BB)) continue;
525
526 // Okay, this is a block that both uses and defines the value. If the first
527 // reference to the alloca is a def (store), then we know it isn't live-in.
528 for (BasicBlock::iterator I = BB->begin(); ; ++I) {
529 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
530 if (SI->getOperand(1) != AI) continue;
531
532 // We found a store to the alloca before a load. The alloca is not
533 // actually live-in here.
534 LiveInBlockWorklist[i] = LiveInBlockWorklist.back();
535 LiveInBlockWorklist.pop_back();
536 --i, --e;
537 break;
538 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
539 if (LI->getOperand(0) != AI) continue;
540
541 // Okay, we found a load before a store to the alloca. It is actually
542 // live into this block.
543 break;
544 }
545 }
546 }
547
548 // Now that we have a set of blocks where the phi is live-in, recursively add
549 // their predecessors until we find the full region the value is live.
550 while (!LiveInBlockWorklist.empty()) {
551 BasicBlock *BB = LiveInBlockWorklist.back();
552 LiveInBlockWorklist.pop_back();
553
554 // The block really is live in here, insert it into the set. If already in
555 // the set, then it has already been processed.
556 if (!LiveInBlocks.insert(BB))
557 continue;
558
559 // Since the value is live into BB, it is either defined in a predecessor or
560 // live into it to. Add the preds to the worklist unless they are a
561 // defining block.
562 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
563 BasicBlock *P = *PI;
564
565 // The value is not live into a predecessor if it defines the value.
566 if (DefBlocks.count(P))
567 continue;
568
569 // Otherwise it is, add to the worklist.
570 LiveInBlockWorklist.push_back(P);
571 }
572 }
573}
574
Chris Lattner0ec8df32007-08-04 21:14:29 +0000575/// DetermineInsertionPoint - At this point, we're committed to promoting the
576/// alloca using IDF's, and the standard SSA construction algorithm. Determine
577/// which blocks need phi nodes and see if we can optimize out some work by
578/// avoiding insertion of dead phi nodes.
579void PromoteMem2Reg::DetermineInsertionPoint(AllocaInst *AI, unsigned AllocaNum,
580 AllocaInfo &Info) {
Chris Lattnerf12f8de2007-08-04 22:50:14 +0000581
582 // Unique the set of defining blocks for efficient lookup.
583 SmallPtrSet<BasicBlock*, 32> DefBlocks;
584 DefBlocks.insert(Info.DefiningBlocks.begin(), Info.DefiningBlocks.end());
585
586 // Determine which blocks the value is live in. These are blocks which lead
587 // to uses.
588 SmallPtrSet<BasicBlock*, 32> LiveInBlocks;
589 ComputeLiveInBlocks(AI, Info, DefBlocks, LiveInBlocks);
590
Chris Lattner0ec8df32007-08-04 21:14:29 +0000591 // Compute the locations where PhiNodes need to be inserted. Look at the
592 // dominance frontier of EACH basic-block we have a write in.
593 unsigned CurrentVersion = 0;
594 SmallPtrSet<PHINode*, 16> InsertedPHINodes;
595 std::vector<std::pair<unsigned, BasicBlock*> > DFBlocks;
596 while (!Info.DefiningBlocks.empty()) {
597 BasicBlock *BB = Info.DefiningBlocks.back();
598 Info.DefiningBlocks.pop_back();
599
Chris Lattnerf12f8de2007-08-04 22:50:14 +0000600 // Look up the DF for this write, add it to defining blocks.
Chris Lattner0ec8df32007-08-04 21:14:29 +0000601 DominanceFrontier::const_iterator it = DF.find(BB);
Chris Lattnerf12f8de2007-08-04 22:50:14 +0000602 if (it == DF.end()) continue;
Chris Lattner0ec8df32007-08-04 21:14:29 +0000603
Chris Lattnerf12f8de2007-08-04 22:50:14 +0000604 const DominanceFrontier::DomSetType &S = it->second;
605
606 // In theory we don't need the indirection through the DFBlocks vector.
607 // In practice, the order of calling QueuePhiNode would depend on the
608 // (unspecified) ordering of basic blocks in the dominance frontier,
609 // which would give PHI nodes non-determinstic subscripts. Fix this by
610 // processing blocks in order of the occurance in the function.
611 for (DominanceFrontier::DomSetType::const_iterator P = S.begin(),
612 PE = S.end(); P != PE; ++P) {
613 // If the frontier block is not in the live-in set for the alloca, don't
614 // bother processing it.
615 if (!LiveInBlocks.count(*P))
616 continue;
617
618 DFBlocks.push_back(std::make_pair(BBNumbers[*P], *P));
619 }
620
621 // Sort by which the block ordering in the function.
622 if (DFBlocks.size() > 1)
623 std::sort(DFBlocks.begin(), DFBlocks.end());
624
625 for (unsigned i = 0, e = DFBlocks.size(); i != e; ++i) {
626 BasicBlock *BB = DFBlocks[i].second;
627 if (QueuePhiNode(BB, AllocaNum, CurrentVersion, InsertedPHINodes))
628 Info.DefiningBlocks.push_back(BB);
629 }
630 DFBlocks.clear();
Chris Lattner0ec8df32007-08-04 21:14:29 +0000631 }
632}
633
634
Chris Lattner5dd75b42007-08-04 01:47:41 +0000635/// RewriteSingleStoreAlloca - If there is only a single store to this value,
636/// replace any loads of it that are directly dominated by the definition with
637/// the value stored.
638void PromoteMem2Reg::RewriteSingleStoreAlloca(AllocaInst *AI,
639 AllocaInfo &Info) {
Chris Lattnerb776a332007-08-04 02:15:24 +0000640 StoreInst *OnlyStore = Info.OnlyStore;
Chris Lattnerd0458e52007-08-04 02:32:22 +0000641 bool StoringGlobalVal = !isa<Instruction>(OnlyStore->getOperand(0));
Chris Lattnerb776a332007-08-04 02:15:24 +0000642
Chris Lattner5dd75b42007-08-04 01:47:41 +0000643 // Be aware of loads before the store.
Chris Lattnerc3f6ea82007-08-04 02:21:22 +0000644 SmallPtrSet<BasicBlock*, 32> ProcessedBlocks;
Chris Lattner5dd75b42007-08-04 01:47:41 +0000645 for (unsigned i = 0, e = Info.UsingBlocks.size(); i != e; ++i) {
Chris Lattner5dd75b42007-08-04 01:47:41 +0000646 BasicBlock *UseBlock = Info.UsingBlocks[i];
Chris Lattnerd0458e52007-08-04 02:32:22 +0000647
648 // If we already processed this block, don't reprocess it.
649 if (!ProcessedBlocks.insert(UseBlock)) {
650 Info.UsingBlocks[i] = Info.UsingBlocks.back();
651 Info.UsingBlocks.pop_back();
652 --i; --e;
653 continue;
654 }
655
656 // If the store dominates the block and if we haven't processed it yet,
657 // do so now. We can't handle the case where the store doesn't dominate a
658 // block because there may be a path between the store and the use, but we
659 // may need to insert phi nodes to handle dominance properly.
Chris Lattnerc69e4912007-08-04 02:45:02 +0000660 if (!StoringGlobalVal && !dominates(OnlyStore->getParent(), UseBlock))
Chris Lattnerb776a332007-08-04 02:15:24 +0000661 continue;
Chris Lattner5dd75b42007-08-04 01:47:41 +0000662
663 // If the use and store are in the same block, do a quick scan to
664 // verify that there are no uses before the store.
Chris Lattnerb776a332007-08-04 02:15:24 +0000665 if (UseBlock == OnlyStore->getParent()) {
Chris Lattner5dd75b42007-08-04 01:47:41 +0000666 BasicBlock::iterator I = UseBlock->begin();
Chris Lattnerb776a332007-08-04 02:15:24 +0000667 for (; &*I != OnlyStore; ++I) { // scan block for store.
Chris Lattner5dd75b42007-08-04 01:47:41 +0000668 if (isa<LoadInst>(I) && I->getOperand(0) == AI)
669 break;
670 }
Chris Lattnerd0458e52007-08-04 02:32:22 +0000671 if (&*I != OnlyStore)
Chris Lattnerc69e4912007-08-04 02:45:02 +0000672 continue; // Do not promote the uses of this in this block.
Chris Lattner5dd75b42007-08-04 01:47:41 +0000673 }
674
675 // Otherwise, if this is a different block or if all uses happen
676 // after the store, do a simple linear scan to replace loads with
677 // the stored value.
Chris Lattnerc3f6ea82007-08-04 02:21:22 +0000678 for (BasicBlock::iterator I = UseBlock->begin(), E = UseBlock->end();
Chris Lattner5dd75b42007-08-04 01:47:41 +0000679 I != E; ) {
680 if (LoadInst *LI = dyn_cast<LoadInst>(I++)) {
681 if (LI->getOperand(0) == AI) {
Chris Lattnerb776a332007-08-04 02:15:24 +0000682 LI->replaceAllUsesWith(OnlyStore->getOperand(0));
Chris Lattner5dd75b42007-08-04 01:47:41 +0000683 if (AST && isa<PointerType>(LI->getType()))
684 AST->deleteValue(LI);
685 LI->eraseFromParent();
686 }
687 }
688 }
689
690 // Finally, remove this block from the UsingBlock set.
691 Info.UsingBlocks[i] = Info.UsingBlocks.back();
Chris Lattnerb776a332007-08-04 02:15:24 +0000692 Info.UsingBlocks.pop_back();
Chris Lattner5dd75b42007-08-04 01:47:41 +0000693 --i; --e;
694 }
695}
696
697
Chris Lattnere47f78e2004-02-03 22:34:12 +0000698/// PromoteLocallyUsedAlloca - Many allocas are only used within a single basic
699/// block. If this is the case, avoid traversing the CFG and inserting a lot of
700/// potentially useless PHI nodes by just performing a single linear pass over
701/// the basic block using the Alloca.
702///
Chris Lattner6cfd1eb2005-06-30 07:29:44 +0000703/// If we cannot promote this alloca (because it is read before it is written),
704/// return true. This is necessary in cases where, due to control flow, the
705/// alloca is potentially undefined on some control flow paths. e.g. code like
706/// this is potentially correct:
707///
708/// for (...) { if (c) { A = undef; undef = B; } }
709///
710/// ... so long as A is not used before undef is set.
711///
712bool PromoteMem2Reg::PromoteLocallyUsedAlloca(BasicBlock *BB, AllocaInst *AI) {
Chris Lattner24011be2003-10-05 20:54:03 +0000713 assert(!AI->use_empty() && "There are no uses of the alloca!");
Chris Lattner7fecc2e2004-02-03 22:00:33 +0000714
715 // Handle degenerate cases quickly.
716 if (AI->hasOneUse()) {
717 Instruction *U = cast<Instruction>(AI->use_back());
718 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
719 // Must be a load of uninitialized value.
Chris Lattnerb20724d2004-10-16 18:10:06 +0000720 LI->replaceAllUsesWith(UndefValue::get(AI->getAllocatedType()));
Chris Lattner62e29b52004-09-15 01:02:54 +0000721 if (AST && isa<PointerType>(LI->getType()))
722 AST->deleteValue(LI);
Chris Lattner7fecc2e2004-02-03 22:00:33 +0000723 } else {
724 // Otherwise it must be a store which is never read.
725 assert(isa<StoreInst>(U));
726 }
727 BB->getInstList().erase(U);
728 } else {
Chris Lattnerb20724d2004-10-16 18:10:06 +0000729 // Uses of the uninitialized memory location shall get undef.
Chris Lattner6cfd1eb2005-06-30 07:29:44 +0000730 Value *CurVal = 0;
Misha Brukmanfd939082005-04-21 23:48:37 +0000731
Chris Lattner7fecc2e2004-02-03 22:00:33 +0000732 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
733 Instruction *Inst = I++;
734 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
735 if (LI->getOperand(0) == AI) {
Chris Lattner6cfd1eb2005-06-30 07:29:44 +0000736 if (!CurVal) return true; // Could not locally promote!
737
Chris Lattnere47f78e2004-02-03 22:34:12 +0000738 // Loads just returns the "current value"...
Chris Lattner7fecc2e2004-02-03 22:00:33 +0000739 LI->replaceAllUsesWith(CurVal);
Chris Lattner62e29b52004-09-15 01:02:54 +0000740 if (AST && isa<PointerType>(LI->getType()))
741 AST->deleteValue(LI);
Chris Lattner7fecc2e2004-02-03 22:00:33 +0000742 BB->getInstList().erase(LI);
743 }
744 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
745 if (SI->getOperand(1) == AI) {
Chris Lattnere47f78e2004-02-03 22:34:12 +0000746 // Store updates the "current value"...
Chris Lattner7fecc2e2004-02-03 22:00:33 +0000747 CurVal = SI->getOperand(0);
748 BB->getInstList().erase(SI);
749 }
Chris Lattner24011be2003-10-05 20:54:03 +0000750 }
751 }
752 }
753
754 // After traversing the basic block, there should be no more uses of the
Chris Lattner7a5745b2007-08-04 20:01:43 +0000755 // alloca: remove it now.
Chris Lattner24011be2003-10-05 20:54:03 +0000756 assert(AI->use_empty() && "Uses of alloca from more than one BB??");
Chris Lattner62e29b52004-09-15 01:02:54 +0000757 if (AST) AST->deleteValue(AI);
Chris Lattner7a5745b2007-08-04 20:01:43 +0000758 AI->eraseFromParent();
Chris Lattnerbbe10402007-08-04 01:41:18 +0000759
760 ++NumLocalPromoted;
Chris Lattner6cfd1eb2005-06-30 07:29:44 +0000761 return false;
Chris Lattner24011be2003-10-05 20:54:03 +0000762}
Cameron Buschardt98a37c22002-03-27 23:17:37 +0000763
Chris Lattnere47f78e2004-02-03 22:34:12 +0000764/// PromoteLocallyUsedAllocas - This method is just like
765/// PromoteLocallyUsedAlloca, except that it processes multiple alloca
766/// instructions in parallel. This is important in cases where we have large
767/// basic blocks, as we don't want to rescan the entire basic block for each
768/// alloca which is locally used in it (which might be a lot).
769void PromoteMem2Reg::
770PromoteLocallyUsedAllocas(BasicBlock *BB, const std::vector<AllocaInst*> &AIs) {
Chris Lattner59a28372007-08-04 19:52:20 +0000771 DenseMap<AllocaInst*, Value*> CurValues;
Chris Lattnere47f78e2004-02-03 22:34:12 +0000772 for (unsigned i = 0, e = AIs.size(); i != e; ++i)
773 CurValues[AIs[i]] = 0; // Insert with null value
774
775 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
776 Instruction *Inst = I++;
777 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
778 // Is this a load of an alloca we are tracking?
779 if (AllocaInst *AI = dyn_cast<AllocaInst>(LI->getOperand(0))) {
Chris Lattner59a28372007-08-04 19:52:20 +0000780 DenseMap<AllocaInst*, Value*>::iterator AIt = CurValues.find(AI);
Chris Lattnere47f78e2004-02-03 22:34:12 +0000781 if (AIt != CurValues.end()) {
Chris Lattner6cfd1eb2005-06-30 07:29:44 +0000782 // If loading an uninitialized value, allow the inter-block case to
783 // handle it. Due to control flow, this might actually be ok.
784 if (AIt->second == 0) { // Use of locally uninitialized value??
785 RetryList.push_back(AI); // Retry elsewhere.
786 CurValues.erase(AIt); // Stop tracking this here.
787 if (CurValues.empty()) return;
788 } else {
789 // Loads just returns the "current value"...
790 LI->replaceAllUsesWith(AIt->second);
791 if (AST && isa<PointerType>(LI->getType()))
792 AST->deleteValue(LI);
793 BB->getInstList().erase(LI);
794 }
Chris Lattnere47f78e2004-02-03 22:34:12 +0000795 }
796 }
797 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
798 if (AllocaInst *AI = dyn_cast<AllocaInst>(SI->getOperand(1))) {
Chris Lattner59a28372007-08-04 19:52:20 +0000799 DenseMap<AllocaInst*, Value*>::iterator AIt = CurValues.find(AI);
Chris Lattnere47f78e2004-02-03 22:34:12 +0000800 if (AIt != CurValues.end()) {
801 // Store updates the "current value"...
802 AIt->second = SI->getOperand(0);
Chris Lattner4f63e762007-08-04 02:38:38 +0000803 SI->eraseFromParent();
Chris Lattnere47f78e2004-02-03 22:34:12 +0000804 }
805 }
806 }
807 }
Chris Lattner7a5745b2007-08-04 20:01:43 +0000808
809 // At the end of the block scan, all allocas in CurValues are dead.
810 for (DenseMap<AllocaInst*, Value*>::iterator I = CurValues.begin(),
811 E = CurValues.end(); I != E; ++I) {
812 AllocaInst *AI = I->first;
813 assert(AI->use_empty() && "Uses of alloca from more than one BB??");
814 if (AST) AST->deleteValue(AI);
815 AI->eraseFromParent();
816 }
817
818 NumLocalPromoted += CurValues.size();
Chris Lattnere47f78e2004-02-03 22:34:12 +0000819}
820
821
822
Chris Lattner9f4eb012002-04-28 18:27:55 +0000823// QueuePhiNode - queues a phi-node to be added to a basic-block for a specific
824// Alloca returns true if there wasn't already a phi-node for that variable
825//
Chris Lattner3c881cb2003-10-05 04:33:22 +0000826bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo,
Chris Lattner69091be2003-10-05 22:19:20 +0000827 unsigned &Version,
Chris Lattner6a1a28d2007-02-05 23:11:37 +0000828 SmallPtrSet<PHINode*, 16> &InsertedPHINodes) {
Chris Lattner62e29b52004-09-15 01:02:54 +0000829 // Look up the basic-block in question.
Chris Lattnerdfb22c32007-02-07 01:15:04 +0000830 PHINode *&PN = NewPhiNodes[std::make_pair(BB, AllocaNo)];
Cameron Buschardt98a37c22002-03-27 23:17:37 +0000831
Chris Lattner9f4eb012002-04-28 18:27:55 +0000832 // If the BB already has a phi node added for the i'th alloca then we're done!
Chris Lattnerdfb22c32007-02-07 01:15:04 +0000833 if (PN) return false;
Cameron Buschardt98a37c22002-03-27 23:17:37 +0000834
Chris Lattner1d608ab2002-09-10 22:38:47 +0000835 // Create a PhiNode using the dereferenced type... and add the phi-node to the
Chris Lattner393689a2003-04-18 19:25:22 +0000836 // BasicBlock.
Chris Lattnerdfb22c32007-02-07 01:15:04 +0000837 PN = new PHINode(Allocas[AllocaNo]->getAllocatedType(),
838 Allocas[AllocaNo]->getName() + "." +
839 utostr(Version++), BB->begin());
Chris Lattnerf12f8de2007-08-04 22:50:14 +0000840 ++NumPHIInsert;
Chris Lattnerdfb22c32007-02-07 01:15:04 +0000841 PhiToAllocaMap[PN] = AllocaNo;
Chris Lattnere7b653d2007-08-04 20:24:50 +0000842 PN->reserveOperandSpace(getNumPreds(BB));
Chris Lattnerdfb22c32007-02-07 01:15:04 +0000843
Chris Lattner62e29b52004-09-15 01:02:54 +0000844 InsertedPHINodes.insert(PN);
845
846 if (AST && isa<PointerType>(PN->getType()))
847 AST->copyValue(PointerAllocaValues[AllocaNo], PN);
848
Chris Lattner9f4eb012002-04-28 18:27:55 +0000849 return true;
Cameron Buschardt98a37c22002-03-27 23:17:37 +0000850}
851
Chris Lattner69091be2003-10-05 22:19:20 +0000852
853// RenamePass - Recursively traverse the CFG of the function, renaming loads and
854// stores to the allocas which we are promoting. IncomingVals indicates what
855// value each Alloca contains on exit from the predecessor block Pred.
856//
Chris Lattnerd99bf492003-02-22 23:57:48 +0000857void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
Chris Lattner483ce142007-08-04 01:19:38 +0000858 RenamePassData::ValVector &IncomingVals,
Chris Lattnerac4aa4b2007-08-04 01:04:40 +0000859 std::vector<RenamePassData> &Worklist) {
Chris Lattner1e76af32007-08-04 20:40:27 +0000860NextIteration:
Chris Lattnerdfb22c32007-02-07 01:15:04 +0000861 // If we are inserting any phi nodes into this BB, they will already be in the
862 // block.
863 if (PHINode *APN = dyn_cast<PHINode>(BB->begin())) {
864 // Pred may have multiple edges to BB. If so, we want to add N incoming
865 // values to each PHI we are inserting on the first time we see the edge.
866 // Check to see if APN already has incoming values from Pred. This also
867 // prevents us from modifying PHI nodes that are not currently being
868 // inserted.
869 bool HasPredEntries = false;
870 for (unsigned i = 0, e = APN->getNumIncomingValues(); i != e; ++i) {
871 if (APN->getIncomingBlock(i) == Pred) {
872 HasPredEntries = true;
873 break;
Chris Lattnerc8789cb2003-04-25 00:54:58 +0000874 }
Chris Lattnerdfb22c32007-02-07 01:15:04 +0000875 }
876
877 // If we have PHI nodes to update, compute the number of edges from Pred to
878 // BB.
879 if (!HasPredEntries) {
880 TerminatorInst *PredTerm = Pred->getTerminator();
881 unsigned NumEdges = 0;
882 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
883 if (PredTerm->getSuccessor(i) == BB)
884 ++NumEdges;
885 }
886 assert(NumEdges && "Must be at least one edge from Pred to BB!");
887
888 // Add entries for all the phis.
889 BasicBlock::iterator PNI = BB->begin();
890 do {
891 unsigned AllocaNo = PhiToAllocaMap[APN];
892
893 // Add N incoming values to the PHI node.
894 for (unsigned i = 0; i != NumEdges; ++i)
895 APN->addIncoming(IncomingVals[AllocaNo], Pred);
896
897 // The currently active variable for this block is now the PHI.
898 IncomingVals[AllocaNo] = APN;
899
900 // Get the next phi node.
901 ++PNI;
902 APN = dyn_cast<PHINode>(PNI);
903 if (APN == 0) break;
904
905 // Verify it doesn't already have entries for Pred. If it does, it is
906 // not being inserted by this mem2reg invocation.
907 HasPredEntries = false;
908 for (unsigned i = 0, e = APN->getNumIncomingValues(); i != e; ++i) {
909 if (APN->getIncomingBlock(i) == Pred) {
910 HasPredEntries = true;
911 break;
912 }
913 }
914 } while (!HasPredEntries);
915 }
Chris Lattner9157f042003-10-05 02:37:36 +0000916 }
Chris Lattnerdfb22c32007-02-07 01:15:04 +0000917
918 // Don't revisit blocks.
919 if (!Visited.insert(BB)) return;
Chris Lattner9f4eb012002-04-28 18:27:55 +0000920
Chris Lattner521c16a2003-10-05 03:45:44 +0000921 for (BasicBlock::iterator II = BB->begin(); !isa<TerminatorInst>(II); ) {
Chris Lattner0fa15712003-10-05 01:52:53 +0000922 Instruction *I = II++; // get the instruction, increment iterator
Chris Lattner9f4eb012002-04-28 18:27:55 +0000923
924 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner1e76af32007-08-04 20:40:27 +0000925 AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand());
926 if (!Src) continue;
927
928 std::map<AllocaInst*, unsigned>::iterator AI = AllocaLookup.find(Src);
929 if (AI == AllocaLookup.end()) continue;
Chris Lattner9f4eb012002-04-28 18:27:55 +0000930
Chris Lattner1e76af32007-08-04 20:40:27 +0000931 Value *V = IncomingVals[AI->second];
932
933 // Anything using the load now uses the current value.
934 LI->replaceAllUsesWith(V);
935 if (AST && isa<PointerType>(LI->getType()))
936 AST->deleteValue(LI);
937 BB->getInstList().erase(LI);
Chris Lattner9f4eb012002-04-28 18:27:55 +0000938 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattnercc139de2003-02-22 22:25:17 +0000939 // Delete this instruction and mark the name as the current holder of the
Chris Lattner9f4eb012002-04-28 18:27:55 +0000940 // value
Chris Lattner1e76af32007-08-04 20:40:27 +0000941 AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand());
942 if (!Dest) continue;
943
944 std::map<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest);
945 if (ai == AllocaLookup.end())
946 continue;
947
948 // what value were we writing?
949 IncomingVals[ai->second] = SI->getOperand(0);
950 BB->getInstList().erase(SI);
Chris Lattner9f4eb012002-04-28 18:27:55 +0000951 }
952 }
Chris Lattner521c16a2003-10-05 03:45:44 +0000953
Chris Lattner1e76af32007-08-04 20:40:27 +0000954 // 'Recurse' to our successors.
Chris Lattner521c16a2003-10-05 03:45:44 +0000955 TerminatorInst *TI = BB->getTerminator();
Chris Lattner1e76af32007-08-04 20:40:27 +0000956 unsigned NumSuccs = TI->getNumSuccessors();
957 if (NumSuccs == 0) return;
958
959 // Add all-but-one successor to the worklist.
960 for (unsigned i = 0; i != NumSuccs-1; i++)
Chris Lattnerac4aa4b2007-08-04 01:04:40 +0000961 Worklist.push_back(RenamePassData(TI->getSuccessor(i), BB, IncomingVals));
Chris Lattner1e76af32007-08-04 20:40:27 +0000962
963 // Handle the last successor without using the worklist. This allows us to
964 // handle unconditional branches directly, for example.
965 Pred = BB;
966 BB = TI->getSuccessor(NumSuccs-1);
967 goto NextIteration;
Chris Lattnerd3db0222002-02-12 17:16:22 +0000968}
Cameron Buschardtb1be0612002-03-27 23:28:40 +0000969
Chris Lattnerd99bf492003-02-22 23:57:48 +0000970/// PromoteMemToReg - Promote the specified list of alloca instructions into
971/// scalar registers, inserting PHI nodes as appropriate. This function makes
972/// use of DominanceFrontier information. This function does not modify the CFG
973/// of the function at all. All allocas must be from the same function.
974///
Chris Lattner62e29b52004-09-15 01:02:54 +0000975/// If AST is specified, the specified tracker is updated to reflect changes
976/// made to the IR.
977///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000978void llvm::PromoteMemToReg(const std::vector<AllocaInst*> &Allocas,
Devang Patel326821e2007-06-07 21:57:03 +0000979 DominatorTree &DT, DominanceFrontier &DF,
Devang Patel68c01b32007-04-25 18:32:35 +0000980 AliasSetTracker *AST) {
Chris Lattner0fa15712003-10-05 01:52:53 +0000981 // If there is nothing to do, bail out...
982 if (Allocas.empty()) return;
Chris Lattner6cfd1eb2005-06-30 07:29:44 +0000983
Chris Lattner40b65552007-02-05 21:58:48 +0000984 SmallVector<AllocaInst*, 16> RetryList;
Devang Patel326821e2007-06-07 21:57:03 +0000985 PromoteMem2Reg(Allocas, RetryList, DT, DF, AST).run();
Chris Lattner6cfd1eb2005-06-30 07:29:44 +0000986
987 // PromoteMem2Reg may not have been able to promote all of the allocas in one
988 // pass, run it again if needed.
Chris Lattner40b65552007-02-05 21:58:48 +0000989 std::vector<AllocaInst*> NewAllocas;
Chris Lattner6cfd1eb2005-06-30 07:29:44 +0000990 while (!RetryList.empty()) {
991 // If we need to retry some allocas, this is due to there being no store
992 // before a read in a local block. To counteract this, insert a store of
993 // undef into the alloca right after the alloca itself.
994 for (unsigned i = 0, e = RetryList.size(); i != e; ++i) {
995 BasicBlock::iterator BBI = RetryList[i];
Jeff Cohen00b168892005-07-27 06:12:32 +0000996
Chris Lattner6cfd1eb2005-06-30 07:29:44 +0000997 new StoreInst(UndefValue::get(RetryList[i]->getAllocatedType()),
998 RetryList[i], ++BBI);
999 }
1000
Chris Lattner40b65552007-02-05 21:58:48 +00001001 NewAllocas.assign(RetryList.begin(), RetryList.end());
1002 RetryList.clear();
Devang Patel326821e2007-06-07 21:57:03 +00001003 PromoteMem2Reg(NewAllocas, RetryList, DT, DF, AST).run();
Chris Lattner40b65552007-02-05 21:58:48 +00001004 NewAllocas.clear();
Chris Lattner6cfd1eb2005-06-30 07:29:44 +00001005 }
Cameron Buschardtb1be0612002-03-27 23:28:40 +00001006}